wind-agent-cli 1.37.2 → 1.37.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (374) hide show
  1. package/LICENSE +718 -718
  2. package/README.md +1 -1
  3. package/dist/api-docs.html +901 -901
  4. package/dist/assets/{CodeEditor-B2Wf7Fg0.js → CodeEditor-BqmxpZ_D.js} +1 -1
  5. package/dist/assets/{FileTree-N2IkkHlv.js → FileTree-DLE7Ioai.js} +1 -1
  6. package/dist/assets/{GitPanel-DZCeuFZ2.js → GitPanel-f8RMRa8D.js} +1 -1
  7. package/dist/assets/{MarkdownPreview-C0tqYnVu.js → MarkdownPreview-93h_1tJa.js} +1 -1
  8. package/dist/assets/{PluginTabContent-Bnuf-fb8.js → PluginTabContent-DU1jjkXP.js} +1 -1
  9. package/dist/assets/{Shell-BfFnMZ-f.js → Shell-CN_2MRIM.js} +1 -1
  10. package/dist/assets/{StandaloneShell-QmyYwNAl.js → StandaloneShell-D0avS8UE.js} +1 -1
  11. package/dist/assets/{TaskMasterPanel-fMsmvN9L.js → TaskMasterPanel-Cpf1Q5Ph.js} +3 -3
  12. package/dist/assets/{abnfDiagram-N423BO3Z-DjPU7HLs.js → abnfDiagram-N423BO3Z-p3aJIm4T.js} +1 -1
  13. package/dist/assets/{arc-Pdq6Tvr3.js → arc-CTeud6Fl.js} +1 -1
  14. package/dist/assets/{architectureDiagram-T3A2C74G-D0JnT0Vh.js → architectureDiagram-T3A2C74G-CG7kRCJU.js} +1 -1
  15. package/dist/assets/{blockDiagram-VBNYF7ZC-DpaEf3mv.js → blockDiagram-VBNYF7ZC-oSjQ1SgE.js} +1 -1
  16. package/dist/assets/{c4Diagram-5PPSVZJV-MpqlPGFi.js → c4Diagram-5PPSVZJV-RkzF0DJV.js} +1 -1
  17. package/dist/assets/channel-BfQbarn9.js +1 -0
  18. package/dist/assets/{chunk-2GRJ4B5K-DoSdNo8u.js → chunk-2GRJ4B5K-B07uZ07O.js} +1 -1
  19. package/dist/assets/{chunk-2Q5K7J3B-CE7I3uMn.js → chunk-2Q5K7J3B-DNSfO7xS.js} +1 -1
  20. package/dist/assets/{chunk-5RXB4S5H-B4UQ8snD.js → chunk-5RXB4S5H-BTeYcgyb.js} +1 -1
  21. package/dist/assets/{chunk-5VM5RSS4-B55XgqHZ.js → chunk-5VM5RSS4-B7vZV0zC.js} +1 -1
  22. package/dist/assets/{chunk-6Q2QTUOP-BS1KpefW.js → chunk-6Q2QTUOP-DuS_xUGG.js} +1 -1
  23. package/dist/assets/{chunk-GF5L2VYU-DkEPedJP.js → chunk-GF5L2VYU-CKLZ3iVD.js} +1 -1
  24. package/dist/assets/{chunk-JWPE2WC7-DOtkNhMm.js → chunk-JWPE2WC7-DD2hcXvs.js} +1 -1
  25. package/dist/assets/{chunk-KBJHAD2P-BXLjviqM.js → chunk-KBJHAD2P-Cz-l38qp.js} +1 -1
  26. package/dist/assets/{chunk-RYQCIY6F-C50fjNNz.js → chunk-RYQCIY6F-DGFIU1YM.js} +1 -1
  27. package/dist/assets/{chunk-XXDRQBXY-QBYqCkb7.js → chunk-XXDRQBXY-CmfzoYFl.js} +1 -1
  28. package/dist/assets/classDiagram-JCYQIIEL-Bpfe3kq7.js +1 -0
  29. package/dist/assets/classDiagram-v2-OCEON4UE-Bpfe3kq7.js +1 -0
  30. package/dist/assets/{code-xml-VK1YfShP.js → code-xml-CLpHzEOP.js} +1 -1
  31. package/dist/assets/{cose-bilkent-JH36ORCC-DrVTo1Nh.js → cose-bilkent-JH36ORCC-DlFcLXCB.js} +1 -1
  32. package/dist/assets/{cynefin-VYW2F7L2-DnJa_OlQ.js → cynefin-VYW2F7L2-P1HecReO.js} +1 -1
  33. package/dist/assets/{cynefinDiagram-MW4NZA55-CCxBjw9E.js → cynefinDiagram-MW4NZA55-COgduz5P.js} +1 -1
  34. package/dist/assets/{dagre-VZM6K2ZE-C_GvE4lu.js → dagre-VZM6K2ZE-Bbb-siGp.js} +1 -1
  35. package/dist/assets/{diagram-7IWD3JNH-pFzs9HEu.js → diagram-7IWD3JNH-9CWGFMYR.js} +1 -1
  36. package/dist/assets/{diagram-B4RE2ZJO-CcehQC7x.js → diagram-B4RE2ZJO-TWK59T6V.js} +1 -1
  37. package/dist/assets/{diagram-LBJQPF4R-hfKcrrxe.js → diagram-LBJQPF4R-ErMC9yaa.js} +1 -1
  38. package/dist/assets/{diagram-Q27KOJAE-C1semJfK.js → diagram-Q27KOJAE-Dt_-C7hV.js} +1 -1
  39. package/dist/assets/{diagram-UB23O5K3-57hvXQXO.js → diagram-UB23O5K3-BJ1DnRAF.js} +1 -1
  40. package/dist/assets/{ebnfDiagram-BXEA7PRR-9KIAlAVw.js → ebnfDiagram-BXEA7PRR-CE1YaQ9s.js} +1 -1
  41. package/dist/assets/{erDiagram-JOGREHBK-B7OzJ767.js → erDiagram-JOGREHBK-Bqk7N9aY.js} +1 -1
  42. package/dist/assets/{flowDiagram-UKHOOZJN-CJV8fQPR.js → flowDiagram-UKHOOZJN-DEr2II5V.js} +1 -1
  43. package/dist/assets/{ganttDiagram-PKOTCBZU-CbMNWWQu.js → ganttDiagram-PKOTCBZU-CWYAUeYN.js} +1 -1
  44. package/dist/assets/{gitGraphDiagram-DS77QQ5N-I_vZ5waO.js → gitGraphDiagram-DS77QQ5N-tdEcEIM6.js} +1 -1
  45. package/dist/assets/{index-ZHwIojzi.js → index-B-sTfSZq.js} +1 -1
  46. package/dist/assets/{index-GFhXZyl2.js → index-BSe3UiFA.js} +1 -1
  47. package/dist/assets/{index-DFnVoqpx.js → index-B_FDMWar.js} +5 -5
  48. package/dist/assets/{index-DlSeAkw_.js → index-CWJtg2pR.js} +1 -1
  49. package/dist/assets/{infoDiagram-6WML65LV-Dh20Tsbq.js → infoDiagram-6WML65LV-A3IqRUnO.js} +1 -1
  50. package/dist/assets/{ishikawaDiagram-WSZJBQD7-DH2Sm3ko.js → ishikawaDiagram-WSZJBQD7-B2uL6bkK.js} +1 -1
  51. package/dist/assets/{journeyDiagram-NVQOT4AX-BNFQqlVu.js → journeyDiagram-NVQOT4AX-D9JB-hRW.js} +1 -1
  52. package/dist/assets/{kanban-definition-27J2QSJJ-B3iL0ztJ.js → kanban-definition-27J2QSJJ-DmlgiV7K.js} +1 -1
  53. package/dist/assets/{linear-Cwe9dEKA.js → linear-Ct_eoJQk.js} +1 -1
  54. package/dist/assets/{mermaid.core-BYRQSshi.js → mermaid.core-CQ698HNn.js} +5 -5
  55. package/dist/assets/{mindmap-definition-FAOFIHXS-BgfBYMzr.js → mindmap-definition-FAOFIHXS-DGtMgQhf.js} +1 -1
  56. package/dist/assets/{pegDiagram-VL7TDLO6-CNYpECr8.js → pegDiagram-VL7TDLO6-CO6vP4n9.js} +1 -1
  57. package/dist/assets/{pieDiagram-7S7Q4E2Y-DeSrxc4I.js → pieDiagram-7S7Q4E2Y-DMkt_Zfr.js} +1 -1
  58. package/dist/assets/{quadrantDiagram-CIZ2JOQS-BXVVQsa6.js → quadrantDiagram-CIZ2JOQS-DgNxRz6t.js} +1 -1
  59. package/dist/assets/{railroadDiagram-AXF67PYL-JTroIW8F.js → railroadDiagram-AXF67PYL-DKz9UqA9.js} +1 -1
  60. package/dist/assets/{requirementDiagram-LRYGKXZP-C1Z_inLz.js → requirementDiagram-LRYGKXZP-L84XyGgV.js} +1 -1
  61. package/dist/assets/{sankeyDiagram-W5VNT64P-DCJgKFUk.js → sankeyDiagram-W5VNT64P-CQqWbJ3j.js} +1 -1
  62. package/dist/assets/{sequenceDiagram-SI44F4Z6-D8Wrx5Vc.js → sequenceDiagram-SI44F4Z6--tnzS2tb.js} +1 -1
  63. package/dist/assets/{sizeCapture-X5ZJPWSS-CXqD68vD.js → sizeCapture-X5ZJPWSS-DujwEOtm.js} +1 -1
  64. package/dist/assets/{stateDiagram-OKZ733FA-CF0Ekqjo.js → stateDiagram-OKZ733FA-BK3TcZY2.js} +1 -1
  65. package/dist/assets/stateDiagram-v2-UEYNNEHI-_medyomK.js +1 -0
  66. package/dist/assets/{swimlanes-SLNWSIFB-DVIax_k4.js → swimlanes-SLNWSIFB-naX-Uv1B.js} +2 -2
  67. package/dist/assets/swimlanesDiagram-ULZ7WXOC-DstIv3TC.js +8 -0
  68. package/dist/assets/{timeline-definition-Z64GVDOM-DSqk3ApG.js → timeline-definition-Z64GVDOM-C-vP_ddU.js} +1 -1
  69. package/dist/assets/{vennDiagram-T6HMQDX7-DNbTqyG5.js → vennDiagram-T6HMQDX7-DN-I7o-7.js} +1 -1
  70. package/dist/assets/{wardleyDiagram-T6FBY63Y-BNCpsFZV.js → wardleyDiagram-T6FBY63Y-Db9dsaXv.js} +1 -1
  71. package/dist/assets/{xychartDiagram-ELKLHX3M-XsVZphHr.js → xychartDiagram-ELKLHX3M-DE6OxW_p.js} +1 -1
  72. package/dist/clear-cache.html +85 -85
  73. package/dist/convert-icons.md +52 -52
  74. package/dist/favicon.svg +8 -8
  75. package/dist/generate-icons.js +48 -48
  76. package/dist/icons/codex-white.svg +3 -3
  77. package/dist/icons/codex.svg +3 -3
  78. package/dist/icons/cursor-white.svg +11 -11
  79. package/dist/icons/icon-128x128.svg +11 -11
  80. package/dist/icons/icon-144x144.svg +11 -11
  81. package/dist/icons/icon-152x152.svg +11 -11
  82. package/dist/icons/icon-192x192.svg +11 -11
  83. package/dist/icons/icon-384x384.svg +11 -11
  84. package/dist/icons/icon-512x512.svg +11 -11
  85. package/dist/icons/icon-72x72.svg +11 -11
  86. package/dist/icons/icon-96x96.svg +11 -11
  87. package/dist/icons/icon-template.svg +11 -11
  88. package/dist/index.html +56 -56
  89. package/dist/logo.svg +17 -17
  90. package/dist/manifest.json +60 -60
  91. package/dist/sw.js +124 -124
  92. package/dist-server/server/modules/cli/cli.service.js +36 -36
  93. package/dist-server/server/modules/cli/sandbox.service.js +38 -38
  94. package/dist-server/server/modules/cli/tests/cli-environment-bootstrap.test.js +74 -74
  95. package/dist-server/server/modules/commands/commands.routes.js +24 -24
  96. package/dist-server/server/modules/database/migrations.js +190 -190
  97. package/dist-server/server/modules/database/repositories/api-keys.js +3 -3
  98. package/dist-server/server/modules/database/repositories/github-tokens.js +2 -2
  99. package/dist-server/server/modules/database/repositories/notification-channel-endpoints.js +28 -28
  100. package/dist-server/server/modules/database/repositories/notification-preferences.js +4 -4
  101. package/dist-server/server/modules/database/repositories/projects.db.js +61 -61
  102. package/dist-server/server/modules/database/repositories/provider-models.js +35 -35
  103. package/dist-server/server/modules/database/repositories/push-subscriptions.js +5 -5
  104. package/dist-server/server/modules/database/repositories/scan-state.db.js +5 -5
  105. package/dist-server/server/modules/database/repositories/sessions.db.js +92 -92
  106. package/dist-server/server/modules/database/schema.js +177 -177
  107. package/dist-server/server/modules/database/tests/provider-models.db.integration.test.js +6 -6
  108. package/dist-server/server/modules/git/git.routes.js +17 -17
  109. package/dist-server/server/modules/providers/list/opencode/opencode-models.provider.js +12 -12
  110. package/dist-server/server/modules/providers/list/opencode/opencode-runtime.provider.js +9 -9
  111. package/dist-server/server/modules/providers/list/opencode/opencode-runtime.provider.test.js +17 -17
  112. package/dist-server/server/modules/providers/list/opencode/opencode-session-synchronizer.provider.js +25 -25
  113. package/dist-server/server/modules/providers/list/opencode/opencode-sessions.provider.js +27 -27
  114. package/dist-server/server/modules/providers/services/provider-token-usage.service.js +9 -9
  115. package/dist-server/server/modules/providers/tests/mcp.test.js +3 -3
  116. package/dist-server/server/modules/providers/tests/opencode-sessions.test.js +96 -96
  117. package/dist-server/server/modules/providers/tests/provider-token-usage.service.test.js +18 -18
  118. package/dist-server/server/modules/taskmaster/taskmaster.routes.js +419 -419
  119. package/electron/cloud.js +260 -260
  120. package/electron/desktopNotifications.js +378 -378
  121. package/electron/desktopWindow.js +766 -766
  122. package/electron/launcher/index.html +14 -14
  123. package/electron/launcher/launcher.css +801 -801
  124. package/electron/launcher/launcher.js +687 -687
  125. package/electron/localServer.js +549 -549
  126. package/electron/main.js +944 -944
  127. package/electron/preload.cjs +60 -60
  128. package/electron/scripts/generate-macos-icon.js +62 -62
  129. package/electron/serverInstaller.js +277 -277
  130. package/electron/tabs.js +87 -87
  131. package/electron/viewHost.js +331 -331
  132. package/package.json +250 -247
  133. package/public/api-docs.html +901 -901
  134. package/scripts/fix-node-pty.js +67 -67
  135. package/scripts/promote-dist-server.mjs +50 -50
  136. package/scripts/release/build-server-bundle.js +176 -176
  137. package/scripts/release/prepare-desktop-app.js +152 -152
  138. package/server/index.ts +399 -399
  139. package/server/load-env.ts +47 -47
  140. package/server/modules/agent/agent.module.ts +52 -52
  141. package/server/modules/agent/agent.routes.ts +1287 -1287
  142. package/server/modules/agent/index.ts +2 -2
  143. package/server/modules/agent/tests/agent.routes.test.ts +205 -205
  144. package/server/modules/assets/assets.routes.ts +150 -150
  145. package/server/modules/assets/index.ts +3 -3
  146. package/server/modules/assets/services/image-assets.service.ts +127 -127
  147. package/server/modules/assets/tests/image-assets.service.test.ts +74 -74
  148. package/server/modules/auth/auth.middleware.ts +163 -163
  149. package/server/modules/auth/auth.module.ts +38 -38
  150. package/server/modules/auth/auth.routes.ts +57 -57
  151. package/server/modules/auth/auth.service.ts +155 -155
  152. package/server/modules/auth/index.ts +9 -9
  153. package/server/modules/auth/tests/auth.service.test.ts +95 -95
  154. package/server/modules/browser-use/browser-use-mcp.routes.ts +120 -120
  155. package/server/modules/browser-use/browser-use-mcp.ts +386 -386
  156. package/server/modules/browser-use/browser-use-runtime.ts +10 -10
  157. package/server/modules/browser-use/browser-use.routes.ts +96 -96
  158. package/server/modules/browser-use/browser-use.service.ts +836 -836
  159. package/server/modules/browser-use/index.ts +11 -11
  160. package/server/modules/browser-use/tests/browser-use.service.test.ts +10 -10
  161. package/server/modules/cli/cli.module.ts +93 -93
  162. package/server/modules/cli/cli.service.ts +248 -248
  163. package/server/modules/cli/cli.ts +19 -19
  164. package/server/modules/cli/index.ts +2 -2
  165. package/server/modules/cli/sandbox.service.ts +398 -398
  166. package/server/modules/cli/tests/cli-environment-bootstrap.test.ts +186 -186
  167. package/server/modules/cli/tests/cli.service.test.ts +86 -86
  168. package/server/modules/cli/tests/sandbox.service.test.ts +58 -58
  169. package/server/modules/commands/commands.module.ts +22 -22
  170. package/server/modules/commands/commands.routes.ts +586 -586
  171. package/server/modules/commands/index.ts +2 -2
  172. package/server/modules/commands/tests/commands.test.ts +109 -109
  173. package/server/modules/database/connection.ts +143 -143
  174. package/server/modules/database/index.ts +17 -17
  175. package/server/modules/database/init-db.ts +17 -17
  176. package/server/modules/database/migrations.ts +515 -515
  177. package/server/modules/database/repositories/api-keys.ts +119 -119
  178. package/server/modules/database/repositories/app-config.ts +53 -53
  179. package/server/modules/database/repositories/credentials.ts +106 -106
  180. package/server/modules/database/repositories/github-tokens.ts +100 -100
  181. package/server/modules/database/repositories/notification-channel-endpoints.ts +153 -153
  182. package/server/modules/database/repositories/notification-preferences.ts +117 -117
  183. package/server/modules/database/repositories/projects.db.ts +196 -196
  184. package/server/modules/database/repositories/provider-models.ts +168 -168
  185. package/server/modules/database/repositories/push-subscriptions.ts +80 -80
  186. package/server/modules/database/repositories/scan-state.db.ts +42 -42
  187. package/server/modules/database/repositories/sessions.db.ts +524 -524
  188. package/server/modules/database/repositories/users.ts +140 -140
  189. package/server/modules/database/repositories/vapid-keys.ts +57 -57
  190. package/server/modules/database/schema.ts +210 -210
  191. package/server/modules/database/tests/projects.db.integration.test.ts +72 -72
  192. package/server/modules/database/tests/provider-models.db.integration.test.ts +125 -125
  193. package/server/modules/database/tests/sessions-provider-mapping.test.ts +109 -109
  194. package/server/modules/database/tests/sessions.db.integration.test.ts +116 -116
  195. package/server/modules/file-tree/file-tree.module.ts +116 -116
  196. package/server/modules/file-tree/file-tree.routes.ts +258 -258
  197. package/server/modules/file-tree/file-tree.service.ts +675 -675
  198. package/server/modules/file-tree/index.ts +2 -2
  199. package/server/modules/file-tree/tests/file-tree.routes.test.ts +157 -157
  200. package/server/modules/file-tree/tests/file-tree.service.test.ts +371 -371
  201. package/server/modules/git/git-branch.service.ts +43 -43
  202. package/server/modules/git/git-parsing.service.ts +66 -66
  203. package/server/modules/git/git.module.ts +22 -22
  204. package/server/modules/git/git.routes.ts +1596 -1596
  205. package/server/modules/git/index.ts +2 -2
  206. package/server/modules/git/tests/git-branch.service.test.ts +60 -60
  207. package/server/modules/git/tests/git-init.routes.test.ts +132 -132
  208. package/server/modules/git/tests/git.test.ts +106 -106
  209. package/server/modules/notifications/index.ts +24 -24
  210. package/server/modules/notifications/notifications.routes.ts +127 -127
  211. package/server/modules/notifications/services/desktop-notification-clients.service.ts +124 -124
  212. package/server/modules/notifications/services/notification-orchestrator.service.js +310 -310
  213. package/server/modules/notifications/tests/notification-orchestrator.integration.test.ts +55 -55
  214. package/server/modules/notifications/vapid-keys.service.ts +38 -38
  215. package/server/modules/notifications/websocket/desktop-notifications-websocket.service.ts +109 -109
  216. package/server/modules/plugins/index.ts +9 -9
  217. package/server/modules/plugins/plugin-process.service.ts +217 -217
  218. package/server/modules/plugins/plugin-registry.service.ts +459 -459
  219. package/server/modules/plugins/plugins.module.ts +33 -33
  220. package/server/modules/plugins/plugins.routes.ts +66 -66
  221. package/server/modules/plugins/plugins.service.ts +147 -147
  222. package/server/modules/plugins/tests/plugins.service.test.ts +32 -32
  223. package/server/modules/projects/index.ts +11 -11
  224. package/server/modules/projects/projects.routes.ts +273 -273
  225. package/server/modules/projects/services/project-clone.service.ts +323 -323
  226. package/server/modules/projects/services/project-delete.service.ts +90 -90
  227. package/server/modules/projects/services/project-management.service.ts +144 -144
  228. package/server/modules/projects/services/project-star.service.ts +78 -78
  229. package/server/modules/projects/services/projects-has-taskmaster.service.ts +248 -248
  230. package/server/modules/projects/services/projects-with-sessions-fetch.service.ts +314 -314
  231. package/server/modules/projects/tests/project-clone.service.test.ts +183 -183
  232. package/server/modules/projects/tests/project-management.service.test.ts +117 -117
  233. package/server/modules/projects/tests/project-star.service.test.ts +123 -123
  234. package/server/modules/projects/tests/projects-has-taskmaster.service.test.ts +105 -105
  235. package/server/modules/providers/README.md +380 -380
  236. package/server/modules/providers/index.ts +10 -10
  237. package/server/modules/providers/list/claude/claude-auth.provider.ts +160 -160
  238. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  239. package/server/modules/providers/list/claude/claude-models.provider.ts +294 -294
  240. package/server/modules/providers/list/claude/claude-runtime.provider.js +1068 -1068
  241. package/server/modules/providers/list/claude/claude-session-synchronizer.provider.ts +203 -203
  242. package/server/modules/providers/list/claude/claude-sessions.provider.ts +684 -684
  243. package/server/modules/providers/list/claude/claude-skills.provider.ts +265 -265
  244. package/server/modules/providers/list/claude/claude.provider.ts +30 -30
  245. package/server/modules/providers/list/codex/codex-auth.provider.ts +100 -100
  246. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  247. package/server/modules/providers/list/codex/codex-models.provider.ts +123 -123
  248. package/server/modules/providers/list/codex/codex-runtime.provider.js +533 -533
  249. package/server/modules/providers/list/codex/codex-session-synchronizer.provider.ts +203 -203
  250. package/server/modules/providers/list/codex/codex-sessions.provider.ts +938 -938
  251. package/server/modules/providers/list/codex/codex-skills.provider.ts +73 -73
  252. package/server/modules/providers/list/codex/codex.provider.ts +28 -28
  253. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +143 -143
  254. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  255. package/server/modules/providers/list/cursor/cursor-models.provider.ts +119 -119
  256. package/server/modules/providers/list/cursor/cursor-runtime.provider.js +385 -385
  257. package/server/modules/providers/list/cursor/cursor-session-synchronizer.provider.ts +159 -159
  258. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +654 -654
  259. package/server/modules/providers/list/cursor/cursor-skills.provider.ts +39 -39
  260. package/server/modules/providers/list/cursor/cursor.provider.ts +30 -30
  261. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +110 -110
  262. package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +228 -228
  263. package/server/modules/providers/list/opencode/opencode-models.provider.ts +203 -203
  264. package/server/modules/providers/list/opencode/opencode-runtime.provider.js +434 -434
  265. package/server/modules/providers/list/opencode/opencode-runtime.provider.test.js +261 -261
  266. package/server/modules/providers/list/opencode/opencode-session-synchronizer.provider.ts +179 -179
  267. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +500 -500
  268. package/server/modules/providers/list/opencode/opencode-skills.provider.ts +78 -78
  269. package/server/modules/providers/list/opencode/opencode.provider.ts +30 -30
  270. package/server/modules/providers/provider.registry.ts +36 -36
  271. package/server/modules/providers/provider.routes.ts +877 -877
  272. package/server/modules/providers/services/mcp.service.ts +109 -109
  273. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  274. package/server/modules/providers/services/provider-capabilities.service.ts +97 -97
  275. package/server/modules/providers/services/provider-models.service.ts +401 -401
  276. package/server/modules/providers/services/provider-runtime.service.ts +108 -108
  277. package/server/modules/providers/services/provider-token-usage.service.ts +357 -357
  278. package/server/modules/providers/services/session-conversations-search.service.ts +1321 -1321
  279. package/server/modules/providers/services/session-synchronizer.service.ts +74 -74
  280. package/server/modules/providers/services/sessions-watcher.service.ts +247 -247
  281. package/server/modules/providers/services/sessions.service.ts +471 -471
  282. package/server/modules/providers/services/skills.service.ts +39 -39
  283. package/server/modules/providers/shared/base/abstract.provider.ts +32 -32
  284. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  285. package/server/modules/providers/shared/skills/skills.provider.ts +287 -287
  286. package/server/modules/providers/tests/claude-auth.test.ts +150 -150
  287. package/server/modules/providers/tests/claude-sessions.test.ts +61 -61
  288. package/server/modules/providers/tests/codex-sessions.test.ts +231 -231
  289. package/server/modules/providers/tests/mcp.test.ts +349 -349
  290. package/server/modules/providers/tests/opencode-models.test.ts +41 -41
  291. package/server/modules/providers/tests/opencode-sessions.test.ts +522 -522
  292. package/server/modules/providers/tests/provider-attachment-history.test.ts +247 -247
  293. package/server/modules/providers/tests/provider-models.service.test.ts +353 -353
  294. package/server/modules/providers/tests/provider-runtime.service.test.ts +138 -138
  295. package/server/modules/providers/tests/provider-token-usage.service.test.ts +186 -186
  296. package/server/modules/providers/tests/provider.routes.test.ts +244 -244
  297. package/server/modules/providers/tests/sessions-details.test.ts +73 -73
  298. package/server/modules/providers/tests/sessions.service.test.ts +127 -127
  299. package/server/modules/providers/tests/skills.test.ts +692 -692
  300. package/server/modules/settings/index.ts +2 -2
  301. package/server/modules/settings/settings.module.ts +50 -50
  302. package/server/modules/settings/settings.routes.ts +51 -51
  303. package/server/modules/settings/settings.service.ts +186 -186
  304. package/server/modules/settings/tests/settings.service.test.ts +54 -54
  305. package/server/modules/system/index.ts +2 -2
  306. package/server/modules/system/system.module.ts +62 -62
  307. package/server/modules/system/system.routes.ts +21 -21
  308. package/server/modules/system/system.service.ts +76 -76
  309. package/server/modules/system/tests/system.service.test.ts +118 -118
  310. package/server/modules/taskmaster/index.ts +2 -2
  311. package/server/modules/taskmaster/taskmaster.module.ts +24 -24
  312. package/server/modules/taskmaster/taskmaster.routes.ts +1482 -1482
  313. package/server/modules/taskmaster/taskmaster.service.ts +132 -132
  314. package/server/modules/taskmaster/tests/taskmaster.routes.test.ts +144 -144
  315. package/server/modules/taskmaster/tests/taskmaster.service.test.ts +97 -97
  316. package/server/modules/user/index.ts +2 -2
  317. package/server/modules/user/tests/user.service.test.ts +61 -61
  318. package/server/modules/user/user.module.ts +58 -58
  319. package/server/modules/user/user.routes.ts +50 -50
  320. package/server/modules/user/user.service.ts +85 -85
  321. package/server/modules/voice/index.ts +2 -2
  322. package/server/modules/voice/tests/voice.service.test.ts +98 -98
  323. package/server/modules/voice/voice.module.ts +47 -47
  324. package/server/modules/voice/voice.routes.ts +113 -113
  325. package/server/modules/voice/voice.service.ts +192 -192
  326. package/server/modules/websocket/README.md +273 -273
  327. package/server/modules/websocket/index.ts +3 -3
  328. package/server/modules/websocket/services/chat-run-registry.service.ts +343 -343
  329. package/server/modules/websocket/services/chat-session-writer.service.ts +145 -145
  330. package/server/modules/websocket/services/chat-websocket.service.ts +425 -425
  331. package/server/modules/websocket/services/plugin-websocket-proxy.service.ts +65 -65
  332. package/server/modules/websocket/services/shell-websocket.service.ts +502 -502
  333. package/server/modules/websocket/services/websocket-auth.service.ts +59 -59
  334. package/server/modules/websocket/services/websocket-server.service.ts +124 -124
  335. package/server/modules/websocket/services/websocket-state.service.ts +16 -16
  336. package/server/modules/websocket/services/websocket-writer.service.ts +38 -38
  337. package/server/modules/websocket/tests/chat-attachment-filter.test.ts +59 -59
  338. package/server/modules/websocket/tests/chat-run-registry.test.ts +282 -282
  339. package/server/modules/websocket/tests/shell-websocket.service.test.ts +100 -100
  340. package/server/modules/websocket/tests/websocket-heartbeat.service.test.ts +78 -78
  341. package/server/modules/worktrees/index.ts +2 -2
  342. package/server/modules/worktrees/services/worktree-create-and-open.service.ts +53 -53
  343. package/server/modules/worktrees/services/worktree-create.service.ts +104 -104
  344. package/server/modules/worktrees/services/worktree-git.service.ts +207 -207
  345. package/server/modules/worktrees/services/worktree-list.service.ts +143 -143
  346. package/server/modules/worktrees/services/worktree-merge.service.ts +157 -157
  347. package/server/modules/worktrees/services/worktree-open.service.ts +85 -85
  348. package/server/modules/worktrees/services/worktree-remove.service.ts +88 -88
  349. package/server/modules/worktrees/tests/worktree-create-and-open.service.test.ts +68 -68
  350. package/server/modules/worktrees/tests/worktree-create.service.test.ts +142 -142
  351. package/server/modules/worktrees/tests/worktree-git.service.test.ts +84 -84
  352. package/server/modules/worktrees/tests/worktree-list.service.test.ts +45 -45
  353. package/server/modules/worktrees/tests/worktree-merge.service.test.ts +213 -213
  354. package/server/modules/worktrees/tests/worktree-open.service.test.ts +122 -122
  355. package/server/modules/worktrees/tests/worktree-remove.service.test.ts +227 -227
  356. package/server/modules/worktrees/tests/worktrees.routes.test.ts +199 -199
  357. package/server/modules/worktrees/worktrees.module.ts +113 -113
  358. package/server/modules/worktrees/worktrees.routes.ts +116 -116
  359. package/server/shared/claude-cli-path.ts +139 -139
  360. package/server/shared/frontmatter.ts +18 -18
  361. package/server/shared/image-attachments.ts +435 -435
  362. package/server/shared/interfaces.ts +179 -179
  363. package/server/shared/tests/claude-cli-path.test.ts +61 -61
  364. package/server/shared/tests/image-attachments.test.ts +353 -353
  365. package/server/shared/tests/slice-tail-page.test.ts +42 -42
  366. package/server/shared/types.ts +1226 -1226
  367. package/server/shared/utils.ts +1161 -1161
  368. package/server/tsconfig.json +40 -40
  369. package/shared/networkHosts.js +22 -22
  370. package/dist/assets/channel-Bm0ZLE4z.js +0 -1
  371. package/dist/assets/classDiagram-JCYQIIEL-DqEOcNxw.js +0 -1
  372. package/dist/assets/classDiagram-v2-OCEON4UE-DqEOcNxw.js +0 -1
  373. package/dist/assets/stateDiagram-v2-UEYNNEHI-DARLpEFJ.js +0 -1
  374. package/dist/assets/swimlanesDiagram-ULZ7WXOC-CrgDgaY8.js +0 -8
