@machina.ai/cell-cli-core 1.0.21-rc4 → 1.2.2-rc1

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 (479) hide show
  1. package/dist/index.d.ts +3 -1
  2. package/dist/index.js +3 -1
  3. package/dist/index.js.map +1 -1
  4. package/dist/package.json +24 -11
  5. package/dist/src/code_assist/codeAssist.d.ts +4 -3
  6. package/dist/src/code_assist/codeAssist.js.map +1 -1
  7. package/dist/src/code_assist/converter.d.ts +2 -1
  8. package/dist/src/code_assist/converter.js +36 -4
  9. package/dist/src/code_assist/converter.js.map +1 -1
  10. package/dist/src/code_assist/converter.test.js +83 -0
  11. package/dist/src/code_assist/converter.test.js.map +1 -1
  12. package/dist/src/code_assist/oauth2.d.ts +2 -1
  13. package/dist/src/code_assist/oauth2.js +29 -24
  14. package/dist/src/code_assist/oauth2.js.map +1 -1
  15. package/dist/src/code_assist/oauth2.test.js +65 -15
  16. package/dist/src/code_assist/oauth2.test.js.map +1 -1
  17. package/dist/src/code_assist/server.d.ts +5 -5
  18. package/dist/src/code_assist/server.js +1 -1
  19. package/dist/src/code_assist/server.js.map +1 -1
  20. package/dist/src/code_assist/setup.d.ts +1 -1
  21. package/dist/src/code_assist/setup.js +1 -1
  22. package/dist/src/code_assist/setup.js.map +1 -1
  23. package/dist/src/code_assist/setup.test.js.map +1 -1
  24. package/dist/src/config/config.d.ts +53 -11
  25. package/dist/src/config/config.js +113 -29
  26. package/dist/src/config/config.js.map +1 -1
  27. package/dist/src/config/config.test.js +103 -5
  28. package/dist/src/config/config.test.js.map +1 -1
  29. package/dist/src/config/models.d.ts +1 -0
  30. package/dist/src/config/models.js +2 -0
  31. package/dist/src/config/models.js.map +1 -1
  32. package/dist/src/config/storage.d.ts +32 -0
  33. package/dist/src/config/storage.js +90 -0
  34. package/dist/src/config/storage.js.map +1 -0
  35. package/dist/src/config/storage.test.js +43 -0
  36. package/dist/src/config/storage.test.js.map +1 -0
  37. package/dist/src/core/client.d.ts +17 -9
  38. package/dist/src/core/client.js +76 -19
  39. package/dist/src/core/client.js.map +1 -1
  40. package/dist/src/core/client.test.js +366 -84
  41. package/dist/src/core/client.test.js.map +1 -1
  42. package/dist/src/core/contentGenerator.d.ts +6 -6
  43. package/dist/src/core/contentGenerator.js +4 -3
  44. package/dist/src/core/contentGenerator.js.map +1 -1
  45. package/dist/src/core/contentGenerator.test.js.map +1 -1
  46. package/dist/src/core/coreToolScheduler.d.ts +14 -5
  47. package/dist/src/core/coreToolScheduler.js +120 -49
  48. package/dist/src/core/coreToolScheduler.js.map +1 -1
  49. package/dist/src/core/coreToolScheduler.test.js +365 -72
  50. package/dist/src/core/coreToolScheduler.test.js.map +1 -1
  51. package/dist/src/core/geminiChat.d.ts +18 -14
  52. package/dist/src/core/geminiChat.js +223 -156
  53. package/dist/src/core/geminiChat.js.map +1 -1
  54. package/dist/src/core/geminiChat.test.js +862 -257
  55. package/dist/src/core/geminiChat.test.js.map +1 -1
  56. package/dist/src/core/geminiRequest.js +1 -0
  57. package/dist/src/core/geminiRequest.js.map +1 -1
  58. package/dist/src/core/logger.d.ts +4 -2
  59. package/dist/src/core/logger.js +4 -3
  60. package/dist/src/core/logger.js.map +1 -1
  61. package/dist/src/core/logger.test.js +19 -18
  62. package/dist/src/core/logger.test.js.map +1 -1
  63. package/dist/src/core/loggingContentGenerator.d.ts +3 -3
  64. package/dist/src/core/loggingContentGenerator.js +3 -1
  65. package/dist/src/core/loggingContentGenerator.js.map +1 -1
  66. package/dist/src/core/nonInteractiveToolExecutor.d.ts +3 -5
  67. package/dist/src/core/nonInteractiveToolExecutor.js +15 -123
  68. package/dist/src/core/nonInteractiveToolExecutor.js.map +1 -1
  69. package/dist/src/core/nonInteractiveToolExecutor.test.js +114 -90
  70. package/dist/src/core/nonInteractiveToolExecutor.test.js.map +1 -1
  71. package/dist/src/core/prompts.js +8 -7
  72. package/dist/src/core/prompts.js.map +1 -1
  73. package/dist/src/core/prompts.test.js +21 -21
  74. package/dist/src/core/prompts.test.js.map +1 -1
  75. package/dist/src/core/subagent.d.ts +24 -18
  76. package/dist/src/core/subagent.js +125 -87
  77. package/dist/src/core/subagent.js.map +1 -1
  78. package/dist/src/core/subagent.test.js +31 -26
  79. package/dist/src/core/subagent.test.js.map +1 -1
  80. package/dist/src/core/turn.d.ts +24 -7
  81. package/dist/src/core/turn.js +41 -11
  82. package/dist/src/core/turn.js.map +1 -1
  83. package/dist/src/core/turn.test.js +157 -1
  84. package/dist/src/core/turn.test.js.map +1 -1
  85. package/dist/src/generated/git-commit.d.ts +2 -2
  86. package/dist/src/generated/git-commit.js +2 -2
  87. package/dist/src/generated/git-commit.js.map +1 -1
  88. package/dist/src/ide/constants.d.ts +1 -1
  89. package/dist/src/ide/constants.js +1 -1
  90. package/dist/src/ide/constants.js.map +1 -1
  91. package/dist/src/ide/detect-ide.d.ts +8 -3
  92. package/dist/src/ide/detect-ide.js +29 -11
  93. package/dist/src/ide/detect-ide.js.map +1 -1
  94. package/dist/src/ide/detect-ide.test.js +96 -52
  95. package/dist/src/ide/detect-ide.test.js.map +1 -1
  96. package/dist/src/ide/ide-client.d.ts +11 -7
  97. package/dist/src/ide/ide-client.js +127 -29
  98. package/dist/src/ide/ide-client.js.map +1 -1
  99. package/dist/src/ide/ide-client.test.js +147 -25
  100. package/dist/src/ide/ide-client.test.js.map +1 -1
  101. package/dist/src/ide/ide-installer.d.ts +1 -1
  102. package/dist/src/ide/ide-installer.js +31 -22
  103. package/dist/src/ide/ide-installer.js.map +1 -1
  104. package/dist/src/ide/ide-installer.test.js +82 -22
  105. package/dist/src/ide/ide-installer.test.js.map +1 -1
  106. package/dist/src/ide/process-utils.d.ts +14 -6
  107. package/dist/src/ide/process-utils.js +136 -34
  108. package/dist/src/ide/process-utils.js.map +1 -1
  109. package/dist/src/ide/process-utils.test.js +158 -0
  110. package/dist/src/ide/process-utils.test.js.map +1 -0
  111. package/dist/src/index.d.ts +11 -2
  112. package/dist/src/index.js +10 -1
  113. package/dist/src/index.js.map +1 -1
  114. package/dist/src/mcp/google-auth-provider.d.ts +3 -3
  115. package/dist/src/mcp/google-auth-provider.test.js.map +1 -1
  116. package/dist/src/mcp/oauth-provider.d.ts +2 -2
  117. package/dist/src/mcp/oauth-provider.js.map +1 -1
  118. package/dist/src/mcp/oauth-provider.test.js +1 -1
  119. package/dist/src/mcp/oauth-provider.test.js.map +1 -1
  120. package/dist/src/mcp/oauth-token-storage.d.ts +5 -27
  121. package/dist/src/mcp/oauth-token-storage.js +2 -5
  122. package/dist/src/mcp/oauth-token-storage.js.map +1 -1
  123. package/dist/src/mcp/oauth-token-storage.test.js +7 -6
  124. package/dist/src/mcp/oauth-token-storage.test.js.map +1 -1
  125. package/dist/src/mcp/oauth-utils.d.ts +9 -1
  126. package/dist/src/mcp/oauth-utils.js +41 -27
  127. package/dist/src/mcp/oauth-utils.js.map +1 -1
  128. package/dist/src/mcp/oauth-utils.test.js +41 -1
  129. package/dist/src/mcp/oauth-utils.test.js.map +1 -1
  130. package/dist/src/mcp/token-storage/base-token-storage.d.ts +19 -0
  131. package/dist/src/mcp/token-storage/base-token-storage.js +36 -0
  132. package/dist/src/mcp/token-storage/base-token-storage.js.map +1 -0
  133. package/dist/src/mcp/token-storage/base-token-storage.test.d.ts +6 -0
  134. package/dist/src/mcp/token-storage/base-token-storage.test.js +160 -0
  135. package/dist/src/mcp/token-storage/base-token-storage.test.js.map +1 -0
  136. package/dist/src/mcp/token-storage/file-token-storage.d.ts +24 -0
  137. package/dist/src/mcp/token-storage/file-token-storage.js +144 -0
  138. package/dist/src/mcp/token-storage/file-token-storage.js.map +1 -0
  139. package/dist/src/mcp/token-storage/file-token-storage.test.d.ts +6 -0
  140. package/dist/src/mcp/token-storage/file-token-storage.test.js +235 -0
  141. package/dist/src/mcp/token-storage/file-token-storage.test.js.map +1 -0
  142. package/dist/src/mcp/token-storage/types.d.ts +34 -0
  143. package/dist/src/mcp/token-storage/types.js +7 -0
  144. package/dist/src/mcp/token-storage/types.js.map +1 -0
  145. package/dist/src/prompts/mcp-prompts.d.ts +2 -2
  146. package/dist/src/prompts/prompt-registry.d.ts +1 -1
  147. package/dist/src/services/chatRecordingService.d.ts +2 -2
  148. package/dist/src/services/chatRecordingService.js +6 -3
  149. package/dist/src/services/chatRecordingService.js.map +1 -1
  150. package/dist/src/services/chatRecordingService.test.js +10 -8
  151. package/dist/src/services/chatRecordingService.test.js.map +1 -1
  152. package/dist/src/services/fileDiscoveryService.js +1 -1
  153. package/dist/src/services/fileDiscoveryService.js.map +1 -1
  154. package/dist/src/services/fileDiscoveryService.test.js +3 -3
  155. package/dist/src/services/fileDiscoveryService.test.js.map +1 -1
  156. package/dist/src/services/fileSystemService.js +1 -1
  157. package/dist/src/services/fileSystemService.js.map +1 -1
  158. package/dist/src/services/fileSystemService.test.js +1 -1
  159. package/dist/src/services/fileSystemService.test.js.map +1 -1
  160. package/dist/src/services/gitService.d.ts +3 -1
  161. package/dist/src/services/gitService.js +21 -12
  162. package/dist/src/services/gitService.js.map +1 -1
  163. package/dist/src/services/gitService.test.js +22 -19
  164. package/dist/src/services/gitService.test.js.map +1 -1
  165. package/dist/src/services/loopDetectionService.d.ts +2 -2
  166. package/dist/src/services/loopDetectionService.js +9 -3
  167. package/dist/src/services/loopDetectionService.js.map +1 -1
  168. package/dist/src/services/loopDetectionService.test.js +23 -1
  169. package/dist/src/services/loopDetectionService.test.js.map +1 -1
  170. package/dist/src/services/shellExecutionService.d.ts +8 -10
  171. package/dist/src/services/shellExecutionService.js +292 -135
  172. package/dist/src/services/shellExecutionService.js.map +1 -1
  173. package/dist/src/services/shellExecutionService.test.js +277 -42
  174. package/dist/src/services/shellExecutionService.test.js.map +1 -1
  175. package/dist/src/telemetry/clearcut-logger/clearcut-logger.d.ts +16 -4
  176. package/dist/src/telemetry/clearcut-logger/clearcut-logger.js +140 -9
  177. package/dist/src/telemetry/clearcut-logger/clearcut-logger.js.map +1 -1
  178. package/dist/src/telemetry/clearcut-logger/clearcut-logger.test.js +84 -11
  179. package/dist/src/telemetry/clearcut-logger/clearcut-logger.test.js.map +1 -1
  180. package/dist/src/telemetry/clearcut-logger/event-metadata-key.d.ts +26 -1
  181. package/dist/src/telemetry/clearcut-logger/event-metadata-key.js +62 -0
  182. package/dist/src/telemetry/clearcut-logger/event-metadata-key.js.map +1 -1
  183. package/dist/src/telemetry/constants.d.ts +8 -0
  184. package/dist/src/telemetry/constants.js +8 -0
  185. package/dist/src/telemetry/constants.js.map +1 -1
  186. package/dist/src/telemetry/file-exporters.d.ts +5 -4
  187. package/dist/src/telemetry/file-exporters.js +1 -1
  188. package/dist/src/telemetry/file-exporters.js.map +1 -1
  189. package/dist/src/telemetry/index.d.ts +5 -2
  190. package/dist/src/telemetry/index.js +3 -2
  191. package/dist/src/telemetry/index.js.map +1 -1
  192. package/dist/src/telemetry/loggers.d.ts +8 -2
  193. package/dist/src/telemetry/loggers.js +105 -2
  194. package/dist/src/telemetry/loggers.js.map +1 -1
  195. package/dist/src/telemetry/loggers.test.circular.js.map +1 -1
  196. package/dist/src/telemetry/loggers.test.js +69 -9
  197. package/dist/src/telemetry/loggers.test.js.map +1 -1
  198. package/dist/src/telemetry/metrics.d.ts +15 -4
  199. package/dist/src/telemetry/metrics.js +46 -8
  200. package/dist/src/telemetry/metrics.js.map +1 -1
  201. package/dist/src/telemetry/metrics.test.js +5 -25
  202. package/dist/src/telemetry/metrics.test.js.map +1 -1
  203. package/dist/src/telemetry/sdk.d.ts +1 -1
  204. package/dist/src/telemetry/sdk.js +3 -3
  205. package/dist/src/telemetry/sdk.js.map +1 -1
  206. package/dist/src/telemetry/telemetry-utils.d.ts +6 -0
  207. package/dist/src/telemetry/telemetry-utils.js +14 -0
  208. package/dist/src/telemetry/telemetry-utils.js.map +1 -0
  209. package/dist/src/telemetry/telemetry-utils.test.d.ts +6 -0
  210. package/dist/src/telemetry/telemetry-utils.test.js +40 -0
  211. package/dist/src/telemetry/telemetry-utils.test.js.map +1 -0
  212. package/dist/src/telemetry/types.d.ts +52 -6
  213. package/dist/src/telemetry/types.js +87 -2
  214. package/dist/src/telemetry/types.js.map +1 -1
  215. package/dist/src/telemetry/uiTelemetry.d.ts +2 -2
  216. package/dist/src/telemetry/uiTelemetry.js +1 -1
  217. package/dist/src/telemetry/uiTelemetry.js.map +1 -1
  218. package/dist/src/telemetry/uiTelemetry.test.js +16 -12
  219. package/dist/src/telemetry/uiTelemetry.test.js.map +1 -1
  220. package/dist/src/test-utils/config.d.ts +2 -1
  221. package/dist/src/test-utils/config.js.map +1 -1
  222. package/dist/src/test-utils/index.d.ts +6 -0
  223. package/dist/src/test-utils/index.js +7 -0
  224. package/dist/src/test-utils/index.js.map +1 -0
  225. package/dist/src/test-utils/mock-tool.d.ts +41 -0
  226. package/dist/src/test-utils/mock-tool.js +51 -0
  227. package/dist/src/test-utils/mock-tool.js.map +1 -0
  228. package/dist/src/test-utils/mockWorkspaceContext.d.ts +1 -1
  229. package/dist/src/test-utils/tools.d.ts +3 -2
  230. package/dist/src/test-utils/tools.js.map +1 -1
  231. package/dist/src/tools/diffOptions.d.ts +1 -1
  232. package/dist/src/tools/edit.d.ts +6 -5
  233. package/dist/src/tools/edit.js +36 -17
  234. package/dist/src/tools/edit.js.map +1 -1
  235. package/dist/src/tools/edit.test.js +45 -8
  236. package/dist/src/tools/edit.test.js.map +1 -1
  237. package/dist/src/tools/glob.d.ts +3 -2
  238. package/dist/src/tools/glob.js +17 -6
  239. package/dist/src/tools/glob.js.map +1 -1
  240. package/dist/src/tools/glob.test.js +29 -4
  241. package/dist/src/tools/glob.test.js.map +1 -1
  242. package/dist/src/tools/grep.d.ts +3 -2
  243. package/dist/src/tools/grep.js +35 -15
  244. package/dist/src/tools/grep.js.map +1 -1
  245. package/dist/src/tools/grep.test.js +26 -3
  246. package/dist/src/tools/grep.test.js.map +1 -1
  247. package/dist/src/tools/ls.d.ts +3 -2
  248. package/dist/src/tools/ls.js +12 -7
  249. package/dist/src/tools/ls.js.map +1 -1
  250. package/dist/src/tools/ls.test.js +7 -2
  251. package/dist/src/tools/ls.test.js.map +1 -1
  252. package/dist/src/tools/mcp-client-manager.d.ts +8 -6
  253. package/dist/src/tools/mcp-client-manager.js +30 -5
  254. package/dist/src/tools/mcp-client-manager.js.map +1 -1
  255. package/dist/src/tools/mcp-client-manager.test.js +20 -1
  256. package/dist/src/tools/mcp-client-manager.test.js.map +1 -1
  257. package/dist/src/tools/mcp-client.d.ts +18 -11
  258. package/dist/src/tools/mcp-client.js +38 -33
  259. package/dist/src/tools/mcp-client.js.map +1 -1
  260. package/dist/src/tools/mcp-client.test.js +29 -4
  261. package/dist/src/tools/mcp-client.test.js.map +1 -1
  262. package/dist/src/tools/mcp-tool.d.ts +6 -3
  263. package/dist/src/tools/mcp-tool.js +21 -7
  264. package/dist/src/tools/mcp-tool.js.map +1 -1
  265. package/dist/src/tools/mcp-tool.test.js +49 -6
  266. package/dist/src/tools/mcp-tool.test.js.map +1 -1
  267. package/dist/src/tools/memoryTool.d.ts +4 -3
  268. package/dist/src/tools/memoryTool.js +15 -38
  269. package/dist/src/tools/memoryTool.js.map +1 -1
  270. package/dist/src/tools/memoryTool.test.js +24 -12
  271. package/dist/src/tools/memoryTool.test.js.map +1 -1
  272. package/dist/src/tools/modifiable-tool.d.ts +2 -2
  273. package/dist/src/tools/modifiable-tool.js +3 -3
  274. package/dist/src/tools/modifiable-tool.js.map +1 -1
  275. package/dist/src/tools/modifiable-tool.test.js +4 -4
  276. package/dist/src/tools/modifiable-tool.test.js.map +1 -1
  277. package/dist/src/tools/read-file.d.ts +3 -2
  278. package/dist/src/tools/read-file.js +12 -34
  279. package/dist/src/tools/read-file.js.map +1 -1
  280. package/dist/src/tools/read-file.test.js +9 -6
  281. package/dist/src/tools/read-file.test.js.map +1 -1
  282. package/dist/src/tools/read-many-files.d.ts +3 -2
  283. package/dist/src/tools/read-many-files.js +35 -58
  284. package/dist/src/tools/read-many-files.js.map +1 -1
  285. package/dist/src/tools/read-many-files.test.js +60 -7
  286. package/dist/src/tools/read-many-files.test.js.map +1 -1
  287. package/dist/src/tools/ripGrep.d.ts +47 -0
  288. package/dist/src/tools/ripGrep.js +368 -0
  289. package/dist/src/tools/ripGrep.js.map +1 -0
  290. package/dist/src/tools/ripGrep.test.d.ts +6 -0
  291. package/dist/src/tools/ripGrep.test.js +874 -0
  292. package/dist/src/tools/ripGrep.test.js.map +1 -0
  293. package/dist/src/tools/shell.d.ts +3 -2
  294. package/dist/src/tools/shell.js +26 -24
  295. package/dist/src/tools/shell.js.map +1 -1
  296. package/dist/src/tools/shell.test.js +33 -24
  297. package/dist/src/tools/shell.test.js.map +1 -1
  298. package/dist/src/tools/smart-edit.d.ts +73 -0
  299. package/dist/src/tools/smart-edit.js +607 -0
  300. package/dist/src/tools/smart-edit.js.map +1 -0
  301. package/dist/src/tools/smart-edit.test.d.ts +6 -0
  302. package/dist/src/tools/smart-edit.test.js +397 -0
  303. package/dist/src/tools/smart-edit.test.js.map +1 -0
  304. package/dist/src/tools/tool-error.d.ts +17 -1
  305. package/dist/src/tools/tool-error.js +26 -0
  306. package/dist/src/tools/tool-error.js.map +1 -1
  307. package/dist/src/tools/tool-registry.d.ts +10 -4
  308. package/dist/src/tools/tool-registry.js +19 -7
  309. package/dist/src/tools/tool-registry.js.map +1 -1
  310. package/dist/src/tools/tool-registry.test.js +86 -3
  311. package/dist/src/tools/tool-registry.test.js.map +1 -1
  312. package/dist/src/tools/tools.d.ts +9 -7
  313. package/dist/src/tools/tools.js +12 -0
  314. package/dist/src/tools/tools.js.map +1 -1
  315. package/dist/src/tools/tools.test.js +1 -2
  316. package/dist/src/tools/tools.test.js.map +1 -1
  317. package/dist/src/tools/web-fetch.d.ts +3 -2
  318. package/dist/src/tools/web-fetch.js +10 -7
  319. package/dist/src/tools/web-fetch.js.map +1 -1
  320. package/dist/src/tools/web-fetch.test.js +55 -16
  321. package/dist/src/tools/web-fetch.test.js.map +1 -1
  322. package/dist/src/tools/web-search.d.ts +4 -3
  323. package/dist/src/tools/web-search.js +28 -7
  324. package/dist/src/tools/web-search.js.map +1 -1
  325. package/dist/src/tools/web-search.test.js +69 -1
  326. package/dist/src/tools/web-search.test.js.map +1 -1
  327. package/dist/src/tools/write-file.d.ts +4 -3
  328. package/dist/src/tools/write-file.js +13 -13
  329. package/dist/src/tools/write-file.js.map +1 -1
  330. package/dist/src/tools/write-file.test.js +9 -5
  331. package/dist/src/tools/write-file.test.js.map +1 -1
  332. package/dist/src/utils/bfsFileSearch.d.ts +2 -2
  333. package/dist/src/utils/bfsFileSearch.js +2 -2
  334. package/dist/src/utils/bfsFileSearch.js.map +1 -1
  335. package/dist/src/utils/bfsFileSearch.test.js +3 -3
  336. package/dist/src/utils/bfsFileSearch.test.js.map +1 -1
  337. package/dist/src/utils/editCorrector.d.ts +2 -2
  338. package/dist/src/utils/editCorrector.js +1 -1
  339. package/dist/src/utils/editCorrector.js.map +1 -1
  340. package/dist/src/utils/editCorrector.test.js +3 -3
  341. package/dist/src/utils/editCorrector.test.js.map +1 -1
  342. package/dist/src/utils/editor.js +2 -2
  343. package/dist/src/utils/editor.js.map +1 -1
  344. package/dist/src/utils/editor.test.js +2 -2
  345. package/dist/src/utils/editor.test.js.map +1 -1
  346. package/dist/src/utils/environmentContext.d.ts +2 -2
  347. package/dist/src/utils/environmentContext.js +1 -1
  348. package/dist/src/utils/environmentContext.js.map +1 -1
  349. package/dist/src/utils/environmentContext.test.js +1 -1
  350. package/dist/src/utils/environmentContext.test.js.map +1 -1
  351. package/dist/src/utils/errorReporting.d.ts +1 -1
  352. package/dist/src/utils/errors.d.ts +19 -0
  353. package/dist/src/utils/errors.js +32 -0
  354. package/dist/src/utils/errors.js.map +1 -1
  355. package/dist/src/utils/fetch.js +1 -1
  356. package/dist/src/utils/fetch.js.map +1 -1
  357. package/dist/src/utils/fileUtils.d.ts +23 -12
  358. package/dist/src/utils/fileUtils.js +155 -75
  359. package/dist/src/utils/fileUtils.js.map +1 -1
  360. package/dist/src/utils/fileUtils.test.js +293 -1
  361. package/dist/src/utils/fileUtils.test.js.map +1 -1
  362. package/dist/src/utils/filesearch/crawler.d.ts +1 -1
  363. package/dist/src/utils/filesearch/crawler.test.js +2 -2
  364. package/dist/src/utils/filesearch/crawler.test.js.map +1 -1
  365. package/dist/src/utils/filesearch/fileSearch.d.ts +1 -0
  366. package/dist/src/utils/filesearch/fileSearch.js +14 -9
  367. package/dist/src/utils/filesearch/fileSearch.js.map +1 -1
  368. package/dist/src/utils/filesearch/fileSearch.test.js +90 -0
  369. package/dist/src/utils/filesearch/fileSearch.test.js.map +1 -1
  370. package/dist/src/utils/generateContentResponseUtilities.d.ts +1 -2
  371. package/dist/src/utils/generateContentResponseUtilities.js +1 -13
  372. package/dist/src/utils/generateContentResponseUtilities.js.map +1 -1
  373. package/dist/src/utils/generateContentResponseUtilities.test.js +2 -40
  374. package/dist/src/utils/generateContentResponseUtilities.test.js.map +1 -1
  375. package/dist/src/utils/getFolderStructure.d.ts +2 -2
  376. package/dist/src/utils/getFolderStructure.js +2 -2
  377. package/dist/src/utils/getFolderStructure.js.map +1 -1
  378. package/dist/src/utils/getFolderStructure.test.js +13 -13
  379. package/dist/src/utils/getFolderStructure.test.js.map +1 -1
  380. package/dist/src/utils/getPty.d.ts +19 -0
  381. package/dist/src/utils/getPty.js +23 -0
  382. package/dist/src/utils/getPty.js.map +1 -0
  383. package/dist/src/utils/gitIgnoreParser.js +3 -3
  384. package/dist/src/utils/gitIgnoreParser.js.map +1 -1
  385. package/dist/src/utils/gitIgnoreParser.test.js +3 -3
  386. package/dist/src/utils/gitIgnoreParser.test.js.map +1 -1
  387. package/dist/src/utils/gitUtils.js +2 -2
  388. package/dist/src/utils/gitUtils.js.map +1 -1
  389. package/dist/src/utils/ignorePatterns.d.ts +103 -0
  390. package/dist/src/utils/ignorePatterns.js +220 -0
  391. package/dist/src/utils/ignorePatterns.js.map +1 -0
  392. package/dist/src/utils/ignorePatterns.test.d.ts +6 -0
  393. package/dist/src/utils/ignorePatterns.test.js +250 -0
  394. package/dist/src/utils/ignorePatterns.test.js.map +1 -0
  395. package/dist/src/utils/installationManager.d.ts +16 -0
  396. package/dist/src/utils/installationManager.js +50 -0
  397. package/dist/src/utils/installationManager.js.map +1 -0
  398. package/dist/src/utils/installationManager.test.d.ts +6 -0
  399. package/dist/src/utils/installationManager.test.js +83 -0
  400. package/dist/src/utils/installationManager.test.js.map +1 -0
  401. package/dist/src/utils/language-detection.d.ts +6 -0
  402. package/dist/src/utils/language-detection.js +101 -0
  403. package/dist/src/utils/language-detection.js.map +1 -0
  404. package/dist/src/utils/llm-edit-fixer.d.ts +25 -0
  405. package/dist/src/utils/llm-edit-fixer.js +112 -0
  406. package/dist/src/utils/llm-edit-fixer.js.map +1 -0
  407. package/dist/src/utils/memoryDiscovery.d.ts +7 -6
  408. package/dist/src/utils/memoryDiscovery.js +68 -33
  409. package/dist/src/utils/memoryDiscovery.js.map +1 -1
  410. package/dist/src/utils/memoryDiscovery.test.js +76 -20
  411. package/dist/src/utils/memoryDiscovery.test.js.map +1 -1
  412. package/dist/src/utils/memoryImportProcessor.js +2 -2
  413. package/dist/src/utils/memoryImportProcessor.js.map +1 -1
  414. package/dist/src/utils/memoryImportProcessor.test.js +2 -141
  415. package/dist/src/utils/memoryImportProcessor.test.js.map +1 -1
  416. package/dist/src/utils/messageInspectors.d.ts +1 -1
  417. package/dist/src/utils/nextSpeakerChecker.d.ts +2 -2
  418. package/dist/src/utils/nextSpeakerChecker.test.js.map +1 -1
  419. package/dist/src/utils/partUtils.d.ts +22 -1
  420. package/dist/src/utils/partUtils.js +68 -0
  421. package/dist/src/utils/partUtils.js.map +1 -1
  422. package/dist/src/utils/partUtils.test.js +112 -1
  423. package/dist/src/utils/partUtils.test.js.map +1 -1
  424. package/dist/src/utils/pathReader.d.ts +17 -0
  425. package/dist/src/utils/pathReader.js +92 -0
  426. package/dist/src/utils/pathReader.js.map +1 -0
  427. package/dist/src/utils/pathReader.test.d.ts +6 -0
  428. package/dist/src/utils/pathReader.test.js +363 -0
  429. package/dist/src/utils/pathReader.test.js.map +1 -0
  430. package/dist/src/utils/paths.d.ts +1 -18
  431. package/dist/src/utils/paths.js +3 -29
  432. package/dist/src/utils/paths.js.map +1 -1
  433. package/dist/src/utils/quotaErrorDetection.d.ts +1 -1
  434. package/dist/src/utils/retry.test.js +4 -1
  435. package/dist/src/utils/retry.test.js.map +1 -1
  436. package/dist/src/utils/schemaValidator.js +4 -0
  437. package/dist/src/utils/schemaValidator.js.map +1 -1
  438. package/dist/src/utils/session.js +1 -1
  439. package/dist/src/utils/session.js.map +1 -1
  440. package/dist/src/utils/shell-utils.d.ts +1 -1
  441. package/dist/src/utils/shell-utils.js +23 -29
  442. package/dist/src/utils/shell-utils.js.map +1 -1
  443. package/dist/src/utils/shell-utils.test.js +8 -1
  444. package/dist/src/utils/shell-utils.test.js.map +1 -1
  445. package/dist/src/utils/summarizer.d.ts +2 -2
  446. package/dist/src/utils/summarizer.test.js.map +1 -1
  447. package/dist/src/utils/systemEncoding.js +2 -2
  448. package/dist/src/utils/systemEncoding.js.map +1 -1
  449. package/dist/src/utils/systemEncoding.test.js +2 -2
  450. package/dist/src/utils/systemEncoding.test.js.map +1 -1
  451. package/dist/src/utils/tool-utils.d.ts +19 -0
  452. package/dist/src/utils/tool-utils.js +58 -0
  453. package/dist/src/utils/tool-utils.js.map +1 -0
  454. package/dist/src/utils/tool-utils.test.d.ts +6 -0
  455. package/dist/src/utils/tool-utils.test.js +61 -0
  456. package/dist/src/utils/tool-utils.test.js.map +1 -0
  457. package/dist/src/utils/userAccountManager.d.ts +20 -0
  458. package/dist/src/utils/userAccountManager.js +114 -0
  459. package/dist/src/utils/userAccountManager.js.map +1 -0
  460. package/dist/src/utils/userAccountManager.test.d.ts +6 -0
  461. package/dist/src/utils/{user_account.test.js → userAccountManager.test.js} +33 -30
  462. package/dist/src/utils/userAccountManager.test.js.map +1 -0
  463. package/dist/src/utils/workspaceContext.js +13 -7
  464. package/dist/src/utils/workspaceContext.js.map +1 -1
  465. package/dist/src/utils/workspaceContext.test.js +41 -16
  466. package/dist/src/utils/workspaceContext.test.js.map +1 -1
  467. package/dist/tsconfig.tsbuildinfo +1 -1
  468. package/package.json +25 -12
  469. package/dist/src/utils/user_account.d.ts +0 -9
  470. package/dist/src/utils/user_account.js +0 -109
  471. package/dist/src/utils/user_account.js.map +0 -1
  472. package/dist/src/utils/user_account.test.js.map +0 -1
  473. package/dist/src/utils/user_id.d.ts +0 -11
  474. package/dist/src/utils/user_id.js +0 -49
  475. package/dist/src/utils/user_id.js.map +0 -1
  476. package/dist/src/utils/user_id.test.js +0 -21
  477. package/dist/src/utils/user_id.test.js.map +0 -1
  478. /package/dist/src/{utils/user_account.test.d.ts → config/storage.test.d.ts} +0 -0
  479. /package/dist/src/{utils/user_id.test.d.ts → ide/process-utils.test.d.ts} +0 -0