@@ -1,684 +1,684 @@
1
- import fs from 'node:fs';
2
- import fsp from 'node:fs/promises';
3
- import path from 'node:path';
4
- import readline from 'node:readline';
5
-
6
- import type { IProviderSessions } from '@/shared/interfaces.js';
7
- import type { AnyRecord, FetchHistoryOptions, FetchHistoryResult, NormalizedMessage } from '@/shared/types.js';
8
- import { parseFilesInputTag } from '@/shared/image-attachments.js';
9
- import { createNormalizedMessage, generateMessageId, readObjectRecord, sliceTailPage } from '@/shared/utils.js';
10
- import { sessionsDb } from '@/modules/database/index.js';
11
-
12
- const PROVIDER = 'claude';
13
-
14
- type ClaudeToolResult = {
15
- content: unknown;
16
- isError: boolean;
17
- subagentTools?: unknown;
18
- toolUseResult?: unknown;
19
- };
20
-
21
- type ClaudeHistoryResult =
22
- | AnyRecord[]
23
- | {
24
- messages?: AnyRecord[];
25
- total?: number;
26
- hasMore?: boolean;
27
- };
28
-
29
- type ClaudeHistoryMessagesResult =
30
- | AnyRecord[]
31
- | {
32
- messages: AnyRecord[];
33
- total: number;
34
- hasMore: boolean;
35
- offset?: number;
36
- limit?: number | null;
37
- };
38
-
39
- async function parseAgentTools(filePath: string): Promise<AnyRecord[]> {
40
- const tools: AnyRecord[] = [];
41
-
42
- try {
43
- const fileStream = fs.createReadStream(filePath);
44
- const rl = readline.createInterface({
45
- input: fileStream,
46
- crlfDelay: Infinity,
47
- });
48
-
49
- for await (const line of rl) {
50
- if (!line.trim()) {
51
- continue;
52
- }
53
-
54
- try {
55
- const entry = JSON.parse(line) as AnyRecord;
56
-
57
- if (entry.message?.role === 'assistant' && Array.isArray(entry.message?.content)) {
58
- for (const part of entry.message.content as AnyRecord[]) {
59
- if (part.type === 'tool_use') {
60
- tools.push({
61
- toolId: part.id,
62
- toolName: part.name,
63
- toolInput: part.input,
64
- timestamp: entry.timestamp,
65
- });
66
- }
67
- }
68
- }
69
-
70
- if (entry.message?.role === 'user' && Array.isArray(entry.message?.content)) {
71
- for (const part of entry.message.content as AnyRecord[]) {
72
- if (part.type !== 'tool_result') {
73
- continue;
74
- }
75
-
76
- const tool = tools.find((candidate) => candidate.toolId === part.tool_use_id);
77
- if (!tool) {
78
- continue;
79
- }
80
-
81
- tool.toolResult = {
82
- content: typeof part.content === 'string'
83
- ? part.content
84
- : Array.isArray(part.content)
85
- ? part.content
86
- .map((contentPart: AnyRecord) => contentPart?.text || '')
87
- .join('\n')
88
- : JSON.stringify(part.content),
89
- isError: Boolean(part.is_error),
90
- };
91
- }
92
- }
93
- } catch {
94
- // Skip malformed lines that can happen during concurrent writes.
95
- }
96
- }
97
- } catch (error) {
98
- const message = error instanceof Error ? error.message : String(error);
99
- console.warn(`Error parsing agent file ${filePath}:`, message);
100
- }
101
-
102
- return tools;
103
- }
104
-
105
- async function getSessionMessages(
106
- sessionId: string,
107
- providerSessionId: string,
108
- limit: number | null,
109
- offset: number,
110
- ): Promise<ClaudeHistoryMessagesResult> {
111
- try {
112
- // The DB row is keyed by the app-facing session id, while the JSONL rows
113
- // on disk carry the provider-native id — both ids are needed here.
114
- const jsonLPath = sessionsDb.getSessionById(sessionId)?.jsonl_path;
115
-
116
- if (!jsonLPath) {
117
- return { messages: [], total: 0, hasMore: false };
118
- }
119
-
120
- const projectDir = path.dirname(jsonLPath);
121
- const files = await fsp.readdir(projectDir);
122
- const agentFiles = files.filter((file) => file.endsWith('.jsonl') && file.startsWith('agent-'));
123
-
124
- const messages: AnyRecord[] = [];
125
- const agentToolsCache = new Map<string, AnyRecord[]>();
126
-
127
- const fileStream = fs.createReadStream(jsonLPath);
128
- const rl = readline.createInterface({
129
- input: fileStream,
130
- crlfDelay: Infinity,
131
- });
132
-
133
- for await (const line of rl) {
134
- if (!line.trim()) {
135
- continue;
136
- }
137
-
138
- try {
139
- const entry = JSON.parse(line) as AnyRecord;
140
- if (entry.sessionId === providerSessionId) {
141
- messages.push(entry);
142
- }
143
- } catch {
144
- // Skip malformed JSONL lines that can happen during concurrent writes.
145
- }
146
- }
147
-
148
- const agentIds = new Set<string>();
149
- for (const message of messages) {
150
- const agentId = message.toolUseResult?.agentId;
151
- if (agentId) {
152
- agentIds.add(String(agentId));
153
- }
154
- }
155
-
156
- for (const agentId of agentIds) {
157
- const agentFileName = `agent-${agentId}.jsonl`;
158
- if (!agentFiles.includes(agentFileName)) {
159
- continue;
160
- }
161
-
162
- const agentFilePath = path.join(projectDir, agentFileName);
163
- const tools = await parseAgentTools(agentFilePath);
164
- agentToolsCache.set(agentId, tools);
165
- }
166
-
167
- for (const message of messages) {
168
- const agentId = message.toolUseResult?.agentId;
169
- if (!agentId) {
170
- continue;
171
- }
172
-
173
- const agentTools = agentToolsCache.get(String(agentId));
174
- if (agentTools && agentTools.length > 0) {
175
- message.subagentTools = agentTools;
176
- }
177
- }
178
-
179
- const sortedMessages = messages.sort(
180
- (a, b) => new Date(a.timestamp || 0).getTime() - new Date(b.timestamp || 0).getTime(),
181
- );
182
- const total = sortedMessages.length;
183
-
184
- if (limit === null) {
185
- return sortedMessages;
186
- }
187
-
188
- const startIndex = Math.max(0, total - offset - limit);
189
- const endIndex = total - offset;
190
- const paginatedMessages = sortedMessages.slice(startIndex, endIndex);
191
- const hasMore = startIndex > 0;
192
-
193
- return {
194
- messages: paginatedMessages,
195
- total,
196
- hasMore,
197
- offset,
198
- limit,
199
- };
200
- } catch (error) {
201
- console.error(`Error reading messages for session ${sessionId}:`, error);
202
- return limit === null ? [] : { messages: [], total: 0, hasMore: false };
203
- }
204
- }
205
-
206
- /**
207
- * Claude writes a mix of truly internal transcript rows and "UI-hidden" local
208
- * command artifacts into the same JSONL stream.
209
- *
210
- * Important distinction:
211
- * - system reminders / caveats / interruption banners should stay hidden
212
- * - local command payloads (`<command-name>...`) and stdout wrappers
213
- * (`<local-command-stdout>...`) should be remapped into normal chat messages
214
- * instead of being discarded as internal content
215
- *
216
- * Skill bodies belong in the first group. When a skill is invoked, Claude
217
- * injects the entire SKILL.md as a synthetic user turn. Persisted transcripts
218
- * tag it `isMeta: true`, but the live SDK stream does not, so without a
219
- * content-level check the same payload renders as a huge user bubble during the
220
- * run and then vanishes on reload. The skill is already represented by the
221
- * `Skill` tool call, so it is never user-visible content.
222
- */
223
- const INTERNAL_CONTENT_PREFIXES = [
224
- '<system-reminder>',
225
- 'Caveat:',
226
- '[Request interrupted',
227
- 'Base directory for this skill:',
228
- ] as const;
229
-
230
- function isInternalContent(content: string): boolean {
231
- return INTERNAL_CONTENT_PREFIXES.some((prefix) => content.startsWith(prefix));
232
- }
233
-
234
- /**
235
- * Claude wraps local slash-command metadata in lightweight XML-like tags inside
236
- * a plain string payload. We intentionally parse only the small tag surface we
237
- * care about instead of introducing a generic XML parser for untrusted history.
238
- */
239
- function extractTaggedContent(content: string, tagName: string): string | null {
240
- const escapedTagName = tagName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
241
- const match = new RegExp(`<${escapedTagName}>([\\s\\S]*?)<\\/${escapedTagName}>`).exec(content);
242
- return match ? match[1] : null;
243
- }
244
-
245
- type ClaudeLocalCommandPayload = {
246
- commandName: string;
247
- commandMessage: string;
248
- commandArgs: string;
249
- };
250
-
251
- /**
252
- * Converts Claude's hidden local command wrapper into structured metadata.
253
- *
254
- * The three tags often coexist in one string payload. Returning `null` lets the
255
- * normal text path continue untouched for unrelated messages.
256
- */
257
- function parseLocalCommandPayload(content: string): ClaudeLocalCommandPayload | null {
258
- const commandName = extractTaggedContent(content, 'command-name');
259
- const commandMessage = extractTaggedContent(content, 'command-message');
260
- const commandArgs = extractTaggedContent(content, 'command-args');
261
-
262
- if (commandName === null && commandMessage === null && commandArgs === null) {
263
- return null;
264
- }
265
-
266
- return {
267
- commandName: commandName ?? '',
268
- commandMessage: commandMessage ?? '',
269
- commandArgs: commandArgs ?? '',
270
- };
271
- }
272
-
273
- /**
274
- * Produces the short user-visible command string that should appear in chat.
275
- *
276
- * We prefer the slash-prefixed command name because that most closely matches
277
- * what the user actually typed, and only fall back to the message body when the
278
- * command name is unavailable in older transcript variants.
279
- */
280
- function buildLocalCommandDisplayText(payload: ClaudeLocalCommandPayload): string {
281
- const commandName = payload.commandName.trim();
282
- const commandMessage = payload.commandMessage.trim();
283
- const commandArgs = payload.commandArgs.trim();
284
- const baseCommand = commandName || commandMessage;
285
-
286
- if (!baseCommand) {
287
- return '';
288
- }
289
-
290
- return commandArgs ? `${baseCommand} ${commandArgs}` : baseCommand;
291
- }
292
-
293
- /**
294
- * Claude local-command stdout may contain ANSI styling codes because it was
295
- * captured from the terminal. The web chat should receive readable plain text.
296
- */
297
- function stripAnsiFormatting(text: string): string {
298
- return text.replace(/\u001B\[[0-9;?]*[ -/]*[@-~]/g, '');
299
- }
300
-
301
- export class ClaudeSessionsProvider implements IProviderSessions {
302
- /**
303
- * Normalizes one Claude JSONL entry or live SDK stream event into the shared
304
- * message shape consumed by REST and WebSocket clients.
305
- */
306
- normalizeMessage(rawMessage: unknown, sessionId: string | null): NormalizedMessage[] {
307
- const raw = readObjectRecord(rawMessage);
308
- if (!raw) {
309
- return [];
310
- }
311
-
312
- if (raw.type === 'content_block_delta' && raw.delta?.text) {
313
- return [createNormalizedMessage({ kind: 'stream_delta', content: raw.delta.text, sessionId, provider: PROVIDER })];
314
- }
315
- if (raw.type === 'content_block_stop') {
316
- return [createNormalizedMessage({ kind: 'stream_end', sessionId, provider: PROVIDER })];
317
- }
318
-
319
- const messages: NormalizedMessage[] = [];
320
- const ts = raw.timestamp || new Date().toISOString();
321
- const baseId = raw.uuid || generateMessageId('claude');
322
-
323
- if (raw.message?.role === 'user' && raw.message?.content && raw.isMeta !== true) {
324
- if (Array.isArray(raw.message.content)) {
325
- // Image attachments sent through the SDK are persisted as base64
326
- // `image` blocks next to the prompt text. Collect them so the UI can
327
- // render them on the user bubble.
328
- const imageAttachments: Array<{ data: string }> = [];
329
- for (const part of raw.message.content) {
330
- if (part?.type === 'image' && part.source?.type === 'base64' && typeof part.source.data === 'string') {
331
- const mediaType = typeof part.source.media_type === 'string' ? part.source.media_type : 'image/png';
332
- imageAttachments.push({ data: `data:${mediaType};base64,${part.source.data}` });
333
- }
334
- }
335
- let imagesAttached = false;
336
- let filesAttached = false;
337
-
338
- for (let partIndex = 0; partIndex < raw.message.content.length; partIndex++) {
339
- const part = raw.message.content[partIndex];
340
- if (part.type === 'tool_result') {
341
- messages.push(createNormalizedMessage({
342
- id: `${baseId}_tr_${part.tool_use_id}`,
343
- sessionId,
344
- timestamp: ts,
345
- provider: PROVIDER,
346
- kind: 'tool_result',
347
- toolId: part.tool_use_id,
348
- content: typeof part.content === 'string' ? part.content : JSON.stringify(part.content),
349
- isError: Boolean(part.is_error),
350
- subagentTools: raw.subagentTools,
351
- toolUseResult: raw.toolUseResult,
352
- }));
353
- } else if (part.type === 'text') {
354
- const text = part.text || '';
355
- const parsedFiles = parseFilesInputTag(text);
356
- if (
357
- (parsedFiles.text || parsedFiles.attachments.length > 0)
358
- && !isInternalContent(parsedFiles.text)
359
- ) {
360
- messages.push(createNormalizedMessage({
361
- id: `${baseId}_text_${partIndex}`,
362
- sessionId,
363
- timestamp: ts,
364
- provider: PROVIDER,
365
- kind: 'text',
366
- role: 'user',
367
- content: parsedFiles.text,
368
- images: !imagesAttached && imageAttachments.length > 0 ? imageAttachments : undefined,
369
- files: !filesAttached && parsedFiles.attachments.length > 0
370
- ? parsedFiles.attachments
371
- : undefined,
372
- }));
373
- imagesAttached = true;
374
- filesAttached = filesAttached || parsedFiles.attachments.length > 0;
375
- }
376
- }
377
- }
378
-
379
- if (messages.length === 0) {
380
- const textParts = raw.message.content
381
- .filter((part: AnyRecord) => part.type === 'text')
382
- .map((part: AnyRecord) => part.text)
383
- .filter(Boolean)
384
- .join('\n');
385
- if (textParts && !isInternalContent(textParts)) {
386
- messages.push(createNormalizedMessage({
387
- id: `${baseId}_text`,
388
- sessionId,
389
- timestamp: ts,
390
- provider: PROVIDER,
391
- kind: 'text',
392
- role: 'user',
393
- content: textParts,
394
- images: imageAttachments.length > 0 ? imageAttachments : undefined,
395
- }));
396
- imagesAttached = true;
397
- }
398
- }
399
-
400
- // Image-only turns still deserve a user bubble even without text.
401
- if (!imagesAttached && imageAttachments.length > 0) {
402
- messages.push(createNormalizedMessage({
403
- id: `${baseId}_images`,
404
- sessionId,
405
- timestamp: ts,
406
- provider: PROVIDER,
407
- kind: 'text',
408
- role: 'user',
409
- content: '',
410
- images: imageAttachments,
411
- }));
412
- }
413
- } else if (typeof raw.message.content === 'string') {
414
- const text = raw.message.content;
415
-
416
- /**
417
- * Claude stores compact summaries as synthetic "user" rows so the CLI
418
- * can resume the next session turn with the summary in-context.
419
- *
420
- * For the web UI this is much more useful as assistant-authored summary
421
- * text; otherwise it is both filtered by the generic internal-prefix
422
- * check and visually mislabeled as a user message.
423
- */
424
- if (raw.isCompactSummary === true && text.trim()) {
425
- messages.push(createNormalizedMessage({
426
- id: baseId,
427
- sessionId,
428
- timestamp: ts,
429
- provider: PROVIDER,
430
- kind: 'text',
431
- role: 'assistant',
432
- content: text,
433
- isCompactSummary: true,
434
- }));
435
- return messages;
436
- }
437
-
438
- /**
439
- * Local slash commands are serialized as tagged text even though they
440
- * are semantically a user action. Expose the parsed fields to the
441
- * frontend and emit a plain user-visible command string so the command
442
- * no longer disappears from history.
443
- */
444
- const localCommandPayload = parseLocalCommandPayload(text);
445
- if (localCommandPayload) {
446
- const displayText = buildLocalCommandDisplayText(localCommandPayload);
447
- if (displayText) {
448
- messages.push(createNormalizedMessage({
449
- id: baseId,
450
- sessionId,
451
- timestamp: ts,
452
- provider: PROVIDER,
453
- kind: 'text',
454
- role: 'user',
455
- content: displayText,
456
- commandName: localCommandPayload.commandName,
457
- commandMessage: localCommandPayload.commandMessage,
458
- commandArgs: localCommandPayload.commandArgs,
459
- isLocalCommand: true,
460
- }));
461
- }
462
- return messages;
463
- }
464
-
465
- /**
466
- * Local command stdout is also written as a "user" row in Claude's
467
- * transcript, but it is terminal output produced in response to the
468
- * command. Re-label it as assistant text so the chat transcript matches
469
- * the actual conversational flow seen by the user.
470
- */
471
- const localCommandStdout = extractTaggedContent(text, 'local-command-stdout');
472
- if (localCommandStdout !== null) {
473
- const stdoutText = stripAnsiFormatting(localCommandStdout).trim();
474
- if (stdoutText) {
475
- messages.push(createNormalizedMessage({
476
- id: baseId,
477
- sessionId,
478
- timestamp: ts,
479
- provider: PROVIDER,
480
- kind: 'text',
481
- role: 'assistant',
482
- content: stdoutText,
483
- isLocalCommandStdout: true,
484
- }));
485
- }
486
- return messages;
487
- }
488
-
489
- const parsedFiles = parseFilesInputTag(text);
490
- if (
491
- (parsedFiles.text || parsedFiles.attachments.length > 0)
492
- && !isInternalContent(parsedFiles.text)
493
- ) {
494
- messages.push(createNormalizedMessage({
495
- id: baseId,
496
- sessionId,
497
- timestamp: ts,
498
- provider: PROVIDER,
499
- kind: 'text',
500
- role: 'user',
501
- content: parsedFiles.text,
502
- files: parsedFiles.attachments.length > 0 ? parsedFiles.attachments : undefined,
503
- }));
504
- }
505
- }
506
- return messages;
507
- }
508
-
509
- if (raw.type === 'thinking' && raw.message?.content) {
510
- messages.push(createNormalizedMessage({
511
- id: baseId,
512
- sessionId,
513
- timestamp: ts,
514
- provider: PROVIDER,
515
- kind: 'thinking',
516
- content: raw.message.content,
517
- }));
518
- return messages;
519
- }
520
-
521
- if (raw.type === 'tool_use' && raw.toolName) {
522
- messages.push(createNormalizedMessage({
523
- id: baseId,
524
- sessionId,
525
- timestamp: ts,
526
- provider: PROVIDER,
527
- kind: 'tool_use',
528
- toolName: raw.toolName,
529
- toolInput: raw.toolInput,
530
- toolId: raw.toolCallId || baseId,
531
- }));
532
- return messages;
533
- }
534
-
535
- if (raw.type === 'tool_result') {
536
- messages.push(createNormalizedMessage({
537
- id: baseId,
538
- sessionId,
539
- timestamp: ts,
540
- provider: PROVIDER,
541
- kind: 'tool_result',
542
- toolId: raw.toolCallId || '',
543
- content: raw.output || '',
544
- isError: false,
545
- }));
546
- return messages;
547
- }
548
-
549
- if (raw.message?.role === 'assistant' && raw.message?.content) {
550
- if (Array.isArray(raw.message.content)) {
551
- let partIndex = 0;
552
- for (const part of raw.message.content) {
553
- if (part.type === 'text' && part.text) {
554
- messages.push(createNormalizedMessage({
555
- id: `${baseId}_${partIndex}`,
556
- sessionId,
557
- timestamp: ts,
558
- provider: PROVIDER,
559
- kind: 'text',
560
- role: 'assistant',
561
- content: part.text,
562
- }));
563
- } else if (part.type === 'tool_use') {
564
- messages.push(createNormalizedMessage({
565
- id: `${baseId}_${partIndex}`,
566
- sessionId,
567
- timestamp: ts,
568
- provider: PROVIDER,
569
- kind: 'tool_use',
570
- toolName: part.name,
571
- toolInput: part.input,
572
- toolId: part.id,
573
- }));
574
- } else if (part.type === 'thinking' && part.thinking) {
575
- messages.push(createNormalizedMessage({
576
- id: `${baseId}_${partIndex}`,
577
- sessionId,
578
- timestamp: ts,
579
- provider: PROVIDER,
580
- kind: 'thinking',
581
- content: part.thinking,
582
- }));
583
- }
584
- partIndex++;
585
- }
586
- } else if (typeof raw.message.content === 'string') {
587
- messages.push(createNormalizedMessage({
588
- id: baseId,
589
- sessionId,
590
- timestamp: ts,
591
- provider: PROVIDER,
592
- kind: 'text',
593
- role: 'assistant',
594
- content: raw.message.content,
595
- }));
596
- }
597
- return messages;
598
- }
599
-
600
- return messages;
601
- }
602
-
603
- /**
604
- * Loads Claude JSONL history for a project/session and returns normalized
605
- * messages, preserving the existing pagination behavior from projects.js.
606
- */
607
- async fetchHistory(
608
- sessionId: string,
609
- options: FetchHistoryOptions = {},
610
- ): Promise<FetchHistoryResult> {
611
- const { limit = null, offset = 0 } = options;
612
- const providerSessionId = options.providerSessionId ?? sessionId;
613
-
614
- let result: ClaudeHistoryResult;
615
- try {
616
- // Load full history first so `total` reflects frontend-normalized messages,
617
- // not raw JSONL records.
618
- result = await getSessionMessages(sessionId, providerSessionId, null, 0);
619
- } catch (error) {
620
- const message = error instanceof Error ? error.message : String(error);
621
- console.warn(`[ClaudeProvider] Failed to load session ${sessionId}:`, message);
622
- return { messages: [], total: 0, hasMore: false, offset: 0, limit: null };
623
- }
624
-
625
- const rawMessages = Array.isArray(result) ? result : (result.messages || []);
626
-
627
- const toolResultMap = new Map<string, ClaudeToolResult>();
628
- for (const raw of rawMessages) {
629
- if (raw.message?.role === 'user' && Array.isArray(raw.message?.content)) {
630
- for (const part of raw.message.content) {
631
- if (part.type === 'tool_result' && part.tool_use_id) {
632
- toolResultMap.set(part.tool_use_id, {
633
- content: part.content,
634
- isError: Boolean(part.is_error),
635
- subagentTools: raw.subagentTools,
636
- toolUseResult: raw.toolUseResult,
637
- });
638
- }
639
- }
640
- }
641
- }
642
-
643
- const normalized: NormalizedMessage[] = [];
644
- for (const raw of rawMessages) {
645
- normalized.push(...this.normalizeMessage(raw, sessionId));
646
- }
647
-
648
- for (const msg of normalized) {
649
- if (msg.kind === 'tool_use' && msg.toolId && toolResultMap.has(msg.toolId)) {
650
- const toolResult = toolResultMap.get(msg.toolId);
651
- if (!toolResult) {
652
- continue;
653
- }
654
-
655
- msg.toolResult = {
656
- content: typeof toolResult.content === 'string'
657
- ? toolResult.content
658
- : JSON.stringify(toolResult.content),
659
- isError: toolResult.isError,
660
- toolUseResult: toolResult.toolUseResult,
661
- };
662
- msg.subagentTools = toolResult.subagentTools;
663
- }
664
- }
665
-
666
- let total = 0;
667
- for (const msg of normalized) {
668
- if (msg.kind !== 'tool_result') {
669
- total += 1;
670
- }
671
- }
672
- const normalizedOffset = Math.max(0, offset);
673
- const normalizedLimit = limit === null ? null : Math.max(0, limit);
674
- const { page, hasMore } = sliceTailPage(normalized, normalizedLimit, normalizedOffset);
675
-
676
- return {
677
- messages: page,
678
- total,
679
- hasMore,
680
- offset: normalizedOffset,
681
- limit: normalizedLimit,
682
- };
683
- }
684
- }
1
+ import fs from 'node:fs';
2
+ import fsp from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import readline from 'node:readline';
5
+
6
+ import type { IProviderSessions } from '@/shared/interfaces.js';
7
+ import type { AnyRecord, FetchHistoryOptions, FetchHistoryResult, NormalizedMessage } from '@/shared/types.js';
8
+ import { parseFilesInputTag } from '@/shared/image-attachments.js';
9
+ import { createNormalizedMessage, generateMessageId, readObjectRecord, sliceTailPage } from '@/shared/utils.js';
10
+ import { sessionsDb } from '@/modules/database/index.js';
11
+
12
+ const PROVIDER = 'claude';
13
+
14
+ type ClaudeToolResult = {
15
+ content: unknown;
16
+ isError: boolean;
17
+ subagentTools?: unknown;
18
+ toolUseResult?: unknown;
19
+ };
20
+
21
+ type ClaudeHistoryResult =
22
+ | AnyRecord[]
23
+ | {
24
+ messages?: AnyRecord[];
25
+ total?: number;
26
+ hasMore?: boolean;
27
+ };
28
+
29
+ type ClaudeHistoryMessagesResult =
30
+ | AnyRecord[]
31
+ | {
32
+ messages: AnyRecord[];
33
+ total: number;
34
+ hasMore: boolean;
35
+ offset?: number;
36
+ limit?: number | null;
37
+ };
38
+
39
+ async function parseAgentTools(filePath: string): Promise<AnyRecord[]> {
40
+ const tools: AnyRecord[] = [];
41
+
42
+ try {
43
+ const fileStream = fs.createReadStream(filePath);
44
+ const rl = readline.createInterface({
45
+ input: fileStream,
46
+ crlfDelay: Infinity,
47
+ });
48
+
49
+ for await (const line of rl) {
50
+ if (!line.trim()) {
51
+ continue;
52
+ }
53
+
54
+ try {
55
+ const entry = JSON.parse(line) as AnyRecord;
56
+
57
+ if (entry.message?.role === 'assistant' && Array.isArray(entry.message?.content)) {
58
+ for (const part of entry.message.content as AnyRecord[]) {
59
+ if (part.type === 'tool_use') {
60
+ tools.push({
61
+ toolId: part.id,
62
+ toolName: part.name,
63
+ toolInput: part.input,
64
+ timestamp: entry.timestamp,
65
+ });
66
+ }
67
+ }
68
+ }
69
+
70
+ if (entry.message?.role === 'user' && Array.isArray(entry.message?.content)) {
71
+ for (const part of entry.message.content as AnyRecord[]) {
72
+ if (part.type !== 'tool_result') {
73
+ continue;
74
+ }
75
+
76
+ const tool = tools.find((candidate) => candidate.toolId === part.tool_use_id);
77
+ if (!tool) {
78
+ continue;
79
+ }
80
+
81
+ tool.toolResult = {
82
+ content: typeof part.content === 'string'
83
+ ? part.content
84
+ : Array.isArray(part.content)
85
+ ? part.content
86
+ .map((contentPart: AnyRecord) => contentPart?.text || '')
87
+ .join('\n')
88
+ : JSON.stringify(part.content),
89
+ isError: Boolean(part.is_error),
90
+ };
91
+ }
92
+ }
93
+ } catch {
94
+ // Skip malformed lines that can happen during concurrent writes.
95
+ }
96
+ }
97
+ } catch (error) {
98
+ const message = error instanceof Error ? error.message : String(error);
99
+ console.warn(`Error parsing agent file ${filePath}:`, message);
100
+ }
101
+
102
+ return tools;
103
+ }
104
+
105
+ async function getSessionMessages(
106
+ sessionId: string,
107
+ providerSessionId: string,
108
+ limit: number | null,
109
+ offset: number,
110
+ ): Promise<ClaudeHistoryMessagesResult> {
111
+ try {
112
+ // The DB row is keyed by the app-facing session id, while the JSONL rows
113
+ // on disk carry the provider-native id — both ids are needed here.
114
+ const jsonLPath = sessionsDb.getSessionById(sessionId)?.jsonl_path;
115
+
116
+ if (!jsonLPath) {
117
+ return { messages: [], total: 0, hasMore: false };
118
+ }
119
+
120
+ const projectDir = path.dirname(jsonLPath);
121
+ const files = await fsp.readdir(projectDir);
122
+ const agentFiles = files.filter((file) => file.endsWith('.jsonl') && file.startsWith('agent-'));
123
+
124
+ const messages: AnyRecord[] = [];
125
+ const agentToolsCache = new Map<string, AnyRecord[]>();
126
+
127
+ const fileStream = fs.createReadStream(jsonLPath);
128
+ const rl = readline.createInterface({
129
+ input: fileStream,
130
+ crlfDelay: Infinity,
131
+ });
132
+
133
+ for await (const line of rl) {
134
+ if (!line.trim()) {
135
+ continue;
136
+ }
137
+
138
+ try {
139
+ const entry = JSON.parse(line) as AnyRecord;
140
+ if (entry.sessionId === providerSessionId) {
141
+ messages.push(entry);
142
+ }
143
+ } catch {
144
+ // Skip malformed JSONL lines that can happen during concurrent writes.
145
+ }
146
+ }
147
+
148
+ const agentIds = new Set<string>();
149
+ for (const message of messages) {
150
+ const agentId = message.toolUseResult?.agentId;
151
+ if (agentId) {
152
+ agentIds.add(String(agentId));
153
+ }
154
+ }
155
+
156
+ for (const agentId of agentIds) {
157
+ const agentFileName = `agent-${agentId}.jsonl`;
158
+ if (!agentFiles.includes(agentFileName)) {
159
+ continue;
160
+ }
161
+
162
+ const agentFilePath = path.join(projectDir, agentFileName);
163
+ const tools = await parseAgentTools(agentFilePath);
164
+ agentToolsCache.set(agentId, tools);
165
+ }
166
+
167
+ for (const message of messages) {
168
+ const agentId = message.toolUseResult?.agentId;
169
+ if (!agentId) {
170
+ continue;
171
+ }
172
+
173
+ const agentTools = agentToolsCache.get(String(agentId));
174
+ if (agentTools && agentTools.length > 0) {
175
+ message.subagentTools = agentTools;
176
+ }
177
+ }
178
+
179
+ const sortedMessages = messages.sort(
180
+ (a, b) => new Date(a.timestamp || 0).getTime() - new Date(b.timestamp || 0).getTime(),
181
+ );
182
+ const total = sortedMessages.length;
183
+
184
+ if (limit === null) {
185
+ return sortedMessages;
186
+ }
187
+
188
+ const startIndex = Math.max(0, total - offset - limit);
189
+ const endIndex = total - offset;
190
+ const paginatedMessages = sortedMessages.slice(startIndex, endIndex);
191
+ const hasMore = startIndex > 0;
192
+
193
+ return {
194
+ messages: paginatedMessages,
195
+ total,
196
+ hasMore,
197
+ offset,
198
+ limit,
199
+ };
200
+ } catch (error) {
201
+ console.error(`Error reading messages for session ${sessionId}:`, error);
202
+ return limit === null ? [] : { messages: [], total: 0, hasMore: false };
203
+ }
204
+ }
205
+
206
+ /**
207
+ * Claude writes a mix of truly internal transcript rows and "UI-hidden" local
208
+ * command artifacts into the same JSONL stream.
209
+ *
210
+ * Important distinction:
211
+ * - system reminders / caveats / interruption banners should stay hidden
212
+ * - local command payloads (`<command-name>...`) and stdout wrappers
213
+ * (`<local-command-stdout>...`) should be remapped into normal chat messages
214
+ * instead of being discarded as internal content
215
+ *
216
+ * Skill bodies belong in the first group. When a skill is invoked, Claude
217
+ * injects the entire SKILL.md as a synthetic user turn. Persisted transcripts
218
+ * tag it `isMeta: true`, but the live SDK stream does not, so without a
219
+ * content-level check the same payload renders as a huge user bubble during the
220
+ * run and then vanishes on reload. The skill is already represented by the
221
+ * `Skill` tool call, so it is never user-visible content.
222
+ */
223
+ const INTERNAL_CONTENT_PREFIXES = [
224
+ '<system-reminder>',
225
+ 'Caveat:',
226
+ '[Request interrupted',
227
+ 'Base directory for this skill:',
228
+ ] as const;
229
+
230
+ function isInternalContent(content: string): boolean {
231
+ return INTERNAL_CONTENT_PREFIXES.some((prefix) => content.startsWith(prefix));
232
+ }
233
+
234
+ /**
235
+ * Claude wraps local slash-command metadata in lightweight XML-like tags inside
236
+ * a plain string payload. We intentionally parse only the small tag surface we
237
+ * care about instead of introducing a generic XML parser for untrusted history.
238
+ */
239
+ function extractTaggedContent(content: string, tagName: string): string | null {
240
+ const escapedTagName = tagName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
241
+ const match = new RegExp(`<${escapedTagName}>([\\s\\S]*?)<\\/${escapedTagName}>`).exec(content);
242
+ return match ? match[1] : null;
243
+ }
244
+
245
+ type ClaudeLocalCommandPayload = {
246
+ commandName: string;
247
+ commandMessage: string;
248
+ commandArgs: string;
249
+ };
250
+
251
+ /**
252
+ * Converts Claude's hidden local command wrapper into structured metadata.
253
+ *
254
+ * The three tags often coexist in one string payload. Returning `null` lets the
255
+ * normal text path continue untouched for unrelated messages.
256
+ */
257
+ function parseLocalCommandPayload(content: string): ClaudeLocalCommandPayload | null {
258
+ const commandName = extractTaggedContent(content, 'command-name');
259
+ const commandMessage = extractTaggedContent(content, 'command-message');
260
+ const commandArgs = extractTaggedContent(content, 'command-args');
261
+
262
+ if (commandName === null && commandMessage === null && commandArgs === null) {
263
+ return null;
264
+ }
265
+
266
+ return {
267
+ commandName: commandName ?? '',
268
+ commandMessage: commandMessage ?? '',
269
+ commandArgs: commandArgs ?? '',
270
+ };
271
+ }
272
+
273
+ /**
274
+ * Produces the short user-visible command string that should appear in chat.
275
+ *
276
+ * We prefer the slash-prefixed command name because that most closely matches
277
+ * what the user actually typed, and only fall back to the message body when the
278
+ * command name is unavailable in older transcript variants.
279
+ */
280
+ function buildLocalCommandDisplayText(payload: ClaudeLocalCommandPayload): string {
281
+ const commandName = payload.commandName.trim();
282
+ const commandMessage = payload.commandMessage.trim();
283
+ const commandArgs = payload.commandArgs.trim();
284
+ const baseCommand = commandName || commandMessage;
285
+
286
+ if (!baseCommand) {
287
+ return '';
288
+ }
289
+
290
+ return commandArgs ? `${baseCommand} ${commandArgs}` : baseCommand;
291
+ }
292
+
293
+ /**
294
+ * Claude local-command stdout may contain ANSI styling codes because it was
295
+ * captured from the terminal. The web chat should receive readable plain text.
296
+ */
297
+ function stripAnsiFormatting(text: string): string {
298
+ return text.replace(/\u001B\[[0-9;?]*[ -/]*[@-~]/g, '');
299
+ }
300
+
301
+ export class ClaudeSessionsProvider implements IProviderSessions {
302
+ /**
303
+ * Normalizes one Claude JSONL entry or live SDK stream event into the shared
304
+ * message shape consumed by REST and WebSocket clients.
305
+ */
306
+ normalizeMessage(rawMessage: unknown, sessionId: string | null): NormalizedMessage[] {
307
+ const raw = readObjectRecord(rawMessage);
308
+ if (!raw) {
309
+ return [];
310
+ }
311
+
312
+ if (raw.type === 'content_block_delta' && raw.delta?.text) {
313
+ return [createNormalizedMessage({ kind: 'stream_delta', content: raw.delta.text, sessionId, provider: PROVIDER })];
314
+ }
315
+ if (raw.type === 'content_block_stop') {
316
+ return [createNormalizedMessage({ kind: 'stream_end', sessionId, provider: PROVIDER })];
317
+ }
318
+
319
+ const messages: NormalizedMessage[] = [];
320
+ const ts = raw.timestamp || new Date().toISOString();
321
+ const baseId = raw.uuid || generateMessageId('claude');
322
+
323
+ if (raw.message?.role === 'user' && raw.message?.content && raw.isMeta !== true) {
324
+ if (Array.isArray(raw.message.content)) {
325
+ // Image attachments sent through the SDK are persisted as base64
326
+ // `image` blocks next to the prompt text. Collect them so the UI can
327
+ // render them on the user bubble.
328
+ const imageAttachments: Array<{ data: string }> = [];
329
+ for (const part of raw.message.content) {
330
+ if (part?.type === 'image' && part.source?.type === 'base64' && typeof part.source.data === 'string') {
331
+ const mediaType = typeof part.source.media_type === 'string' ? part.source.media_type : 'image/png';
332
+ imageAttachments.push({ data: `data:${mediaType};base64,${part.source.data}` });
333
+ }
334
+ }
335
+ let imagesAttached = false;
336
+ let filesAttached = false;
337
+
338
+ for (let partIndex = 0; partIndex < raw.message.content.length; partIndex++) {
339
+ const part = raw.message.content[partIndex];
340
+ if (part.type === 'tool_result') {
341
+ messages.push(createNormalizedMessage({
342
+ id: `${baseId}_tr_${part.tool_use_id}`,
343
+ sessionId,
344
+ timestamp: ts,
345
+ provider: PROVIDER,
346
+ kind: 'tool_result',
347
+ toolId: part.tool_use_id,
348
+ content: typeof part.content === 'string' ? part.content : JSON.stringify(part.content),
349
+ isError: Boolean(part.is_error),
350
+ subagentTools: raw.subagentTools,
351
+ toolUseResult: raw.toolUseResult,
352
+ }));
353
+ } else if (part.type === 'text') {
354
+ const text = part.text || '';
355
+ const parsedFiles = parseFilesInputTag(text);
356
+ if (
357
+ (parsedFiles.text || parsedFiles.attachments.length > 0)
358
+ && !isInternalContent(parsedFiles.text)
359
+ ) {
360
+ messages.push(createNormalizedMessage({
361
+ id: `${baseId}_text_${partIndex}`,
362
+ sessionId,
363
+ timestamp: ts,
364
+ provider: PROVIDER,
365
+ kind: 'text',
366
+ role: 'user',
367
+ content: parsedFiles.text,
368
+ images: !imagesAttached && imageAttachments.length > 0 ? imageAttachments : undefined,
369
+ files: !filesAttached && parsedFiles.attachments.length > 0
370
+ ? parsedFiles.attachments
371
+ : undefined,
372
+ }));
373
+ imagesAttached = true;
374
+ filesAttached = filesAttached || parsedFiles.attachments.length > 0;
375
+ }
376
+ }
377
+ }
378
+
379
+ if (messages.length === 0) {
380
+ const textParts = raw.message.content
381
+ .filter((part: AnyRecord) => part.type === 'text')
382
+ .map((part: AnyRecord) => part.text)
383
+ .filter(Boolean)
384
+ .join('\n');
385
+ if (textParts && !isInternalContent(textParts)) {
386
+ messages.push(createNormalizedMessage({
387
+ id: `${baseId}_text`,
388
+ sessionId,
389
+ timestamp: ts,
390
+ provider: PROVIDER,
391
+ kind: 'text',
392
+ role: 'user',
393
+ content: textParts,
394
+ images: imageAttachments.length > 0 ? imageAttachments : undefined,
395
+ }));
396
+ imagesAttached = true;
397
+ }
398
+ }
399
+
400
+ // Image-only turns still deserve a user bubble even without text.
401
+ if (!imagesAttached && imageAttachments.length > 0) {
402
+ messages.push(createNormalizedMessage({
403
+ id: `${baseId}_images`,
404
+ sessionId,
405
+ timestamp: ts,
406
+ provider: PROVIDER,
407
+ kind: 'text',
408
+ role: 'user',
409
+ content: '',
410
+ images: imageAttachments,
411
+ }));
412
+ }
413
+ } else if (typeof raw.message.content === 'string') {
414
+ const text = raw.message.content;
415
+
416
+ /**
417
+ * Claude stores compact summaries as synthetic "user" rows so the CLI
418
+ * can resume the next session turn with the summary in-context.
419
+ *
420
+ * For the web UI this is much more useful as assistant-authored summary
421
+ * text; otherwise it is both filtered by the generic internal-prefix
422
+ * check and visually mislabeled as a user message.
423
+ */
424
+ if (raw.isCompactSummary === true && text.trim()) {
425
+ messages.push(createNormalizedMessage({
426
+ id: baseId,
427
+ sessionId,
428
+ timestamp: ts,
429
+ provider: PROVIDER,
430
+ kind: 'text',
431
+ role: 'assistant',
432
+ content: text,
433
+ isCompactSummary: true,
434
+ }));
435
+ return messages;
436
+ }
437
+
438
+ /**
439
+ * Local slash commands are serialized as tagged text even though they
440
+ * are semantically a user action. Expose the parsed fields to the
441
+ * frontend and emit a plain user-visible command string so the command
442
+ * no longer disappears from history.
443
+ */
444
+ const localCommandPayload = parseLocalCommandPayload(text);
445
+ if (localCommandPayload) {
446
+ const displayText = buildLocalCommandDisplayText(localCommandPayload);
447
+ if (displayText) {
448
+ messages.push(createNormalizedMessage({
449
+ id: baseId,
450
+ sessionId,
451
+ timestamp: ts,
452
+ provider: PROVIDER,
453
+ kind: 'text',
454
+ role: 'user',
455
+ content: displayText,
456
+ commandName: localCommandPayload.commandName,
457
+ commandMessage: localCommandPayload.commandMessage,
458
+ commandArgs: localCommandPayload.commandArgs,
459
+ isLocalCommand: true,
460
+ }));
461
+ }
462
+ return messages;
463
+ }
464
+
465
+ /**
466
+ * Local command stdout is also written as a "user" row in Claude's
467
+ * transcript, but it is terminal output produced in response to the
468
+ * command. Re-label it as assistant text so the chat transcript matches
469
+ * the actual conversational flow seen by the user.
470
+ */
471
+ const localCommandStdout = extractTaggedContent(text, 'local-command-stdout');
472
+ if (localCommandStdout !== null) {
473
+ const stdoutText = stripAnsiFormatting(localCommandStdout).trim();
474
+ if (stdoutText) {
475
+ messages.push(createNormalizedMessage({
476
+ id: baseId,
477
+ sessionId,
478
+ timestamp: ts,
479
+ provider: PROVIDER,
480
+ kind: 'text',
481
+ role: 'assistant',
482
+ content: stdoutText,
483
+ isLocalCommandStdout: true,
484
+ }));
485
+ }
486
+ return messages;
487
+ }
488
+
489
+ const parsedFiles = parseFilesInputTag(text);
490
+ if (
491
+ (parsedFiles.text || parsedFiles.attachments.length > 0)
492
+ && !isInternalContent(parsedFiles.text)
493
+ ) {
494
+ messages.push(createNormalizedMessage({
495
+ id: baseId,
496
+ sessionId,
497
+ timestamp: ts,
498
+ provider: PROVIDER,
499
+ kind: 'text',
500
+ role: 'user',
501
+ content: parsedFiles.text,
502
+ files: parsedFiles.attachments.length > 0 ? parsedFiles.attachments : undefined,
503
+ }));
504
+ }
505
+ }
506
+ return messages;
507
+ }
508
+
509
+ if (raw.type === 'thinking' && raw.message?.content) {
510
+ messages.push(createNormalizedMessage({
511
+ id: baseId,
512
+ sessionId,
513
+ timestamp: ts,
514
+ provider: PROVIDER,
515
+ kind: 'thinking',
516
+ content: raw.message.content,
517
+ }));
518
+ return messages;
519
+ }
520
+
521
+ if (raw.type === 'tool_use' && raw.toolName) {
522
+ messages.push(createNormalizedMessage({
523
+ id: baseId,
524
+ sessionId,
525
+ timestamp: ts,
526
+ provider: PROVIDER,
527
+ kind: 'tool_use',
528
+ toolName: raw.toolName,
529
+ toolInput: raw.toolInput,
530
+ toolId: raw.toolCallId || baseId,
531
+ }));
532
+ return messages;
533
+ }
534
+
535
+ if (raw.type === 'tool_result') {
536
+ messages.push(createNormalizedMessage({
537
+ id: baseId,
538
+ sessionId,
539
+ timestamp: ts,
540
+ provider: PROVIDER,
541
+ kind: 'tool_result',
542
+ toolId: raw.toolCallId || '',
543
+ content: raw.output || '',
544
+ isError: false,
545
+ }));
546
+ return messages;
547
+ }
548
+
549
+ if (raw.message?.role === 'assistant' && raw.message?.content) {
550
+ if (Array.isArray(raw.message.content)) {
551
+ let partIndex = 0;
552
+ for (const part of raw.message.content) {
553
+ if (part.type === 'text' && part.text) {
554
+ messages.push(createNormalizedMessage({
555
+ id: `${baseId}_${partIndex}`,
556
+ sessionId,
557
+ timestamp: ts,
558
+ provider: PROVIDER,
559
+ kind: 'text',
560
+ role: 'assistant',
561
+ content: part.text,
562
+ }));
563
+ } else if (part.type === 'tool_use') {
564
+ messages.push(createNormalizedMessage({
565
+ id: `${baseId}_${partIndex}`,
566
+ sessionId,
567
+ timestamp: ts,
568
+ provider: PROVIDER,
569
+ kind: 'tool_use',
570
+ toolName: part.name,
571
+ toolInput: part.input,
572
+ toolId: part.id,
573
+ }));
574
+ } else if (part.type === 'thinking' && part.thinking) {
575
+ messages.push(createNormalizedMessage({
576
+ id: `${baseId}_${partIndex}`,
577
+ sessionId,
578
+ timestamp: ts,
579
+ provider: PROVIDER,
580
+ kind: 'thinking',
581
+ content: part.thinking,
582
+ }));
583
+ }
584
+ partIndex++;
585
+ }
586
+ } else if (typeof raw.message.content === 'string') {
587
+ messages.push(createNormalizedMessage({
588
+ id: baseId,
589
+ sessionId,
590
+ timestamp: ts,
591
+ provider: PROVIDER,
592
+ kind: 'text',
593
+ role: 'assistant',
594
+ content: raw.message.content,
595
+ }));
596
+ }
597
+ return messages;
598
+ }
599
+
600
+ return messages;
601
+ }
602
+
603
+ /**
604
+ * Loads Claude JSONL history for a project/session and returns normalized
605
+ * messages, preserving the existing pagination behavior from projects.js.
606
+ */
607
+ async fetchHistory(
608
+ sessionId: string,
609
+ options: FetchHistoryOptions = {},
610
+ ): Promise<FetchHistoryResult> {
611
+ const { limit = null, offset = 0 } = options;
612
+ const providerSessionId = options.providerSessionId ?? sessionId;
613
+
614
+ let result: ClaudeHistoryResult;
615
+ try {
616
+ // Load full history first so `total` reflects frontend-normalized messages,
617
+ // not raw JSONL records.
618
+ result = await getSessionMessages(sessionId, providerSessionId, null, 0);
619
+ } catch (error) {
620
+ const message = error instanceof Error ? error.message : String(error);
621
+ console.warn(`[ClaudeProvider] Failed to load session ${sessionId}:`, message);
622
+ return { messages: [], total: 0, hasMore: false, offset: 0, limit: null };
623
+ }
624
+
625
+ const rawMessages = Array.isArray(result) ? result : (result.messages || []);
626
+
627
+ const toolResultMap = new Map<string, ClaudeToolResult>();
628
+ for (const raw of rawMessages) {
629
+ if (raw.message?.role === 'user' && Array.isArray(raw.message?.content)) {
630
+ for (const part of raw.message.content) {
631
+ if (part.type === 'tool_result' && part.tool_use_id) {
632
+ toolResultMap.set(part.tool_use_id, {
633
+ content: part.content,
634
+ isError: Boolean(part.is_error),
635
+ subagentTools: raw.subagentTools,
636
+ toolUseResult: raw.toolUseResult,
637
+ });
638
+ }
639
+ }
640
+ }
641
+ }
642
+
643
+ const normalized: NormalizedMessage[] = [];
644
+ for (const raw of rawMessages) {
645
+ normalized.push(...this.normalizeMessage(raw, sessionId));
646
+ }
647
+
648
+ for (const msg of normalized) {
649
+ if (msg.kind === 'tool_use' && msg.toolId && toolResultMap.has(msg.toolId)) {
650
+ const toolResult = toolResultMap.get(msg.toolId);
651
+ if (!toolResult) {
652
+ continue;
653
+ }
654
+
655
+ msg.toolResult = {
656
+ content: typeof toolResult.content === 'string'
657
+ ? toolResult.content
658
+ : JSON.stringify(toolResult.content),
659
+ isError: toolResult.isError,
660
+ toolUseResult: toolResult.toolUseResult,
661
+ };
662
+ msg.subagentTools = toolResult.subagentTools;
663
+ }
664
+ }
665
+
666
+ let total = 0;
667
+ for (const msg of normalized) {
668
+ if (msg.kind !== 'tool_result') {
669
+ total += 1;
670
+ }
671
+ }
672
+ const normalizedOffset = Math.max(0, offset);
673
+ const normalizedLimit = limit === null ? null : Math.max(0, limit);
674
+ const { page, hasMore } = sliceTailPage(normalized, normalizedLimit, normalizedOffset);
675
+
676
+ return {
677
+ messages: page,
678
+ total,
679
+ hasMore,
680
+ offset: normalizedOffset,
681
+ limit: normalizedLimit,
682
+ };
683
+ }
684
+ }