@@ -4,7 +4,7 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
  import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
7
- import { GeminiChat } from './geminiChat.js';
7
+ import { GeminiChat, EmptyStreamError } from './geminiChat.js';
8
8
  import { setSimulate429 } from '../utils/testUtils.js';
9
9
  // Mocks
10
10
  const mockModelsModule = {
@@ -14,6 +14,16 @@ const mockModelsModule = {
14
14
  embedContent: vi.fn(),
15
15
  batchEmbedContents: vi.fn(),
16
16
  };
17
+ const { mockLogInvalidChunk, mockLogContentRetry, mockLogContentRetryFailure } = vi.hoisted(() => ({
18
+ mockLogInvalidChunk: vi.fn(),
19
+ mockLogContentRetry: vi.fn(),
20
+ mockLogContentRetryFailure: vi.fn(),
21
+ }));
22
+ vi.mock('../telemetry/loggers.js', () => ({
23
+ logInvalidChunk: mockLogInvalidChunk,
24
+ logContentRetry: mockLogContentRetry,
25
+ logContentRetryFailure: mockLogContentRetryFailure,
26
+ }));
17
27
  describe('GeminiChat', () => {
18
28
  let chat;
19
29
  let mockConfig;
@@ -45,6 +55,181 @@ describe('GeminiChat', () => {
45
55
  vi.resetAllMocks();
46
56
  });
47
57
  describe('sendMessage', () => {
58
+ it('should retain the initial user message when an automatic function call occurs', async () => {
59
+ // 1. Define the user's initial text message. This is the turn that gets dropped by the buggy logic.
60
+ const userInitialMessage = {
61
+ role: 'user',
62
+ parts: [{ text: 'How is the weather in Boston?' }],
63
+ };
64
+ // 2. Mock the full API response, including the automaticFunctionCallingHistory.
65
+ // This history represents the full turn: user asks, model calls tool, tool responds, model answers.
66
+ const mockAfcResponse = {
67
+ candidates: [
68
+ {
69
+ content: {
70
+ role: 'model',
71
+ parts: [
72
+ { text: 'The weather in Boston is 72 degrees and sunny.' },
73
+ ],
74
+ },
75
+ },
76
+ ],
77
+ automaticFunctionCallingHistory: [
78
+ userInitialMessage, // The user's turn
79
+ {
80
+ // The model's first response: a tool call
81
+ role: 'model',
82
+ parts: [
83
+ {
84
+ functionCall: {
85
+ name: 'get_weather',
86
+ args: { location: 'Boston' },
87
+ },
88
+ },
89
+ ],
90
+ },
91
+ {
92
+ // The tool's response, which has a 'user' role
93
+ role: 'user',
94
+ parts: [
95
+ {
96
+ functionResponse: {
97
+ name: 'get_weather',
98
+ response: { temperature: 72, condition: 'sunny' },
99
+ },
100
+ },
101
+ ],
102
+ },
103
+ ],
104
+ };
105
+ vi.mocked(mockModelsModule.generateContent).mockResolvedValue(mockAfcResponse);
106
+ // 3. Action: Send the initial message.
107
+ await chat.sendMessage({ message: 'How is the weather in Boston?' }, 'prompt-id-afc-bug');
108
+ // 4. Assert: Check the final state of the history.
109
+ const history = chat.getHistory();
110
+ // With the bug, history.length will be 3, because the first user message is dropped.
111
+ // The correct behavior is for the history to contain all 4 turns.
112
+ expect(history.length).toBe(4);
113
+ // Crucially, assert that the very first turn in the history matches the user's initial message.
114
+ // This is the assertion that will fail.
115
+ const firstTurn = history[0];
116
+ expect(firstTurn.role).toBe('user');
117
+ expect(firstTurn?.parts[0].text).toBe('How is the weather in Boston?');
118
+ // Verify the rest of the history is also correct.
119
+ const secondTurn = history[1];
120
+ expect(secondTurn.role).toBe('model');
121
+ expect(secondTurn?.parts[0].functionCall).toBeDefined();
122
+ const thirdTurn = history[2];
123
+ expect(thirdTurn.role).toBe('user');
124
+ expect(thirdTurn?.parts[0].functionResponse).toBeDefined();
125
+ const fourthTurn = history[3];
126
+ expect(fourthTurn.role).toBe('model');
127
+ expect(fourthTurn?.parts[0].text).toContain('72 degrees and sunny');
128
+ });
129
+ it('should throw an error when attempting to add a user turn after another user turn', async () => {
130
+ // 1. Setup: Create a history that already ends with a user turn (a functionResponse).
131
+ const initialHistory = [
132
+ { role: 'user', parts: [{ text: 'Initial prompt' }] },
133
+ {
134
+ role: 'model',
135
+ parts: [{ functionCall: { name: 'test_tool', args: {} } }],
136
+ },
137
+ {
138
+ role: 'user',
139
+ parts: [{ functionResponse: { name: 'test_tool', response: {} } }],
140
+ },
141
+ ];
142
+ chat.setHistory(initialHistory);
143
+ // 2. Mock a valid model response so the call doesn't fail for other reasons.
144
+ const mockResponse = {
145
+ candidates: [
146
+ { content: { role: 'model', parts: [{ text: 'some response' }] } },
147
+ ],
148
+ };
149
+ vi.mocked(mockModelsModule.generateContent).mockResolvedValue(mockResponse);
150
+ // 3. Action & Assert: Expect that sending another user message immediately
151
+ // after a user-role turn throws the specific error.
152
+ await expect(chat.sendMessage({ message: 'This is an invalid consecutive user message' }, 'prompt-id-1')).rejects.toThrow('Cannot add a user turn after another user turn.');
153
+ });
154
+ it('should preserve text parts that are in the same response as a thought', async () => {
155
+ // 1. Mock the API to return a single response containing both a thought and visible text.
156
+ const mixedContentResponse = {
157
+ candidates: [
158
+ {
159
+ content: {
160
+ role: 'model',
161
+ parts: [
162
+ { thought: 'This is a thought.' },
163
+ { text: 'This is the visible text that should not be lost.' },
164
+ ],
165
+ },
166
+ },
167
+ ],
168
+ };
169
+ vi.mocked(mockModelsModule.generateContent).mockResolvedValue(mixedContentResponse);
170
+ // 2. Action: Send a standard, non-streaming message.
171
+ await chat.sendMessage({ message: 'test message' }, 'prompt-id-mixed-response');
172
+ // 3. Assert: Check the final state of the history.
173
+ const history = chat.getHistory();
174
+ // The history should contain two turns: the user's message and the model's response.
175
+ expect(history.length).toBe(2);
176
+ const modelTurn = history[1];
177
+ expect(modelTurn.role).toBe('model');
178
+ // CRUCIAL ASSERTION:
179
+ // Buggy code would discard the entire response because a "thought" was present,
180
+ // resulting in an empty placeholder turn with 0 parts.
181
+ // The corrected code will pass, preserving the single visible text part.
182
+ expect(modelTurn?.parts?.length).toBe(1);
183
+ expect(modelTurn?.parts[0].text).toBe('This is the visible text that should not be lost.');
184
+ });
185
+ it('should add a placeholder model turn when a tool call is followed by an empty model response', async () => {
186
+ // 1. Setup: A history where the model has just made a function call.
187
+ const initialHistory = [
188
+ {
189
+ role: 'user',
190
+ parts: [{ text: 'Find a good Italian restaurant for me.' }],
191
+ },
192
+ {
193
+ role: 'model',
194
+ parts: [
195
+ {
196
+ functionCall: {
197
+ name: 'find_restaurant',
198
+ args: { cuisine: 'Italian' },
199
+ },
200
+ },
201
+ ],
202
+ },
203
+ ];
204
+ chat.setHistory(initialHistory);
205
+ // 2. Mock the API to return an empty/thought-only response.
206
+ const emptyModelResponse = {
207
+ candidates: [
208
+ { content: { role: 'model', parts: [{ thought: true }] } },
209
+ ],
210
+ };
211
+ vi.mocked(mockModelsModule.generateContent).mockResolvedValue(emptyModelResponse);
212
+ // 3. Action: Send the function response back to the model.
213
+ await chat.sendMessage({
214
+ message: {
215
+ functionResponse: {
216
+ name: 'find_restaurant',
217
+ response: { name: 'Vesuvio' },
218
+ },
219
+ },
220
+ }, 'prompt-id-1');
221
+ // 4. Assert: The history should now have four valid, alternating turns.
222
+ const history = chat.getHistory();
223
+ expect(history.length).toBe(4);
224
+ // The final turn must be the empty model placeholder.
225
+ const lastTurn = history[3];
226
+ expect(lastTurn.role).toBe('model');
227
+ expect(lastTurn?.parts?.length).toBe(0);
228
+ // The second-to-last turn must be the function response we sent.
229
+ const secondToLastTurn = history[2];
230
+ expect(secondToLastTurn.role).toBe('user');
231
+ expect(secondToLastTurn?.parts[0].functionResponse).toBeDefined();
232
+ });
48
233
  it('should call generateContent with the correct parameters', async () => {
49
234
  const response = {
50
235
  candidates: [
@@ -70,6 +255,309 @@ describe('GeminiChat', () => {
70
255
  });
71
256
  });
72
257
  describe('sendMessageStream', () => {
258
+ it('should succeed if a tool call is followed by an empty part', async () => {
259
+ // 1. Mock a stream that contains a tool call, then an invalid (empty) part.
260
+ const streamWithToolCall = (async function* () {
261
+ yield {
262
+ candidates: [
263
+ {
264
+ content: {
265
+ role: 'model',
266
+ parts: [{ functionCall: { name: 'test_tool', args: {} } }],
267
+ },
268
+ },
269
+ ],
270
+ };
271
+ // This second chunk is invalid according to isValidResponse
272
+ yield {
273
+ candidates: [
274
+ {
275
+ content: {
276
+ role: 'model',
277
+ parts: [{ text: '' }],
278
+ },
279
+ },
280
+ ],
281
+ };
282
+ })();
283
+ vi.mocked(mockModelsModule.generateContentStream).mockResolvedValue(streamWithToolCall);
284
+ // 2. Action & Assert: The stream processing should complete without throwing an error
285
+ // because the presence of a tool call makes the empty final chunk acceptable.
286
+ const stream = await chat.sendMessageStream({ message: 'test message' }, 'prompt-id-tool-call-empty-end');
287
+ await expect((async () => {
288
+ for await (const _ of stream) {
289
+ /* consume stream */
290
+ }
291
+ })()).resolves.not.toThrow();
292
+ // 3. Verify history was recorded correctly
293
+ const history = chat.getHistory();
294
+ expect(history.length).toBe(2); // user turn + model turn
295
+ const modelTurn = history[1];
296
+ expect(modelTurn?.parts?.length).toBe(1); // The empty part is discarded
297
+ expect(modelTurn?.parts[0].functionCall).toBeDefined();
298
+ });
299
+ it('should succeed if the stream ends with an empty part but has a valid finishReason', async () => {
300
+ // 1. Mock a stream that ends with an invalid part but has a 'STOP' finish reason.
301
+ const streamWithValidFinish = (async function* () {
302
+ yield {
303
+ candidates: [
304
+ {
305
+ content: {
306
+ role: 'model',
307
+ parts: [{ text: 'Initial content...' }],
308
+ },
309
+ },
310
+ ],
311
+ };
312
+ // This second chunk is invalid, but the finishReason should save it from retrying.
313
+ yield {
314
+ candidates: [
315
+ {
316
+ content: {
317
+ role: 'model',
318
+ parts: [{ text: '' }],
319
+ },
320
+ finishReason: 'STOP',
321
+ },
322
+ ],
323
+ };
324
+ })();
325
+ vi.mocked(mockModelsModule.generateContentStream).mockResolvedValue(streamWithValidFinish);
326
+ // 2. Action & Assert: The stream should complete successfully because the valid
327
+ // finishReason overrides the invalid final chunk.
328
+ const stream = await chat.sendMessageStream({ message: 'test message' }, 'prompt-id-valid-finish-empty-end');
329
+ await expect((async () => {
330
+ for await (const _ of stream) {
331
+ /* consume stream */
332
+ }
333
+ })()).resolves.not.toThrow();
334
+ // 3. Verify history was recorded correctly
335
+ const history = chat.getHistory();
336
+ expect(history.length).toBe(2);
337
+ const modelTurn = history[1];
338
+ expect(modelTurn?.parts?.length).toBe(1); // The empty part is discarded
339
+ expect(modelTurn?.parts[0].text).toBe('Initial content...');
340
+ });
341
+ it('should not consolidate text into a part that also contains a functionCall', async () => {
342
+ // 1. Mock the API to stream a malformed part followed by a valid text part.
343
+ const multiChunkStream = (async function* () {
344
+ // This malformed part has both text and a functionCall.
345
+ yield {
346
+ candidates: [
347
+ {
348
+ content: {
349
+ role: 'model',
350
+ parts: [
351
+ {
352
+ text: 'Some text',
353
+ functionCall: { name: 'do_stuff', args: {} },
354
+ },
355
+ ],
356
+ },
357
+ },
358
+ ],
359
+ };
360
+ // This valid text part should NOT be merged into the malformed one.
361
+ yield {
362
+ candidates: [
363
+ {
364
+ content: {
365
+ role: 'model',
366
+ parts: [{ text: ' that should not be merged.' }],
367
+ },
368
+ },
369
+ ],
370
+ };
371
+ })();
372
+ vi.mocked(mockModelsModule.generateContentStream).mockResolvedValue(multiChunkStream);
373
+ // 2. Action: Send a message and consume the stream.
374
+ const stream = await chat.sendMessageStream({ message: 'test message' }, 'prompt-id-malformed-chunk');
375
+ for await (const _ of stream) {
376
+ // Consume the stream to trigger history recording.
377
+ }
378
+ // 3. Assert: Check that the final history was not incorrectly consolidated.
379
+ const history = chat.getHistory();
380
+ expect(history.length).toBe(2);
381
+ const modelTurn = history[1];
382
+ // CRUCIAL ASSERTION: There should be two separate parts.
383
+ // The old, non-strict logic would incorrectly merge them, resulting in one part.
384
+ expect(modelTurn?.parts?.length).toBe(2);
385
+ // Verify the contents of each part.
386
+ expect(modelTurn?.parts[0].text).toBe('Some text');
387
+ expect(modelTurn?.parts[0].functionCall).toBeDefined();
388
+ expect(modelTurn?.parts[1].text).toBe(' that should not be merged.');
389
+ });
390
+ it('should consolidate subsequent text chunks after receiving an empty text chunk', async () => {
391
+ // 1. Mock the API to return a stream where one chunk is just an empty text part.
392
+ const multiChunkStream = (async function* () {
393
+ yield {
394
+ candidates: [
395
+ { content: { role: 'model', parts: [{ text: 'Hello' }] } },
396
+ ],
397
+ };
398
+ // FIX: The original test used { text: '' }, which is invalid.
399
+ // A chunk can be empty but still valid. This chunk is now removed
400
+ // as the important part is consolidating what comes after.
401
+ yield {
402
+ candidates: [
403
+ { content: { role: 'model', parts: [{ text: ' World!' }] } },
404
+ ],
405
+ };
406
+ })();
407
+ vi.mocked(mockModelsModule.generateContentStream).mockResolvedValue(multiChunkStream);
408
+ // 2. Action: Send a message and consume the stream.
409
+ const stream = await chat.sendMessageStream({ message: 'test message' }, 'prompt-id-empty-chunk-consolidation');
410
+ for await (const _ of stream) {
411
+ // Consume the stream
412
+ }
413
+ // 3. Assert: Check that the final history was correctly consolidated.
414
+ const history = chat.getHistory();
415
+ expect(history.length).toBe(2);
416
+ const modelTurn = history[1];
417
+ expect(modelTurn?.parts?.length).toBe(1);
418
+ expect(modelTurn?.parts[0].text).toBe('Hello World!');
419
+ });
420
+ it('should consolidate adjacent text parts that arrive in separate stream chunks', async () => {
421
+ // 1. Mock the API to return a stream of multiple, adjacent text chunks.
422
+ const multiChunkStream = (async function* () {
423
+ yield {
424
+ candidates: [
425
+ { content: { role: 'model', parts: [{ text: 'This is the ' }] } },
426
+ ],
427
+ };
428
+ yield {
429
+ candidates: [
430
+ { content: { role: 'model', parts: [{ text: 'first part.' }] } },
431
+ ],
432
+ };
433
+ // This function call should break the consolidation.
434
+ yield {
435
+ candidates: [
436
+ {
437
+ content: {
438
+ role: 'model',
439
+ parts: [{ functionCall: { name: 'do_stuff', args: {} } }],
440
+ },
441
+ },
442
+ ],
443
+ };
444
+ yield {
445
+ candidates: [
446
+ {
447
+ content: {
448
+ role: 'model',
449
+ parts: [{ text: 'This is the second part.' }],
450
+ },
451
+ },
452
+ ],
453
+ };
454
+ })();
455
+ vi.mocked(mockModelsModule.generateContentStream).mockResolvedValue(multiChunkStream);
456
+ // 2. Action: Send a message and consume the stream.
457
+ const stream = await chat.sendMessageStream({ message: 'test message' }, 'prompt-id-multi-chunk');
458
+ for await (const _ of stream) {
459
+ // Consume the stream to trigger history recording.
460
+ }
461
+ // 3. Assert: Check that the final history was correctly consolidated.
462
+ const history = chat.getHistory();
463
+ // The history should contain the user's turn and ONE consolidated model turn.
464
+ expect(history.length).toBe(2);
465
+ const modelTurn = history[1];
466
+ expect(modelTurn.role).toBe('model');
467
+ // The model turn should have 3 distinct parts: the merged text, the function call, and the final text.
468
+ expect(modelTurn?.parts?.length).toBe(3);
469
+ expect(modelTurn?.parts[0].text).toBe('This is the first part.');
470
+ expect(modelTurn.parts[1].functionCall).toBeDefined();
471
+ expect(modelTurn.parts[2].text).toBe('This is the second part.');
472
+ });
473
+ it('should preserve text parts that stream in the same chunk as a thought', async () => {
474
+ // 1. Mock the API to return a single chunk containing both a thought and visible text.
475
+ const mixedContentStream = (async function* () {
476
+ yield {
477
+ candidates: [
478
+ {
479
+ content: {
480
+ role: 'model',
481
+ parts: [
482
+ { thought: 'This is a thought.' },
483
+ { text: 'This is the visible text that should not be lost.' },
484
+ ],
485
+ },
486
+ },
487
+ ],
488
+ };
489
+ })();
490
+ vi.mocked(mockModelsModule.generateContentStream).mockResolvedValue(mixedContentStream);
491
+ // 2. Action: Send a message and fully consume the stream to trigger history recording.
492
+ const stream = await chat.sendMessageStream({ message: 'test message' }, 'prompt-id-mixed-chunk');
493
+ for await (const _ of stream) {
494
+ // This loop consumes the stream.
495
+ }
496
+ // 3. Assert: Check the final state of the history.
497
+ const history = chat.getHistory();
498
+ // The history should contain two turns: the user's message and the model's response.
499
+ expect(history.length).toBe(2);
500
+ const modelTurn = history[1];
501
+ expect(modelTurn.role).toBe('model');
502
+ // CRUCIAL ASSERTION:
503
+ // The buggy code would fail here, resulting in parts.length being 0.
504
+ // The corrected code will pass, preserving the single visible text part.
505
+ expect(modelTurn?.parts?.length).toBe(1);
506
+ expect(modelTurn?.parts[0].text).toBe('This is the visible text that should not be lost.');
507
+ });
508
+ it('should add a placeholder model turn when a tool call is followed by an empty stream response', async () => {
509
+ // 1. Setup: A history where the model has just made a function call.
510
+ const initialHistory = [
511
+ {
512
+ role: 'user',
513
+ parts: [{ text: 'Find a good Italian restaurant for me.' }],
514
+ },
515
+ {
516
+ role: 'model',
517
+ parts: [
518
+ {
519
+ functionCall: {
520
+ name: 'find_restaurant',
521
+ args: { cuisine: 'Italian' },
522
+ },
523
+ },
524
+ ],
525
+ },
526
+ ];
527
+ chat.setHistory(initialHistory);
528
+ // 2. Mock the API to return an empty/thought-only stream.
529
+ const emptyStreamResponse = (async function* () {
530
+ yield {
531
+ candidates: [
532
+ { content: { role: 'model', parts: [{ thought: true }] } },
533
+ ],
534
+ };
535
+ })();
536
+ vi.mocked(mockModelsModule.generateContentStream).mockResolvedValue(emptyStreamResponse);
537
+ // 3. Action: Send the function response back to the model and consume the stream.
538
+ const stream = await chat.sendMessageStream({
539
+ message: {
540
+ functionResponse: {
541
+ name: 'find_restaurant',
542
+ response: { name: 'Vesuvio' },
543
+ },
544
+ },
545
+ }, 'prompt-id-stream-1');
546
+ for await (const _ of stream) {
547
+ // This loop consumes the stream to trigger the internal logic.
548
+ }
549
+ // 4. Assert: The history should now have four valid, alternating turns.
550
+ const history = chat.getHistory();
551
+ expect(history.length).toBe(4);
552
+ // The final turn must be the empty model placeholder.
553
+ const lastTurn = history[3];
554
+ expect(lastTurn.role).toBe('model');
555
+ expect(lastTurn?.parts?.length).toBe(0);
556
+ // The second-to-last turn must be the function response we sent.
557
+ const secondToLastTurn = history[2];
558
+ expect(secondToLastTurn.role).toBe('user');
559
+ expect(secondToLastTurn?.parts[0].functionResponse).toBeDefined();
560
+ });
73
561
  it('should call generateContentStream with the correct parameters', async () => {
74
562
  const response = (async function* () {
75
563
  yield {
@@ -88,7 +576,10 @@ describe('GeminiChat', () => {
88
576
  };
89
577
  })();
90
578
  vi.mocked(mockModelsModule.generateContentStream).mockResolvedValue(response);
91
- await chat.sendMessageStream({ message: 'hello' }, 'prompt-id-1');
579
+ const stream = await chat.sendMessageStream({ message: 'hello' }, 'prompt-id-1');
580
+ for await (const _ of stream) {
581
+ // consume stream to trigger internal logic
582
+ }
92
583
  expect(mockModelsModule.generateContentStream).toHaveBeenCalledWith({
93
584
  model: 'gemini-pro',
94
585
  contents: [{ role: 'user', parts: [{ text: 'hello' }] }],
@@ -101,295 +592,128 @@ describe('GeminiChat', () => {
101
592
  role: 'user',
102
593
  parts: [{ text: 'User input' }],
103
594
  };
104
- it('should add user input and a single model output to history', () => {
595
+ it('should consolidate all consecutive model turns into a single turn', () => {
596
+ const userInput = {
597
+ role: 'user',
598
+ parts: [{ text: 'User input' }],
599
+ };
600
+ // This simulates a multi-part model response with different part types.
105
601
  const modelOutput = [
106
- { role: 'model', parts: [{ text: 'Model output' }] },
602
+ { role: 'model', parts: [{ text: 'Thinking...' }] },
603
+ {
604
+ role: 'model',
605
+ parts: [{ functionCall: { name: 'do_stuff', args: {} } }],
606
+ },
107
607
  ];
108
- // @ts-expect-error Accessing private method for testing purposes
608
+ // @ts-expect-error Accessing private method for testing
109
609
  chat.recordHistory(userInput, modelOutput);
110
610
  const history = chat.getHistory();
111
- expect(history).toEqual([userInput, modelOutput[0]]);
112
- });
113
- it('should consolidate adjacent model outputs', () => {
114
- const modelOutputParts = [
115
- { role: 'model', parts: [{ text: 'Model part 1' }] },
116
- { role: 'model', parts: [{ text: 'Model part 2' }] },
117
- ];
118
- // @ts-expect-error Accessing private method for testing purposes
119
- chat.recordHistory(userInput, modelOutputParts);
120
- const history = chat.getHistory();
121
- expect(history.length).toBe(2);
122
- expect(history[0]).toEqual(userInput);
123
- expect(history[1].role).toBe('model');
124
- expect(history[1].parts).toEqual([{ text: 'Model part 1Model part 2' }]);
125
- });
126
- it('should handle a mix of user and model roles in outputContents (though unusual)', () => {
127
- const mixedOutput = [
128
- { role: 'model', parts: [{ text: 'Model 1' }] },
129
- { role: 'user', parts: [{ text: 'Unexpected User' }] }, // This should be pushed as is
130
- { role: 'model', parts: [{ text: 'Model 2' }] },
131
- ];
132
- // @ts-expect-error Accessing private method for testing purposes
133
- chat.recordHistory(userInput, mixedOutput);
134
- const history = chat.getHistory();
135
- expect(history.length).toBe(4); // user, model1, user_unexpected, model2
136
- expect(history[0]).toEqual(userInput);
137
- expect(history[1]).toEqual(mixedOutput[0]);
138
- expect(history[2]).toEqual(mixedOutput[1]);
139
- expect(history[3]).toEqual(mixedOutput[2]);
140
- });
141
- it('should consolidate multiple adjacent model outputs correctly', () => {
142
- const modelOutputParts = [
143
- { role: 'model', parts: [{ text: 'M1' }] },
144
- { role: 'model', parts: [{ text: 'M2' }] },
145
- { role: 'model', parts: [{ text: 'M3' }] },
146
- ];
147
- // @ts-expect-error Accessing private method for testing purposes
148
- chat.recordHistory(userInput, modelOutputParts);
149
- const history = chat.getHistory();
611
+ // The history should contain the user's turn and ONE consolidated model turn.
612
+ // The old code would fail here, resulting in a length of 3.
613
+ //expect(history).toBe([]);
150
614
  expect(history.length).toBe(2);
151
- expect(history[1].parts).toEqual([{ text: 'M1M2M3' }]);
152
- });
153
- it('should not consolidate if roles are different between model outputs', () => {
154
- const modelOutputParts = [
155
- { role: 'model', parts: [{ text: 'M1' }] },
156
- { role: 'user', parts: [{ text: 'Interjecting User' }] },
157
- { role: 'model', parts: [{ text: 'M2' }] },
158
- ];
159
- // @ts-expect-error Accessing private method for testing purposes
160
- chat.recordHistory(userInput, modelOutputParts);
161
- const history = chat.getHistory();
162
- expect(history.length).toBe(4); // user, M1, Interjecting User, M2
163
- expect(history[1].parts).toEqual([{ text: 'M1' }]);
164
- expect(history[3].parts).toEqual([{ text: 'M2' }]);
615
+ const modelTurn = history[1];
616
+ expect(modelTurn.role).toBe('model');
617
+ // The consolidated turn should contain both the text part and the functionCall part.
618
+ expect(modelTurn?.parts?.length).toBe(2);
619
+ expect(modelTurn?.parts[0].text).toBe('Thinking...');
620
+ expect(modelTurn?.parts[1].functionCall).toBeDefined();
165
621
  });
166
- it('should merge with last history entry if it is also a model output', () => {
167
- // @ts-expect-error Accessing private property for test setup
168
- chat.history = [
169
- userInput,
170
- { role: 'model', parts: [{ text: 'Initial Model Output' }] },
171
- ]; // Prime the history
172
- const newModelOutput = [
173
- { role: 'model', parts: [{ text: 'New Model Part 1' }] },
174
- { role: 'model', parts: [{ text: 'New Model Part 2' }] },
175
- ];
176
- // @ts-expect-error Accessing private method for testing purposes
177
- chat.recordHistory(userInput, newModelOutput); // userInput here is for the *next* turn, but history is already primed
178
- // Reset and set up a more realistic scenario for merging with existing history
179
- chat = new GeminiChat(mockConfig, mockModelsModule, config, []);
180
- const firstUserInput = {
181
- role: 'user',
182
- parts: [{ text: 'First user input' }],
183
- };
184
- const firstModelOutput = [
185
- { role: 'model', parts: [{ text: 'First model response' }] },
186
- ];
187
- // @ts-expect-error Accessing private method for testing purposes
188
- chat.recordHistory(firstUserInput, firstModelOutput);
189
- const secondUserInput = {
190
- role: 'user',
191
- parts: [{ text: 'Second user input' }],
192
- };
193
- const secondModelOutput = [
194
- { role: 'model', parts: [{ text: 'Second model response part 1' }] },
195
- { role: 'model', parts: [{ text: 'Second model response part 2' }] },
622
+ it('should add a placeholder model turn when a tool call is followed by an empty response', () => {
623
+ // 1. Setup: A history where the model has just made a function call.
624
+ const initialHistory = [
625
+ { role: 'user', parts: [{ text: 'Initial prompt' }] },
626
+ {
627
+ role: 'model',
628
+ parts: [{ functionCall: { name: 'test_tool', args: {} } }],
629
+ },
196
630
  ];
197
- // @ts-expect-error Accessing private method for testing purposes
198
- chat.recordHistory(secondUserInput, secondModelOutput);
199
- const finalHistory = chat.getHistory();
200
- expect(finalHistory.length).toBe(4); // user1, model1, user2, model2(consolidated)
201
- expect(finalHistory[0]).toEqual(firstUserInput);
202
- expect(finalHistory[1]).toEqual(firstModelOutput[0]);
203
- expect(finalHistory[2]).toEqual(secondUserInput);
204
- expect(finalHistory[3].role).toBe('model');
205
- expect(finalHistory[3].parts).toEqual([
206
- { text: 'Second model response part 1Second model response part 2' },
207
- ]);
208
- });
209
- it('should correctly merge consolidated new output with existing model history', () => {
210
- // Setup: history ends with a model turn
211
- const initialUser = {
631
+ chat.setHistory(initialHistory);
632
+ // 2. Action: The user provides the tool's response, and the model's
633
+ // final output is empty (e.g., just a thought, which gets filtered out).
634
+ const functionResponse = {
212
635
  role: 'user',
213
- parts: [{ text: 'Initial user query' }],
636
+ parts: [{ functionResponse: { name: 'test_tool', response: {} } }],
214
637
  };
215
- const initialModel = {
216
- role: 'model',
217
- parts: [{ text: 'Initial model answer.' }],
218
- };
219
- chat = new GeminiChat(mockConfig, mockModelsModule, config, [
220
- initialUser,
221
- initialModel,
638
+ const emptyModelOutput = [];
639
+ // @ts-expect-error Accessing private method for testing
640
+ chat.recordHistory(functionResponse, emptyModelOutput, [
641
+ functionResponse,
222
642
  ]);
223
- // New interaction
224
- const currentUserInput = {
225
- role: 'user',
226
- parts: [{ text: 'Follow-up question' }],
227
- };
228
- const newModelParts = [
229
- { role: 'model', parts: [{ text: 'Part A of new answer.' }] },
230
- { role: 'model', parts: [{ text: 'Part B of new answer.' }] },
231
- ];
232
- // @ts-expect-error Accessing private method for testing purposes
233
- chat.recordHistory(currentUserInput, newModelParts);
643
+ // 3. Assert: The history should now have four valid, alternating turns.
234
644
  const history = chat.getHistory();
235
- // Expected: initialUser, initialModel, currentUserInput, consolidatedNewModelParts
236
645
  expect(history.length).toBe(4);
237
- expect(history[0]).toEqual(initialUser);
238
- expect(history[1]).toEqual(initialModel);
239
- expect(history[2]).toEqual(currentUserInput);
240
- expect(history[3].role).toBe('model');
241
- expect(history[3].parts).toEqual([
242
- { text: 'Part A of new answer.Part B of new answer.' },
243
- ]);
244
- });
245
- it('should handle empty modelOutput array', () => {
246
- // @ts-expect-error Accessing private method for testing purposes
247
- chat.recordHistory(userInput, []);
248
- const history = chat.getHistory();
249
- // If modelOutput is empty, it might push a default empty model part depending on isFunctionResponse
250
- // Assuming isFunctionResponse(userInput) is false for this simple text input
251
- expect(history.length).toBe(2);
252
- expect(history[0]).toEqual(userInput);
253
- expect(history[1].role).toBe('model');
254
- expect(history[1].parts).toEqual([]);
255
- });
256
- it('should handle aggregating modelOutput', () => {
257
- const modelOutputUndefinedParts = [
258
- { role: 'model', parts: [{ text: 'First model part' }] },
259
- { role: 'model', parts: [{ text: 'Second model part' }] },
260
- { role: 'model', parts: undefined }, // Test undefined parts
261
- { role: 'model', parts: [{ text: 'Third model part' }] },
262
- { role: 'model', parts: [] }, // Test empty parts array
263
- ];
264
- // @ts-expect-error Accessing private method for testing purposes
265
- chat.recordHistory(userInput, modelOutputUndefinedParts);
266
- const history = chat.getHistory();
267
- expect(history.length).toBe(5);
268
- expect(history[0]).toEqual(userInput);
269
- expect(history[1].role).toBe('model');
270
- expect(history[1].parts).toEqual([
271
- { text: 'First model partSecond model part' },
272
- ]);
273
- expect(history[2].role).toBe('model');
274
- expect(history[2].parts).toBeUndefined();
275
- expect(history[3].role).toBe('model');
276
- expect(history[3].parts).toEqual([{ text: 'Third model part' }]);
277
- expect(history[4].role).toBe('model');
278
- expect(history[4].parts).toEqual([]);
646
+ // The final turn must be the empty model placeholder.
647
+ const lastTurn = history[3];
648
+ expect(lastTurn.role).toBe('model');
649
+ expect(lastTurn?.parts?.length).toBe(0);
650
+ // The second-to-last turn must be the function response we provided.
651
+ const secondToLastTurn = history[2];
652
+ expect(secondToLastTurn.role).toBe('user');
653
+ expect(secondToLastTurn?.parts[0].functionResponse).toBeDefined();
279
654
  });
280
- it('should handle modelOutput with parts being undefined or empty (if they pass initial every check)', () => {
281
- const modelOutputUndefinedParts = [
282
- { role: 'model', parts: [{ text: 'Text part' }] },
283
- { role: 'model', parts: undefined }, // Test undefined parts
284
- { role: 'model', parts: [] }, // Test empty parts array
285
- ];
286
- // @ts-expect-error Accessing private method for testing purposes
287
- chat.recordHistory(userInput, modelOutputUndefinedParts);
288
- const history = chat.getHistory();
289
- expect(history.length).toBe(4); // userInput, model1 (text), model2 (undefined parts), model3 (empty parts)
290
- expect(history[0]).toEqual(userInput);
291
- expect(history[1].role).toBe('model');
292
- expect(history[1].parts).toEqual([{ text: 'Text part' }]);
293
- expect(history[2].role).toBe('model');
294
- expect(history[2].parts).toBeUndefined();
295
- expect(history[3].role).toBe('model');
296
- expect(history[3].parts).toEqual([]);
297
- });
298
- it('should correctly handle automaticFunctionCallingHistory', () => {
299
- const afcHistory = [
300
- { role: 'user', parts: [{ text: 'AFC User' }] },
301
- { role: 'model', parts: [{ text: 'AFC Model' }] },
302
- ];
303
- const modelOutput = [
304
- { role: 'model', parts: [{ text: 'Regular Model Output' }] },
305
- ];
306
- // @ts-expect-error Accessing private method for testing purposes
307
- chat.recordHistory(userInput, modelOutput, afcHistory);
308
- const history = chat.getHistory();
309
- expect(history.length).toBe(3);
310
- expect(history[0]).toEqual(afcHistory[0]);
311
- expect(history[1]).toEqual(afcHistory[1]);
312
- expect(history[2]).toEqual(modelOutput[0]);
313
- });
314
- it('should add userInput if AFC history is present but empty', () => {
655
+ it('should add user input and a single model output to history', () => {
315
656
  const modelOutput = [
316
- { role: 'model', parts: [{ text: 'Model Output' }] },
657
+ { role: 'model', parts: [{ text: 'Model output' }] },
317
658
  ];
318
- // @ts-expect-error Accessing private method for testing purposes
319
- chat.recordHistory(userInput, modelOutput, []); // Empty AFC history
659
+ // @ts-expect-error Accessing private method for testing
660
+ chat.recordHistory(userInput, modelOutput);
320
661
  const history = chat.getHistory();
321
662
  expect(history.length).toBe(2);
322
663
  expect(history[0]).toEqual(userInput);
323
664
  expect(history[1]).toEqual(modelOutput[0]);
324
665
  });
325
- it('should skip "thought" content from modelOutput', () => {
326
- const modelOutputWithThought = [
327
- { role: 'model', parts: [{ thought: true }, { text: 'Visible text' }] },
328
- { role: 'model', parts: [{ text: 'Another visible text' }] },
666
+ it('should consolidate adjacent text parts from multiple content objects', () => {
667
+ const modelOutput = [
668
+ { role: 'model', parts: [{ text: 'Part 1.' }] },
669
+ { role: 'model', parts: [{ text: ' Part 2.' }] },
670
+ { role: 'model', parts: [{ text: ' Part 3.' }] },
329
671
  ];
330
- // @ts-expect-error Accessing private method for testing purposes
331
- chat.recordHistory(userInput, modelOutputWithThought);
672
+ // @ts-expect-error Accessing private method for testing
673
+ chat.recordHistory(userInput, modelOutput);
332
674
  const history = chat.getHistory();
333
- expect(history.length).toBe(2); // User input + consolidated model output
334
- expect(history[0]).toEqual(userInput);
675
+ expect(history.length).toBe(2);
335
676
  expect(history[1].role).toBe('model');
336
- // The 'thought' part is skipped, 'Another visible text' becomes the first part.
337
- expect(history[1].parts).toEqual([{ text: 'Another visible text' }]);
338
- });
339
- it('should skip "thought" content even if it is the only content', () => {
340
- const modelOutputOnlyThought = [
341
- { role: 'model', parts: [{ thought: true }] },
342
- ];
343
- // @ts-expect-error Accessing private method for testing purposes
344
- chat.recordHistory(userInput, modelOutputOnlyThought);
345
- const history = chat.getHistory();
346
- expect(history.length).toBe(1); // User input + default empty model part
347
- expect(history[0]).toEqual(userInput);
677
+ expect(history[1].parts).toEqual([{ text: 'Part 1. Part 2. Part 3.' }]);
348
678
  });
349
- it('should correctly consolidate text parts when a thought part is in between', () => {
350
- const modelOutputMixed = [
351
- { role: 'model', parts: [{ text: 'Part 1.' }] },
352
- {
353
- role: 'model',
354
- parts: [{ thought: true }, { text: 'Should be skipped' }],
355
- },
356
- { role: 'model', parts: [{ text: 'Part 2.' }] },
357
- ];
358
- // @ts-expect-error Accessing private method for testing purposes
359
- chat.recordHistory(userInput, modelOutputMixed);
679
+ it('should add an empty placeholder turn if modelOutput is empty', () => {
680
+ // This simulates receiving a pre-filtered, thought-only response.
681
+ const emptyModelOutput = [];
682
+ // @ts-expect-error Accessing private method for testing
683
+ chat.recordHistory(userInput, emptyModelOutput);
360
684
  const history = chat.getHistory();
361
685
  expect(history.length).toBe(2);
362
686
  expect(history[0]).toEqual(userInput);
363
687
  expect(history[1].role).toBe('model');
364
- expect(history[1].parts).toEqual([{ text: 'Part 1.Part 2.' }]);
688
+ expect(history[1].parts).toEqual([]);
365
689
  });
366
- it('should handle multiple thought parts correctly', () => {
367
- const modelOutputMultipleThoughts = [
368
- { role: 'model', parts: [{ thought: true }] },
369
- { role: 'model', parts: [{ text: 'Visible 1' }] },
370
- { role: 'model', parts: [{ thought: true }] },
371
- { role: 'model', parts: [{ text: 'Visible 2' }] },
690
+ it('should preserve model outputs with undefined or empty parts arrays', () => {
691
+ const malformedOutput = [
692
+ { role: 'model', parts: [{ text: 'Text part' }] },
693
+ { role: 'model', parts: undefined },
694
+ { role: 'model', parts: [] },
372
695
  ];
373
- // @ts-expect-error Accessing private method for testing purposes
374
- chat.recordHistory(userInput, modelOutputMultipleThoughts);
696
+ // @ts-expect-error Accessing private method for testing
697
+ chat.recordHistory(userInput, malformedOutput);
375
698
  const history = chat.getHistory();
376
- expect(history.length).toBe(2);
377
- expect(history[0]).toEqual(userInput);
378
- expect(history[1].role).toBe('model');
379
- expect(history[1].parts).toEqual([{ text: 'Visible 1Visible 2' }]);
699
+ expect(history.length).toBe(4); // userInput + 3 model turns
700
+ expect(history[1].parts).toEqual([{ text: 'Text part' }]);
701
+ expect(history[2].parts).toBeUndefined();
702
+ expect(history[3].parts).toEqual([]);
380
703
  });
381
- it('should handle thought part at the end of outputContents', () => {
382
- const modelOutputThoughtAtEnd = [
383
- { role: 'model', parts: [{ text: 'Visible text' }] },
384
- { role: 'model', parts: [{ thought: true }] },
704
+ it('should not consolidate content with different roles', () => {
705
+ const mixedOutput = [
706
+ { role: 'model', parts: [{ text: 'Model 1' }] },
707
+ { role: 'user', parts: [{ text: 'Unexpected User' }] },
708
+ { role: 'model', parts: [{ text: 'Model 2' }] },
385
709
  ];
386
- // @ts-expect-error Accessing private method for testing purposes
387
- chat.recordHistory(userInput, modelOutputThoughtAtEnd);
710
+ // @ts-expect-error Accessing private method for testing
711
+ chat.recordHistory(userInput, mixedOutput);
388
712
  const history = chat.getHistory();
389
- expect(history.length).toBe(2);
390
- expect(history[0]).toEqual(userInput);
391
- expect(history[1].role).toBe('model');
392
- expect(history[1].parts).toEqual([{ text: 'Visible text' }]);
713
+ expect(history.length).toBe(4); // userInput, model1, unexpected_user, model2
714
+ expect(history[1]).toEqual(mixedOutput[0]);
715
+ expect(history[2]).toEqual(mixedOutput[1]);
716
+ expect(history[3]).toEqual(mixedOutput[2]);
393
717
  });
394
718
  });
395
719
  describe('addHistory', () => {
@@ -420,5 +744,286 @@ describe('GeminiChat', () => {
420
744
  expect(history[1]).toEqual(content2);
421
745
  });
422
746
  });
747
+ describe('sendMessageStream with retries', () => {
748
+ it('should retry on invalid content, succeed, and report metrics', async () => {
749
+ // Use mockImplementationOnce to provide a fresh, promise-wrapped generator for each attempt.
750
+ vi.mocked(mockModelsModule.generateContentStream)
751
+ .mockImplementationOnce(async () =>
752
+ // First call returns an invalid stream
753
+ (async function* () {
754
+ yield {
755
+ candidates: [{ content: { parts: [{ text: '' }] } }], // Invalid empty text part
756
+ };
757
+ })())
758
+ .mockImplementationOnce(async () =>
759
+ // Second call returns a valid stream
760
+ (async function* () {
761
+ yield {
762
+ candidates: [
763
+ { content: { parts: [{ text: 'Successful response' }] } },
764
+ ],
765
+ };
766
+ })());
767
+ const stream = await chat.sendMessageStream({ message: 'test' }, 'prompt-id-retry-success');
768
+ const chunks = [];
769
+ for await (const chunk of stream) {
770
+ chunks.push(chunk);
771
+ }
772
+ // Assertions
773
+ expect(mockLogInvalidChunk).toHaveBeenCalledTimes(1);
774
+ expect(mockLogContentRetry).toHaveBeenCalledTimes(1);
775
+ expect(mockLogContentRetryFailure).not.toHaveBeenCalled();
776
+ expect(mockModelsModule.generateContentStream).toHaveBeenCalledTimes(2);
777
+ expect(chunks.some((c) => c.candidates?.[0]?.content?.parts?.[0]?.text ===
778
+ 'Successful response')).toBe(true);
779
+ // Check that history was recorded correctly once, with no duplicates.
780
+ const history = chat.getHistory();
781
+ expect(history.length).toBe(2);
782
+ expect(history[0]).toEqual({
783
+ role: 'user',
784
+ parts: [{ text: 'test' }],
785
+ });
786
+ expect(history[1]).toEqual({
787
+ role: 'model',
788
+ parts: [{ text: 'Successful response' }],
789
+ });
790
+ });
791
+ it('should fail after all retries on persistent invalid content and report metrics', async () => {
792
+ vi.mocked(mockModelsModule.generateContentStream).mockImplementation(async () => (async function* () {
793
+ yield {
794
+ candidates: [
795
+ {
796
+ content: {
797
+ parts: [{ text: '' }],
798
+ role: 'model',
799
+ },
800
+ },
801
+ ],
802
+ };
803
+ })());
804
+ // This helper function consumes the stream and allows us to test for rejection.
805
+ async function consumeStreamAndExpectError() {
806
+ const stream = await chat.sendMessageStream({ message: 'test' }, 'prompt-id-retry-fail');
807
+ for await (const _ of stream) {
808
+ // Must loop to trigger the internal logic that throws.
809
+ }
810
+ }
811
+ await expect(consumeStreamAndExpectError()).rejects.toThrow(EmptyStreamError);
812
+ // Should be called 3 times (initial + 2 retries)
813
+ expect(mockModelsModule.generateContentStream).toHaveBeenCalledTimes(3);
814
+ expect(mockLogInvalidChunk).toHaveBeenCalledTimes(3);
815
+ expect(mockLogContentRetry).toHaveBeenCalledTimes(2);
816
+ expect(mockLogContentRetryFailure).toHaveBeenCalledTimes(1);
817
+ // History should be clean, as if the failed turn never happened.
818
+ const history = chat.getHistory();
819
+ expect(history.length).toBe(0);
820
+ });
821
+ });
822
+ it('should correctly retry and append to an existing history mid-conversation', async () => {
823
+ // 1. Setup
824
+ const initialHistory = [
825
+ { role: 'user', parts: [{ text: 'First question' }] },
826
+ { role: 'model', parts: [{ text: 'First answer' }] },
827
+ ];
828
+ chat.setHistory(initialHistory);
829
+ // 2. Mock the API to fail once with an empty stream, then succeed.
830
+ vi.mocked(mockModelsModule.generateContentStream)
831
+ .mockImplementationOnce(async () => (async function* () {
832
+ yield {
833
+ candidates: [{ content: { parts: [{ text: '' }] } }],
834
+ };
835
+ })())
836
+ .mockImplementationOnce(async () =>
837
+ // Second attempt succeeds
838
+ (async function* () {
839
+ yield {
840
+ candidates: [{ content: { parts: [{ text: 'Second answer' }] } }],
841
+ };
842
+ })());
843
+ // 3. Send a new message
844
+ const stream = await chat.sendMessageStream({ message: 'Second question' }, 'prompt-id-retry-existing');
845
+ for await (const _ of stream) {
846
+ // consume stream
847
+ }
848
+ // 4. Assert the final history and metrics
849
+ const history = chat.getHistory();
850
+ expect(history.length).toBe(4);
851
+ // Assert that the correct metrics were reported for one empty-stream retry
852
+ expect(mockLogContentRetry).toHaveBeenCalledTimes(1);
853
+ // Explicitly verify the structure of each part to satisfy TypeScript
854
+ const turn1 = history[0];
855
+ if (!turn1?.parts?.[0] || !('text' in turn1.parts[0])) {
856
+ throw new Error('Test setup error: First turn is not a valid text part.');
857
+ }
858
+ expect(turn1.parts[0].text).toBe('First question');
859
+ const turn2 = history[1];
860
+ if (!turn2?.parts?.[0] || !('text' in turn2.parts[0])) {
861
+ throw new Error('Test setup error: Second turn is not a valid text part.');
862
+ }
863
+ expect(turn2.parts[0].text).toBe('First answer');
864
+ const turn3 = history[2];
865
+ if (!turn3?.parts?.[0] || !('text' in turn3.parts[0])) {
866
+ throw new Error('Test setup error: Third turn is not a valid text part.');
867
+ }
868
+ expect(turn3.parts[0].text).toBe('Second question');
869
+ const turn4 = history[3];
870
+ if (!turn4?.parts?.[0] || !('text' in turn4.parts[0])) {
871
+ throw new Error('Test setup error: Fourth turn is not a valid text part.');
872
+ }
873
+ expect(turn4.parts[0].text).toBe('Second answer');
874
+ });
875
+ describe('concurrency control', () => {
876
+ it('should queue a subsequent sendMessage call until the first one completes', async () => {
877
+ // 1. Create promises to manually control when the API calls resolve
878
+ let firstCallResolver;
879
+ const firstCallPromise = new Promise((resolve) => {
880
+ firstCallResolver = resolve;
881
+ });
882
+ let secondCallResolver;
883
+ const secondCallPromise = new Promise((resolve) => {
884
+ secondCallResolver = resolve;
885
+ });
886
+ // A standard response body for the mock
887
+ const mockResponse = {
888
+ candidates: [
889
+ {
890
+ content: { parts: [{ text: 'response' }], role: 'model' },
891
+ },
892
+ ],
893
+ };
894
+ // 2. Mock the API to return our controllable promises in order
895
+ vi.mocked(mockModelsModule.generateContent)
896
+ .mockReturnValueOnce(firstCallPromise)
897
+ .mockReturnValueOnce(secondCallPromise);
898
+ // 3. Start the first message call. Do not await it yet.
899
+ const firstMessagePromise = chat.sendMessage({ message: 'first' }, 'prompt-1');
900
+ // Give the event loop a chance to run the async call up to the `await`
901
+ await new Promise(process.nextTick);
902
+ // 4. While the first call is "in-flight", start the second message call.
903
+ const secondMessagePromise = chat.sendMessage({ message: 'second' }, 'prompt-2');
904
+ // 5. CRUCIAL CHECK: At this point, only the first API call should have been made.
905
+ // The second call should be waiting on `sendPromise`.
906
+ expect(mockModelsModule.generateContent).toHaveBeenCalledTimes(1);
907
+ expect(mockModelsModule.generateContent).toHaveBeenCalledWith(expect.objectContaining({
908
+ contents: expect.arrayContaining([
909
+ expect.objectContaining({ parts: [{ text: 'first' }] }),
910
+ ]),
911
+ }), 'prompt-1');
912
+ // 6. Unblock the first API call and wait for the first message to fully complete.
913
+ firstCallResolver(mockResponse);
914
+ await firstMessagePromise;
915
+ // Give the event loop a chance to unblock and run the second call.
916
+ await new Promise(process.nextTick);
917
+ // 7. CRUCIAL CHECK: Now, the second API call should have been made.
918
+ expect(mockModelsModule.generateContent).toHaveBeenCalledTimes(2);
919
+ expect(mockModelsModule.generateContent).toHaveBeenCalledWith(expect.objectContaining({
920
+ contents: expect.arrayContaining([
921
+ expect.objectContaining({ parts: [{ text: 'second' }] }),
922
+ ]),
923
+ }), 'prompt-2');
924
+ // 8. Clean up by resolving the second call.
925
+ secondCallResolver(mockResponse);
926
+ await secondMessagePromise;
927
+ });
928
+ });
929
+ it('should retry if the model returns a completely empty stream (no chunks)', async () => {
930
+ // 1. Mock the API to return an empty stream first, then a valid one.
931
+ vi.mocked(mockModelsModule.generateContentStream)
932
+ .mockImplementationOnce(
933
+ // First call resolves to an async generator that yields nothing.
934
+ async () => (async function* () { })())
935
+ .mockImplementationOnce(
936
+ // Second call returns a valid stream.
937
+ async () => (async function* () {
938
+ yield {
939
+ candidates: [
940
+ {
941
+ content: {
942
+ parts: [{ text: 'Successful response after empty' }],
943
+ },
944
+ },
945
+ ],
946
+ };
947
+ })());
948
+ // 2. Call the method and consume the stream.
949
+ const stream = await chat.sendMessageStream({ message: 'test empty stream' }, 'prompt-id-empty-stream');
950
+ const chunks = [];
951
+ for await (const chunk of stream) {
952
+ chunks.push(chunk);
953
+ }
954
+ // 3. Assert the results.
955
+ expect(mockModelsModule.generateContentStream).toHaveBeenCalledTimes(2);
956
+ expect(chunks.some((c) => c.candidates?.[0]?.content?.parts?.[0]?.text ===
957
+ 'Successful response after empty')).toBe(true);
958
+ const history = chat.getHistory();
959
+ expect(history.length).toBe(2);
960
+ // Explicitly verify the structure of each part to satisfy TypeScript
961
+ const turn1 = history[0];
962
+ if (!turn1?.parts?.[0] || !('text' in turn1.parts[0])) {
963
+ throw new Error('Test setup error: First turn is not a valid text part.');
964
+ }
965
+ expect(turn1.parts[0].text).toBe('test empty stream');
966
+ const turn2 = history[1];
967
+ if (!turn2?.parts?.[0] || !('text' in turn2.parts[0])) {
968
+ throw new Error('Test setup error: Second turn is not a valid text part.');
969
+ }
970
+ expect(turn2.parts[0].text).toBe('Successful response after empty');
971
+ });
972
+ it('should queue a subsequent sendMessageStream call until the first stream is fully consumed', async () => {
973
+ // 1. Create a promise to manually control the stream's lifecycle
974
+ let continueFirstStream;
975
+ const firstStreamContinuePromise = new Promise((resolve) => {
976
+ continueFirstStream = resolve;
977
+ });
978
+ // 2. Mock the API to return controllable async generators
979
+ const firstStreamGenerator = (async function* () {
980
+ yield {
981
+ candidates: [
982
+ { content: { parts: [{ text: 'first response part 1' }] } },
983
+ ],
984
+ };
985
+ await firstStreamContinuePromise; // Pause the stream
986
+ yield {
987
+ candidates: [{ content: { parts: [{ text: ' part 2' }] } }],
988
+ };
989
+ })();
990
+ const secondStreamGenerator = (async function* () {
991
+ yield {
992
+ candidates: [{ content: { parts: [{ text: 'second response' }] } }],
993
+ };
994
+ })();
995
+ vi.mocked(mockModelsModule.generateContentStream)
996
+ .mockResolvedValueOnce(firstStreamGenerator)
997
+ .mockResolvedValueOnce(secondStreamGenerator);
998
+ // 3. Start the first stream and consume only the first chunk to pause it
999
+ const firstStream = await chat.sendMessageStream({ message: 'first' }, 'prompt-1');
1000
+ const firstStreamIterator = firstStream[Symbol.asyncIterator]();
1001
+ await firstStreamIterator.next();
1002
+ // 4. While the first stream is paused, start the second call. It will block.
1003
+ const secondStreamPromise = chat.sendMessageStream({ message: 'second' }, 'prompt-2');
1004
+ // 5. Assert that only one API call has been made so far.
1005
+ expect(mockModelsModule.generateContentStream).toHaveBeenCalledTimes(1);
1006
+ // 6. Unblock and fully consume the first stream to completion.
1007
+ continueFirstStream();
1008
+ await firstStreamIterator.next(); // Consume the rest of the stream
1009
+ await firstStreamIterator.next(); // Finish the iterator
1010
+ // 7. Now that the first stream is done, await the second promise to get its generator.
1011
+ const secondStream = await secondStreamPromise;
1012
+ // 8. Start consuming the second stream, which triggers its internal API call.
1013
+ const secondStreamIterator = secondStream[Symbol.asyncIterator]();
1014
+ await secondStreamIterator.next();
1015
+ // 9. The second API call should now have been made.
1016
+ expect(mockModelsModule.generateContentStream).toHaveBeenCalledTimes(2);
1017
+ // 10. FIX: Fully consume the second stream to ensure recordHistory is called.
1018
+ await secondStreamIterator.next(); // This finishes the iterator.
1019
+ // 11. Final check on history.
1020
+ const history = chat.getHistory();
1021
+ expect(history.length).toBe(4);
1022
+ const turn4 = history[3];
1023
+ if (!turn4?.parts?.[0] || !('text' in turn4.parts[0])) {
1024
+ throw new Error('Test setup error: Fourth turn is not a valid text part.');
1025
+ }
1026
+ expect(turn4.parts[0].text).toBe('second response');
1027
+ });
423
1028
  });
424
1029
  //# sourceMappingURL=geminiChat.test.js.map