@office-ai/aioncli-core 0.1.18-beta.1

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 (567) hide show
  1. package/dist/.last_build +0 -0
  2. package/dist/index.d.ts +7 -0
  3. package/dist/index.js +8 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/src/__mocks__/fs/promises.d.ts +11 -0
  6. package/dist/src/__mocks__/fs/promises.js +17 -0
  7. package/dist/src/__mocks__/fs/promises.js.map +1 -0
  8. package/dist/src/code_assist/codeAssist.d.ts +9 -0
  9. package/dist/src/code_assist/codeAssist.js +19 -0
  10. package/dist/src/code_assist/codeAssist.js.map +1 -0
  11. package/dist/src/code_assist/converter.d.ts +70 -0
  12. package/dist/src/code_assist/converter.js +126 -0
  13. package/dist/src/code_assist/converter.js.map +1 -0
  14. package/dist/src/code_assist/converter.test.d.ts +6 -0
  15. package/dist/src/code_assist/converter.test.js +279 -0
  16. package/dist/src/code_assist/converter.test.js.map +1 -0
  17. package/dist/src/code_assist/oauth2.d.ts +20 -0
  18. package/dist/src/code_assist/oauth2.js +337 -0
  19. package/dist/src/code_assist/oauth2.js.map +1 -0
  20. package/dist/src/code_assist/oauth2.test.d.ts +6 -0
  21. package/dist/src/code_assist/oauth2.test.js +334 -0
  22. package/dist/src/code_assist/oauth2.test.js.map +1 -0
  23. package/dist/src/code_assist/server.d.ts +37 -0
  24. package/dist/src/code_assist/server.js +125 -0
  25. package/dist/src/code_assist/server.js.map +1 -0
  26. package/dist/src/code_assist/server.test.d.ts +6 -0
  27. package/dist/src/code_assist/server.test.js +134 -0
  28. package/dist/src/code_assist/server.test.js.map +1 -0
  29. package/dist/src/code_assist/setup.d.ts +20 -0
  30. package/dist/src/code_assist/setup.js +70 -0
  31. package/dist/src/code_assist/setup.js.map +1 -0
  32. package/dist/src/code_assist/setup.test.d.ts +6 -0
  33. package/dist/src/code_assist/setup.test.js +65 -0
  34. package/dist/src/code_assist/setup.test.js.map +1 -0
  35. package/dist/src/code_assist/types.d.ts +148 -0
  36. package/dist/src/code_assist/types.js +46 -0
  37. package/dist/src/code_assist/types.js.map +1 -0
  38. package/dist/src/config/config.d.ts +272 -0
  39. package/dist/src/config/config.js +554 -0
  40. package/dist/src/config/config.js.map +1 -0
  41. package/dist/src/config/config.test.d.ts +6 -0
  42. package/dist/src/config/config.test.js +365 -0
  43. package/dist/src/config/config.test.js.map +1 -0
  44. package/dist/src/config/flashFallback.test.d.ts +6 -0
  45. package/dist/src/config/flashFallback.test.js +87 -0
  46. package/dist/src/config/flashFallback.test.js.map +1 -0
  47. package/dist/src/config/models.d.ts +9 -0
  48. package/dist/src/config/models.js +10 -0
  49. package/dist/src/config/models.js.map +1 -0
  50. package/dist/src/core/client.d.ts +61 -0
  51. package/dist/src/core/client.js +485 -0
  52. package/dist/src/core/client.js.map +1 -0
  53. package/dist/src/core/client.test.d.ts +6 -0
  54. package/dist/src/core/client.test.js +1008 -0
  55. package/dist/src/core/client.test.js.map +1 -0
  56. package/dist/src/core/contentGenerator.d.ts +45 -0
  57. package/dist/src/core/contentGenerator.js +81 -0
  58. package/dist/src/core/contentGenerator.js.map +1 -0
  59. package/dist/src/core/contentGenerator.test.d.ts +6 -0
  60. package/dist/src/core/contentGenerator.test.js +100 -0
  61. package/dist/src/core/contentGenerator.test.js.map +1 -0
  62. package/dist/src/core/coreToolScheduler.d.ts +117 -0
  63. package/dist/src/core/coreToolScheduler.js +530 -0
  64. package/dist/src/core/coreToolScheduler.js.map +1 -0
  65. package/dist/src/core/coreToolScheduler.test.d.ts +6 -0
  66. package/dist/src/core/coreToolScheduler.test.js +625 -0
  67. package/dist/src/core/coreToolScheduler.test.js.map +1 -0
  68. package/dist/src/core/geminiChat.d.ts +118 -0
  69. package/dist/src/core/geminiChat.js +509 -0
  70. package/dist/src/core/geminiChat.js.map +1 -0
  71. package/dist/src/core/geminiChat.test.d.ts +6 -0
  72. package/dist/src/core/geminiChat.test.js +424 -0
  73. package/dist/src/core/geminiChat.test.js.map +1 -0
  74. package/dist/src/core/geminiRequest.d.ts +13 -0
  75. package/dist/src/core/geminiRequest.js +10 -0
  76. package/dist/src/core/geminiRequest.js.map +1 -0
  77. package/dist/src/core/logger.d.ts +37 -0
  78. package/dist/src/core/logger.js +273 -0
  79. package/dist/src/core/logger.js.map +1 -0
  80. package/dist/src/core/logger.test.d.ts +6 -0
  81. package/dist/src/core/logger.test.js +467 -0
  82. package/dist/src/core/logger.test.js.map +1 -0
  83. package/dist/src/core/loggingContentGenerator.d.ts +24 -0
  84. package/dist/src/core/loggingContentGenerator.js +89 -0
  85. package/dist/src/core/loggingContentGenerator.js.map +1 -0
  86. package/dist/src/core/modelCheck.d.ts +14 -0
  87. package/dist/src/core/modelCheck.js +62 -0
  88. package/dist/src/core/modelCheck.js.map +1 -0
  89. package/dist/src/core/nonInteractiveToolExecutor.d.ts +12 -0
  90. package/dist/src/core/nonInteractiveToolExecutor.js +124 -0
  91. package/dist/src/core/nonInteractiveToolExecutor.js.map +1 -0
  92. package/dist/src/core/nonInteractiveToolExecutor.test.d.ts +6 -0
  93. package/dist/src/core/nonInteractiveToolExecutor.test.js +165 -0
  94. package/dist/src/core/nonInteractiveToolExecutor.test.js.map +1 -0
  95. package/dist/src/core/openaiContentGenerator.d.ts +77 -0
  96. package/dist/src/core/openaiContentGenerator.js +1395 -0
  97. package/dist/src/core/openaiContentGenerator.js.map +1 -0
  98. package/dist/src/core/openaiContentGenerator.test.d.ts +6 -0
  99. package/dist/src/core/openaiContentGenerator.test.js +1904 -0
  100. package/dist/src/core/openaiContentGenerator.test.js.map +1 -0
  101. package/dist/src/core/prompts.d.ts +12 -0
  102. package/dist/src/core/prompts.js +359 -0
  103. package/dist/src/core/prompts.js.map +1 -0
  104. package/dist/src/core/prompts.test.d.ts +6 -0
  105. package/dist/src/core/prompts.test.js +214 -0
  106. package/dist/src/core/prompts.test.js.map +1 -0
  107. package/dist/src/core/subagent.d.ts +230 -0
  108. package/dist/src/core/subagent.js +447 -0
  109. package/dist/src/core/subagent.js.map +1 -0
  110. package/dist/src/core/subagent.test.d.ts +6 -0
  111. package/dist/src/core/subagent.test.js +515 -0
  112. package/dist/src/core/subagent.test.js.map +1 -0
  113. package/dist/src/core/tokenLimits.d.ts +10 -0
  114. package/dist/src/core/tokenLimits.js +28 -0
  115. package/dist/src/core/tokenLimits.js.map +1 -0
  116. package/dist/src/core/turn.d.ts +114 -0
  117. package/dist/src/core/turn.js +143 -0
  118. package/dist/src/core/turn.js.map +1 -0
  119. package/dist/src/core/turn.test.d.ts +6 -0
  120. package/dist/src/core/turn.test.js +369 -0
  121. package/dist/src/core/turn.test.js.map +1 -0
  122. package/dist/src/ide/detect-ide.d.ts +10 -0
  123. package/dist/src/ide/detect-ide.js +27 -0
  124. package/dist/src/ide/detect-ide.js.map +1 -0
  125. package/dist/src/ide/ide-client.d.ts +56 -0
  126. package/dist/src/ide/ide-client.js +268 -0
  127. package/dist/src/ide/ide-client.js.map +1 -0
  128. package/dist/src/ide/ide-installer.d.ts +14 -0
  129. package/dist/src/ide/ide-installer.js +109 -0
  130. package/dist/src/ide/ide-installer.js.map +1 -0
  131. package/dist/src/ide/ide-installer.test.d.ts +6 -0
  132. package/dist/src/ide/ide-installer.test.js +55 -0
  133. package/dist/src/ide/ide-installer.test.js.map +1 -0
  134. package/dist/src/ide/ideContext.d.ts +374 -0
  135. package/dist/src/ide/ideContext.js +147 -0
  136. package/dist/src/ide/ideContext.js.map +1 -0
  137. package/dist/src/ide/ideContext.test.d.ts +6 -0
  138. package/dist/src/ide/ideContext.test.js +265 -0
  139. package/dist/src/ide/ideContext.test.js.map +1 -0
  140. package/dist/src/index.d.ts +68 -0
  141. package/dist/src/index.js +78 -0
  142. package/dist/src/index.js.map +1 -0
  143. package/dist/src/index.test.d.ts +6 -0
  144. package/dist/src/index.test.js +12 -0
  145. package/dist/src/index.test.js.map +1 -0
  146. package/dist/src/mcp/google-auth-provider.d.ts +23 -0
  147. package/dist/src/mcp/google-auth-provider.js +63 -0
  148. package/dist/src/mcp/google-auth-provider.js.map +1 -0
  149. package/dist/src/mcp/google-auth-provider.test.d.ts +6 -0
  150. package/dist/src/mcp/google-auth-provider.test.js +54 -0
  151. package/dist/src/mcp/google-auth-provider.test.js.map +1 -0
  152. package/dist/src/mcp/oauth-provider.d.ts +147 -0
  153. package/dist/src/mcp/oauth-provider.js +484 -0
  154. package/dist/src/mcp/oauth-provider.js.map +1 -0
  155. package/dist/src/mcp/oauth-provider.test.d.ts +6 -0
  156. package/dist/src/mcp/oauth-provider.test.js +602 -0
  157. package/dist/src/mcp/oauth-provider.test.js.map +1 -0
  158. package/dist/src/mcp/oauth-token-storage.d.ts +83 -0
  159. package/dist/src/mcp/oauth-token-storage.js +151 -0
  160. package/dist/src/mcp/oauth-token-storage.js.map +1 -0
  161. package/dist/src/mcp/oauth-token-storage.test.d.ts +6 -0
  162. package/dist/src/mcp/oauth-token-storage.test.js +205 -0
  163. package/dist/src/mcp/oauth-token-storage.test.js.map +1 -0
  164. package/dist/src/mcp/oauth-utils.d.ts +109 -0
  165. package/dist/src/mcp/oauth-utils.js +183 -0
  166. package/dist/src/mcp/oauth-utils.js.map +1 -0
  167. package/dist/src/mcp/oauth-utils.test.d.ts +6 -0
  168. package/dist/src/mcp/oauth-utils.test.js +144 -0
  169. package/dist/src/mcp/oauth-utils.test.js.map +1 -0
  170. package/dist/src/prompts/mcp-prompts.d.ts +8 -0
  171. package/dist/src/prompts/mcp-prompts.js +13 -0
  172. package/dist/src/prompts/mcp-prompts.js.map +1 -0
  173. package/dist/src/prompts/prompt-registry.d.ts +34 -0
  174. package/dist/src/prompts/prompt-registry.js +63 -0
  175. package/dist/src/prompts/prompt-registry.js.map +1 -0
  176. package/dist/src/services/fileDiscoveryService.d.ts +35 -0
  177. package/dist/src/services/fileDiscoveryService.js +91 -0
  178. package/dist/src/services/fileDiscoveryService.js.map +1 -0
  179. package/dist/src/services/fileDiscoveryService.test.d.ts +6 -0
  180. package/dist/src/services/fileDiscoveryService.test.js +143 -0
  181. package/dist/src/services/fileDiscoveryService.test.js.map +1 -0
  182. package/dist/src/services/gitService.d.ts +21 -0
  183. package/dist/src/services/gitService.js +101 -0
  184. package/dist/src/services/gitService.js.map +1 -0
  185. package/dist/src/services/gitService.test.d.ts +6 -0
  186. package/dist/src/services/gitService.test.js +209 -0
  187. package/dist/src/services/gitService.test.js.map +1 -0
  188. package/dist/src/services/loopDetectionService.d.ts +97 -0
  189. package/dist/src/services/loopDetectionService.js +340 -0
  190. package/dist/src/services/loopDetectionService.js.map +1 -0
  191. package/dist/src/services/loopDetectionService.test.d.ts +6 -0
  192. package/dist/src/services/loopDetectionService.test.js +484 -0
  193. package/dist/src/services/loopDetectionService.test.js.map +1 -0
  194. package/dist/src/services/shellExecutionService.d.ts +70 -0
  195. package/dist/src/services/shellExecutionService.js +175 -0
  196. package/dist/src/services/shellExecutionService.js.map +1 -0
  197. package/dist/src/services/shellExecutionService.test.d.ts +6 -0
  198. package/dist/src/services/shellExecutionService.test.js +272 -0
  199. package/dist/src/services/shellExecutionService.test.js.map +1 -0
  200. package/dist/src/telemetry/clearcut-logger/clearcut-logger.d.ts +65 -0
  201. package/dist/src/telemetry/clearcut-logger/clearcut-logger.js +652 -0
  202. package/dist/src/telemetry/clearcut-logger/clearcut-logger.js.map +1 -0
  203. package/dist/src/telemetry/clearcut-logger/clearcut-logger.test.d.ts +6 -0
  204. package/dist/src/telemetry/clearcut-logger/clearcut-logger.test.js +186 -0
  205. package/dist/src/telemetry/clearcut-logger/clearcut-logger.test.js.map +1 -0
  206. package/dist/src/telemetry/clearcut-logger/event-metadata-key.d.ts +59 -0
  207. package/dist/src/telemetry/clearcut-logger/event-metadata-key.js +159 -0
  208. package/dist/src/telemetry/clearcut-logger/event-metadata-key.js.map +1 -0
  209. package/dist/src/telemetry/constants.d.ts +23 -0
  210. package/dist/src/telemetry/constants.js +24 -0
  211. package/dist/src/telemetry/constants.js.map +1 -0
  212. package/dist/src/telemetry/file-exporters.d.ts +28 -0
  213. package/dist/src/telemetry/file-exporters.js +62 -0
  214. package/dist/src/telemetry/file-exporters.js.map +1 -0
  215. package/dist/src/telemetry/index.d.ts +18 -0
  216. package/dist/src/telemetry/index.js +20 -0
  217. package/dist/src/telemetry/index.js.map +1 -0
  218. package/dist/src/telemetry/integration.test.circular.d.ts +6 -0
  219. package/dist/src/telemetry/integration.test.circular.js +53 -0
  220. package/dist/src/telemetry/integration.test.circular.js.map +1 -0
  221. package/dist/src/telemetry/loggers.d.ts +18 -0
  222. package/dist/src/telemetry/loggers.js +268 -0
  223. package/dist/src/telemetry/loggers.js.map +1 -0
  224. package/dist/src/telemetry/loggers.test.circular.d.ts +6 -0
  225. package/dist/src/telemetry/loggers.test.circular.js +107 -0
  226. package/dist/src/telemetry/loggers.test.circular.js.map +1 -0
  227. package/dist/src/telemetry/loggers.test.d.ts +6 -0
  228. package/dist/src/telemetry/loggers.test.js +568 -0
  229. package/dist/src/telemetry/loggers.test.js.map +1 -0
  230. package/dist/src/telemetry/metrics.d.ts +20 -0
  231. package/dist/src/telemetry/metrics.js +150 -0
  232. package/dist/src/telemetry/metrics.js.map +1 -0
  233. package/dist/src/telemetry/metrics.test.d.ts +6 -0
  234. package/dist/src/telemetry/metrics.test.js +212 -0
  235. package/dist/src/telemetry/metrics.test.js.map +1 -0
  236. package/dist/src/telemetry/sdk.d.ts +9 -0
  237. package/dist/src/telemetry/sdk.js +127 -0
  238. package/dist/src/telemetry/sdk.js.map +1 -0
  239. package/dist/src/telemetry/telemetry.test.d.ts +6 -0
  240. package/dist/src/telemetry/telemetry.test.js +50 -0
  241. package/dist/src/telemetry/telemetry.test.js.map +1 -0
  242. package/dist/src/telemetry/tool-call-decision.d.ts +13 -0
  243. package/dist/src/telemetry/tool-call-decision.js +29 -0
  244. package/dist/src/telemetry/tool-call-decision.js.map +1 -0
  245. package/dist/src/telemetry/types.d.ts +145 -0
  246. package/dist/src/telemetry/types.js +267 -0
  247. package/dist/src/telemetry/types.js.map +1 -0
  248. package/dist/src/telemetry/uiTelemetry.d.ts +71 -0
  249. package/dist/src/telemetry/uiTelemetry.js +140 -0
  250. package/dist/src/telemetry/uiTelemetry.js.map +1 -0
  251. package/dist/src/telemetry/uiTelemetry.test.d.ts +6 -0
  252. package/dist/src/telemetry/uiTelemetry.test.js +518 -0
  253. package/dist/src/telemetry/uiTelemetry.test.js.map +1 -0
  254. package/dist/src/test-utils/mockWorkspaceContext.d.ts +13 -0
  255. package/dist/src/test-utils/mockWorkspaceContext.js +24 -0
  256. package/dist/src/test-utils/mockWorkspaceContext.js.map +1 -0
  257. package/dist/src/test-utils/tools.d.ts +23 -0
  258. package/dist/src/test-utils/tools.js +41 -0
  259. package/dist/src/test-utils/tools.js.map +1 -0
  260. package/dist/src/tools/diffOptions.d.ts +9 -0
  261. package/dist/src/tools/diffOptions.js +38 -0
  262. package/dist/src/tools/diffOptions.js.map +1 -0
  263. package/dist/src/tools/diffOptions.test.d.ts +6 -0
  264. package/dist/src/tools/diffOptions.test.js +119 -0
  265. package/dist/src/tools/diffOptions.test.js.map +1 -0
  266. package/dist/src/tools/edit.d.ts +55 -0
  267. package/dist/src/tools/edit.js +398 -0
  268. package/dist/src/tools/edit.js.map +1 -0
  269. package/dist/src/tools/edit.test.d.ts +6 -0
  270. package/dist/src/tools/edit.test.js +681 -0
  271. package/dist/src/tools/edit.test.js.map +1 -0
  272. package/dist/src/tools/glob.d.ts +51 -0
  273. package/dist/src/tools/glob.js +226 -0
  274. package/dist/src/tools/glob.js.map +1 -0
  275. package/dist/src/tools/glob.test.d.ts +6 -0
  276. package/dist/src/tools/glob.test.js +330 -0
  277. package/dist/src/tools/glob.test.js.map +1 -0
  278. package/dist/src/tools/grep.d.ts +46 -0
  279. package/dist/src/tools/grep.js +503 -0
  280. package/dist/src/tools/grep.js.map +1 -0
  281. package/dist/src/tools/grep.test.d.ts +6 -0
  282. package/dist/src/tools/grep.test.js +272 -0
  283. package/dist/src/tools/grep.test.js.map +1 -0
  284. package/dist/src/tools/ls.d.ts +86 -0
  285. package/dist/src/tools/ls.js +224 -0
  286. package/dist/src/tools/ls.js.map +1 -0
  287. package/dist/src/tools/ls.test.d.ts +6 -0
  288. package/dist/src/tools/ls.test.js +356 -0
  289. package/dist/src/tools/ls.test.js.map +1 -0
  290. package/dist/src/tools/mcp-client.d.ts +149 -0
  291. package/dist/src/tools/mcp-client.js +844 -0
  292. package/dist/src/tools/mcp-client.js.map +1 -0
  293. package/dist/src/tools/mcp-client.test.d.ts +6 -0
  294. package/dist/src/tools/mcp-client.test.js +643 -0
  295. package/dist/src/tools/mcp-client.test.js.map +1 -0
  296. package/dist/src/tools/mcp-tool.d.ts +29 -0
  297. package/dist/src/tools/mcp-tool.js +202 -0
  298. package/dist/src/tools/mcp-tool.js.map +1 -0
  299. package/dist/src/tools/mcp-tool.test.d.ts +6 -0
  300. package/dist/src/tools/mcp-tool.test.js +501 -0
  301. package/dist/src/tools/mcp-tool.test.js.map +1 -0
  302. package/dist/src/tools/memoryTool.d.ts +43 -0
  303. package/dist/src/tools/memoryTool.js +290 -0
  304. package/dist/src/tools/memoryTool.js.map +1 -0
  305. package/dist/src/tools/memoryTool.test.d.ts +6 -0
  306. package/dist/src/tools/memoryTool.test.js +266 -0
  307. package/dist/src/tools/memoryTool.test.js.map +1 -0
  308. package/dist/src/tools/modifiable-tool.d.ts +32 -0
  309. package/dist/src/tools/modifiable-tool.js +88 -0
  310. package/dist/src/tools/modifiable-tool.js.map +1 -0
  311. package/dist/src/tools/modifiable-tool.test.d.ts +6 -0
  312. package/dist/src/tools/modifiable-tool.test.js +193 -0
  313. package/dist/src/tools/modifiable-tool.test.js.map +1 -0
  314. package/dist/src/tools/read-file.d.ts +34 -0
  315. package/dist/src/tools/read-file.js +152 -0
  316. package/dist/src/tools/read-file.js.map +1 -0
  317. package/dist/src/tools/read-file.test.d.ts +6 -0
  318. package/dist/src/tools/read-file.test.js +300 -0
  319. package/dist/src/tools/read-file.test.js.map +1 -0
  320. package/dist/src/tools/read-many-files.d.ts +61 -0
  321. package/dist/src/tools/read-many-files.js +421 -0
  322. package/dist/src/tools/read-many-files.js.map +1 -0
  323. package/dist/src/tools/read-many-files.test.d.ts +6 -0
  324. package/dist/src/tools/read-many-files.test.js +455 -0
  325. package/dist/src/tools/read-many-files.test.js.map +1 -0
  326. package/dist/src/tools/shell.d.ts +23 -0
  327. package/dist/src/tools/shell.js +313 -0
  328. package/dist/src/tools/shell.js.map +1 -0
  329. package/dist/src/tools/shell.test.d.ts +6 -0
  330. package/dist/src/tools/shell.test.js +321 -0
  331. package/dist/src/tools/shell.test.js.map +1 -0
  332. package/dist/src/tools/tool-error.d.ts +26 -0
  333. package/dist/src/tools/tool-error.js +31 -0
  334. package/dist/src/tools/tool-error.js.map +1 -0
  335. package/dist/src/tools/tool-registry.d.ts +85 -0
  336. package/dist/src/tools/tool-registry.js +390 -0
  337. package/dist/src/tools/tool-registry.js.map +1 -0
  338. package/dist/src/tools/tool-registry.test.d.ts +6 -0
  339. package/dist/src/tools/tool-registry.test.js +417 -0
  340. package/dist/src/tools/tool-registry.test.js.map +1 -0
  341. package/dist/src/tools/tools.d.ts +328 -0
  342. package/dist/src/tools/tools.js +281 -0
  343. package/dist/src/tools/tools.js.map +1 -0
  344. package/dist/src/tools/tools.test.d.ts +6 -0
  345. package/dist/src/tools/tools.test.js +117 -0
  346. package/dist/src/tools/tools.test.js.map +1 -0
  347. package/dist/src/tools/web-fetch.d.ts +29 -0
  348. package/dist/src/tools/web-fetch.js +246 -0
  349. package/dist/src/tools/web-fetch.js.map +1 -0
  350. package/dist/src/tools/web-fetch.test.d.ts +6 -0
  351. package/dist/src/tools/web-fetch.test.js +71 -0
  352. package/dist/src/tools/web-fetch.test.js.map +1 -0
  353. package/dist/src/tools/web-search.d.ts +49 -0
  354. package/dist/src/tools/web-search.js +120 -0
  355. package/dist/src/tools/web-search.js.map +1 -0
  356. package/dist/src/tools/write-file.d.ts +46 -0
  357. package/dist/src/tools/write-file.js +321 -0
  358. package/dist/src/tools/write-file.js.map +1 -0
  359. package/dist/src/tools/write-file.test.d.ts +6 -0
  360. package/dist/src/tools/write-file.test.js +572 -0
  361. package/dist/src/tools/write-file.test.js.map +1 -0
  362. package/dist/src/utils/LruCache.d.ts +13 -0
  363. package/dist/src/utils/LruCache.js +38 -0
  364. package/dist/src/utils/LruCache.js.map +1 -0
  365. package/dist/src/utils/bfsFileSearch.d.ts +24 -0
  366. package/dist/src/utils/bfsFileSearch.js +89 -0
  367. package/dist/src/utils/bfsFileSearch.js.map +1 -0
  368. package/dist/src/utils/bfsFileSearch.test.d.ts +6 -0
  369. package/dist/src/utils/bfsFileSearch.test.js +163 -0
  370. package/dist/src/utils/bfsFileSearch.test.js.map +1 -0
  371. package/dist/src/utils/browser.d.ts +13 -0
  372. package/dist/src/utils/browser.js +49 -0
  373. package/dist/src/utils/browser.js.map +1 -0
  374. package/dist/src/utils/editCorrector.d.ts +53 -0
  375. package/dist/src/utils/editCorrector.js +546 -0
  376. package/dist/src/utils/editCorrector.js.map +1 -0
  377. package/dist/src/utils/editCorrector.test.d.ts +6 -0
  378. package/dist/src/utils/editCorrector.test.js +564 -0
  379. package/dist/src/utils/editCorrector.test.js.map +1 -0
  380. package/dist/src/utils/editor.d.ts +28 -0
  381. package/dist/src/utils/editor.js +186 -0
  382. package/dist/src/utils/editor.js.map +1 -0
  383. package/dist/src/utils/editor.test.d.ts +6 -0
  384. package/dist/src/utils/editor.test.js +445 -0
  385. package/dist/src/utils/editor.test.js.map +1 -0
  386. package/dist/src/utils/environmentContext.d.ts +21 -0
  387. package/dist/src/utils/environmentContext.js +90 -0
  388. package/dist/src/utils/environmentContext.js.map +1 -0
  389. package/dist/src/utils/environmentContext.test.d.ts +6 -0
  390. package/dist/src/utils/environmentContext.test.js +139 -0
  391. package/dist/src/utils/environmentContext.test.js.map +1 -0
  392. package/dist/src/utils/errorReporting.d.ts +14 -0
  393. package/dist/src/utils/errorReporting.js +88 -0
  394. package/dist/src/utils/errorReporting.js.map +1 -0
  395. package/dist/src/utils/errorReporting.test.d.ts +6 -0
  396. package/dist/src/utils/errorReporting.test.js +130 -0
  397. package/dist/src/utils/errorReporting.test.js.map +1 -0
  398. package/dist/src/utils/errors.d.ts +14 -0
  399. package/dist/src/utils/errors.js +54 -0
  400. package/dist/src/utils/errors.js.map +1 -0
  401. package/dist/src/utils/fetch.d.ts +11 -0
  402. package/dist/src/utils/fetch.js +51 -0
  403. package/dist/src/utils/fetch.js.map +1 -0
  404. package/dist/src/utils/fileUtils.d.ts +56 -0
  405. package/dist/src/utils/fileUtils.js +314 -0
  406. package/dist/src/utils/fileUtils.js.map +1 -0
  407. package/dist/src/utils/fileUtils.test.d.ts +6 -0
  408. package/dist/src/utils/fileUtils.test.js +363 -0
  409. package/dist/src/utils/fileUtils.test.js.map +1 -0
  410. package/dist/src/utils/filesearch/crawlCache.d.ts +25 -0
  411. package/dist/src/utils/filesearch/crawlCache.js +57 -0
  412. package/dist/src/utils/filesearch/crawlCache.js.map +1 -0
  413. package/dist/src/utils/filesearch/crawlCache.test.d.ts +6 -0
  414. package/dist/src/utils/filesearch/crawlCache.test.js +103 -0
  415. package/dist/src/utils/filesearch/crawlCache.test.js.map +1 -0
  416. package/dist/src/utils/filesearch/fileSearch.d.ts +81 -0
  417. package/dist/src/utils/filesearch/fileSearch.js +241 -0
  418. package/dist/src/utils/filesearch/fileSearch.js.map +1 -0
  419. package/dist/src/utils/filesearch/fileSearch.test.d.ts +6 -0
  420. package/dist/src/utils/filesearch/fileSearch.test.js +654 -0
  421. package/dist/src/utils/filesearch/fileSearch.test.js.map +1 -0
  422. package/dist/src/utils/filesearch/ignore.d.ts +35 -0
  423. package/dist/src/utils/filesearch/ignore.js +81 -0
  424. package/dist/src/utils/filesearch/ignore.js.map +1 -0
  425. package/dist/src/utils/filesearch/ignore.test.d.ts +6 -0
  426. package/dist/src/utils/filesearch/ignore.test.js +57 -0
  427. package/dist/src/utils/filesearch/ignore.test.js.map +1 -0
  428. package/dist/src/utils/filesearch/result-cache.d.ts +34 -0
  429. package/dist/src/utils/filesearch/result-cache.js +61 -0
  430. package/dist/src/utils/filesearch/result-cache.js.map +1 -0
  431. package/dist/src/utils/filesearch/result-cache.test.d.ts +6 -0
  432. package/dist/src/utils/filesearch/result-cache.test.js +47 -0
  433. package/dist/src/utils/filesearch/result-cache.test.js.map +1 -0
  434. package/dist/src/utils/flashFallback.integration.test.d.ts +6 -0
  435. package/dist/src/utils/flashFallback.integration.test.js +118 -0
  436. package/dist/src/utils/flashFallback.integration.test.js.map +1 -0
  437. package/dist/src/utils/formatters.d.ts +6 -0
  438. package/dist/src/utils/formatters.js +16 -0
  439. package/dist/src/utils/formatters.js.map +1 -0
  440. package/dist/src/utils/generateContentResponseUtilities.d.ts +14 -0
  441. package/dist/src/utils/generateContentResponseUtilities.js +92 -0
  442. package/dist/src/utils/generateContentResponseUtilities.js.map +1 -0
  443. package/dist/src/utils/generateContentResponseUtilities.test.d.ts +6 -0
  444. package/dist/src/utils/generateContentResponseUtilities.test.js +273 -0
  445. package/dist/src/utils/generateContentResponseUtilities.test.js.map +1 -0
  446. package/dist/src/utils/getFolderStructure.d.ts +31 -0
  447. package/dist/src/utils/getFolderStructure.js +246 -0
  448. package/dist/src/utils/getFolderStructure.js.map +1 -0
  449. package/dist/src/utils/getFolderStructure.test.d.ts +6 -0
  450. package/dist/src/utils/getFolderStructure.test.js +282 -0
  451. package/dist/src/utils/getFolderStructure.test.js.map +1 -0
  452. package/dist/src/utils/gitIgnoreParser.d.ts +20 -0
  453. package/dist/src/utils/gitIgnoreParser.js +61 -0
  454. package/dist/src/utils/gitIgnoreParser.js.map +1 -0
  455. package/dist/src/utils/gitIgnoreParser.test.d.ts +6 -0
  456. package/dist/src/utils/gitIgnoreParser.test.js +154 -0
  457. package/dist/src/utils/gitIgnoreParser.test.js.map +1 -0
  458. package/dist/src/utils/gitUtils.d.ts +17 -0
  459. package/dist/src/utils/gitUtils.js +61 -0
  460. package/dist/src/utils/gitUtils.js.map +1 -0
  461. package/dist/src/utils/memoryDiscovery.d.ts +15 -0
  462. package/dist/src/utils/memoryDiscovery.js +219 -0
  463. package/dist/src/utils/memoryDiscovery.js.map +1 -0
  464. package/dist/src/utils/memoryDiscovery.test.d.ts +6 -0
  465. package/dist/src/utils/memoryDiscovery.test.js +181 -0
  466. package/dist/src/utils/memoryDiscovery.test.js.map +1 -0
  467. package/dist/src/utils/memoryImportProcessor.d.ts +42 -0
  468. package/dist/src/utils/memoryImportProcessor.js +300 -0
  469. package/dist/src/utils/memoryImportProcessor.js.map +1 -0
  470. package/dist/src/utils/memoryImportProcessor.test.d.ts +6 -0
  471. package/dist/src/utils/memoryImportProcessor.test.js +715 -0
  472. package/dist/src/utils/memoryImportProcessor.test.js.map +1 -0
  473. package/dist/src/utils/messageInspectors.d.ts +8 -0
  474. package/dist/src/utils/messageInspectors.js +16 -0
  475. package/dist/src/utils/messageInspectors.js.map +1 -0
  476. package/dist/src/utils/nextSpeakerChecker.d.ts +12 -0
  477. package/dist/src/utils/nextSpeakerChecker.js +92 -0
  478. package/dist/src/utils/nextSpeakerChecker.js.map +1 -0
  479. package/dist/src/utils/nextSpeakerChecker.test.d.ts +6 -0
  480. package/dist/src/utils/nextSpeakerChecker.test.js +168 -0
  481. package/dist/src/utils/nextSpeakerChecker.test.js.map +1 -0
  482. package/dist/src/utils/openaiLogger.d.ts +42 -0
  483. package/dist/src/utils/openaiLogger.js +123 -0
  484. package/dist/src/utils/openaiLogger.js.map +1 -0
  485. package/dist/src/utils/partUtils.d.ts +14 -0
  486. package/dist/src/utils/partUtils.js +65 -0
  487. package/dist/src/utils/partUtils.js.map +1 -0
  488. package/dist/src/utils/partUtils.test.d.ts +6 -0
  489. package/dist/src/utils/partUtils.test.js +130 -0
  490. package/dist/src/utils/partUtils.test.js.map +1 -0
  491. package/dist/src/utils/paths.d.ts +68 -0
  492. package/dist/src/utils/paths.js +170 -0
  493. package/dist/src/utils/paths.js.map +1 -0
  494. package/dist/src/utils/paths.test.d.ts +6 -0
  495. package/dist/src/utils/paths.test.js +153 -0
  496. package/dist/src/utils/paths.test.js.map +1 -0
  497. package/dist/src/utils/quotaErrorDetection.d.ts +22 -0
  498. package/dist/src/utils/quotaErrorDetection.js +65 -0
  499. package/dist/src/utils/quotaErrorDetection.js.map +1 -0
  500. package/dist/src/utils/retry.d.ts +30 -0
  501. package/dist/src/utils/retry.js +276 -0
  502. package/dist/src/utils/retry.js.map +1 -0
  503. package/dist/src/utils/retry.test.d.ts +6 -0
  504. package/dist/src/utils/retry.test.js +322 -0
  505. package/dist/src/utils/retry.test.js.map +1 -0
  506. package/dist/src/utils/safeJsonStringify.d.ts +13 -0
  507. package/dist/src/utils/safeJsonStringify.js +25 -0
  508. package/dist/src/utils/safeJsonStringify.js.map +1 -0
  509. package/dist/src/utils/safeJsonStringify.test.d.ts +6 -0
  510. package/dist/src/utils/safeJsonStringify.test.js +61 -0
  511. package/dist/src/utils/safeJsonStringify.test.js.map +1 -0
  512. package/dist/src/utils/schemaValidator.d.ts +22 -0
  513. package/dist/src/utils/schemaValidator.js +65 -0
  514. package/dist/src/utils/schemaValidator.js.map +1 -0
  515. package/dist/src/utils/secure-browser-launcher.d.ts +23 -0
  516. package/dist/src/utils/secure-browser-launcher.js +164 -0
  517. package/dist/src/utils/secure-browser-launcher.js.map +1 -0
  518. package/dist/src/utils/secure-browser-launcher.test.d.ts +6 -0
  519. package/dist/src/utils/secure-browser-launcher.test.js +149 -0
  520. package/dist/src/utils/secure-browser-launcher.test.js.map +1 -0
  521. package/dist/src/utils/session.d.ts +6 -0
  522. package/dist/src/utils/session.js +8 -0
  523. package/dist/src/utils/session.js.map +1 -0
  524. package/dist/src/utils/shell-utils.d.ts +78 -0
  525. package/dist/src/utils/shell-utils.js +306 -0
  526. package/dist/src/utils/shell-utils.js.map +1 -0
  527. package/dist/src/utils/shell-utils.test.d.ts +6 -0
  528. package/dist/src/utils/shell-utils.test.js +200 -0
  529. package/dist/src/utils/shell-utils.test.js.map +1 -0
  530. package/dist/src/utils/summarizer.d.ts +25 -0
  531. package/dist/src/utils/summarizer.js +51 -0
  532. package/dist/src/utils/summarizer.js.map +1 -0
  533. package/dist/src/utils/summarizer.test.d.ts +6 -0
  534. package/dist/src/utils/summarizer.test.js +131 -0
  535. package/dist/src/utils/summarizer.test.js.map +1 -0
  536. package/dist/src/utils/systemEncoding.d.ts +40 -0
  537. package/dist/src/utils/systemEncoding.js +149 -0
  538. package/dist/src/utils/systemEncoding.js.map +1 -0
  539. package/dist/src/utils/systemEncoding.test.d.ts +6 -0
  540. package/dist/src/utils/systemEncoding.test.js +368 -0
  541. package/dist/src/utils/systemEncoding.test.js.map +1 -0
  542. package/dist/src/utils/testUtils.d.ts +29 -0
  543. package/dist/src/utils/testUtils.js +70 -0
  544. package/dist/src/utils/testUtils.js.map +1 -0
  545. package/dist/src/utils/textUtils.d.ts +13 -0
  546. package/dist/src/utils/textUtils.js +28 -0
  547. package/dist/src/utils/textUtils.js.map +1 -0
  548. package/dist/src/utils/user_account.d.ts +9 -0
  549. package/dist/src/utils/user_account.js +99 -0
  550. package/dist/src/utils/user_account.js.map +1 -0
  551. package/dist/src/utils/user_account.test.d.ts +6 -0
  552. package/dist/src/utils/user_account.test.js +153 -0
  553. package/dist/src/utils/user_account.test.js.map +1 -0
  554. package/dist/src/utils/user_id.d.ts +11 -0
  555. package/dist/src/utils/user_id.js +49 -0
  556. package/dist/src/utils/user_id.js.map +1 -0
  557. package/dist/src/utils/user_id.test.d.ts +6 -0
  558. package/dist/src/utils/user_id.test.js +21 -0
  559. package/dist/src/utils/user_id.test.js.map +1 -0
  560. package/dist/src/utils/workspaceContext.d.ts +51 -0
  561. package/dist/src/utils/workspaceContext.js +139 -0
  562. package/dist/src/utils/workspaceContext.js.map +1 -0
  563. package/dist/src/utils/workspaceContext.test.d.ts +6 -0
  564. package/dist/src/utils/workspaceContext.test.js +209 -0
  565. package/dist/src/utils/workspaceContext.test.js.map +1 -0
  566. package/dist/tsconfig.tsbuildinfo +1 -0
  567. package/package.json +74 -0
@@ -0,0 +1,1008 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
7
+ import { GoogleGenAI, } from '@google/genai';
8
+ import { findIndexAfterFraction, GeminiClient } from './client.js';
9
+ import { AuthType } from './contentGenerator.js';
10
+ import { Config } from '../config/config.js';
11
+ import { GeminiEventType, Turn } from './turn.js';
12
+ import { getCoreSystemPrompt } from './prompts.js';
13
+ import { DEFAULT_GEMINI_FLASH_MODEL } from '../config/models.js';
14
+ import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
15
+ import { setSimulate429 } from '../utils/testUtils.js';
16
+ import { tokenLimit } from './tokenLimits.js';
17
+ import { ideContext } from '../ide/ideContext.js';
18
+ // --- Mocks ---
19
+ const mockChatCreateFn = vi.fn();
20
+ const mockGenerateContentFn = vi.fn();
21
+ const mockEmbedContentFn = vi.fn();
22
+ const mockTurnRunFn = vi.fn();
23
+ vi.mock('@google/genai');
24
+ vi.mock('./turn', () => {
25
+ // Define a mock class that has the same shape as the real Turn
26
+ class MockTurn {
27
+ pendingToolCalls = [];
28
+ // The run method is a property that holds our mock function
29
+ run = mockTurnRunFn;
30
+ constructor() {
31
+ // The constructor can be empty or do some mock setup
32
+ }
33
+ }
34
+ // Export the mock class as 'Turn'
35
+ return {
36
+ Turn: MockTurn,
37
+ GeminiEventType: {
38
+ MaxSessionTurns: 'MaxSessionTurns',
39
+ ChatCompressed: 'ChatCompressed',
40
+ },
41
+ };
42
+ });
43
+ vi.mock('../config/config.js');
44
+ vi.mock('./prompts');
45
+ vi.mock('../utils/getFolderStructure', () => ({
46
+ getFolderStructure: vi.fn().mockResolvedValue('Mock Folder Structure'),
47
+ }));
48
+ vi.mock('../utils/errorReporting', () => ({ reportError: vi.fn() }));
49
+ vi.mock('../utils/nextSpeakerChecker', () => ({
50
+ checkNextSpeaker: vi.fn().mockResolvedValue(null),
51
+ }));
52
+ vi.mock('../utils/generateContentResponseUtilities', () => ({
53
+ getResponseText: (result) => result.candidates?.[0]?.content?.parts?.map((part) => part.text).join('') ||
54
+ undefined,
55
+ }));
56
+ vi.mock('../telemetry/index.js', () => ({
57
+ logApiRequest: vi.fn(),
58
+ logApiResponse: vi.fn(),
59
+ logApiError: vi.fn(),
60
+ }));
61
+ vi.mock('../ide/ideContext.js');
62
+ describe('findIndexAfterFraction', () => {
63
+ const history = [
64
+ { role: 'user', parts: [{ text: 'This is the first message.' }] }, // JSON length: 66
65
+ { role: 'model', parts: [{ text: 'This is the second message.' }] }, // JSON length: 68
66
+ { role: 'user', parts: [{ text: 'This is the third message.' }] }, // JSON length: 66
67
+ { role: 'model', parts: [{ text: 'This is the fourth message.' }] }, // JSON length: 68
68
+ { role: 'user', parts: [{ text: 'This is the fifth message.' }] }, // JSON length: 65
69
+ ];
70
+ // Total length: 333
71
+ it('should throw an error for non-positive numbers', () => {
72
+ expect(() => findIndexAfterFraction(history, 0)).toThrow('Fraction must be between 0 and 1');
73
+ });
74
+ it('should throw an error for a fraction greater than or equal to 1', () => {
75
+ expect(() => findIndexAfterFraction(history, 1)).toThrow('Fraction must be between 0 and 1');
76
+ });
77
+ it('should handle a fraction in the middle', () => {
78
+ // 333 * 0.5 = 166.5
79
+ // 0: 66
80
+ // 1: 66 + 68 = 134
81
+ // 2: 134 + 66 = 200
82
+ // 200 >= 166.5, so index is 2
83
+ expect(findIndexAfterFraction(history, 0.5)).toBe(2);
84
+ });
85
+ it('should handle a fraction that results in the last index', () => {
86
+ // 333 * 0.9 = 299.7
87
+ // ...
88
+ // 3: 200 + 68 = 268
89
+ // 4: 268 + 65 = 333
90
+ // 333 >= 299.7, so index is 4
91
+ expect(findIndexAfterFraction(history, 0.9)).toBe(4);
92
+ });
93
+ it('should handle an empty history', () => {
94
+ expect(findIndexAfterFraction([], 0.5)).toBe(0);
95
+ });
96
+ it('should handle a history with only one item', () => {
97
+ expect(findIndexAfterFraction(history.slice(0, 1), 0.5)).toBe(0);
98
+ });
99
+ it('should handle history with weird parts', () => {
100
+ const historyWithEmptyParts = [
101
+ { role: 'user', parts: [{ text: 'Message 1' }] },
102
+ { role: 'model', parts: [{ fileData: { fileUri: 'derp' } }] },
103
+ { role: 'user', parts: [{ text: 'Message 2' }] },
104
+ ];
105
+ expect(findIndexAfterFraction(historyWithEmptyParts, 0.5)).toBe(1);
106
+ });
107
+ });
108
+ describe('Gemini Client (client.ts)', () => {
109
+ let client;
110
+ beforeEach(async () => {
111
+ vi.resetAllMocks();
112
+ // Disable 429 simulation for tests
113
+ setSimulate429(false);
114
+ // Set up the mock for GoogleGenAI constructor and its methods
115
+ const MockedGoogleGenAI = vi.mocked(GoogleGenAI);
116
+ MockedGoogleGenAI.mockImplementation(() => {
117
+ const mock = {
118
+ chats: { create: mockChatCreateFn },
119
+ models: {
120
+ generateContent: mockGenerateContentFn,
121
+ embedContent: mockEmbedContentFn,
122
+ },
123
+ };
124
+ return mock;
125
+ });
126
+ mockChatCreateFn.mockResolvedValue({});
127
+ mockGenerateContentFn.mockResolvedValue({
128
+ candidates: [
129
+ {
130
+ content: {
131
+ parts: [{ text: '{"key": "value"}' }],
132
+ },
133
+ },
134
+ ],
135
+ });
136
+ // Because the GeminiClient constructor kicks off an async process (startChat)
137
+ // that depends on a fully-formed Config object, we need to mock the
138
+ // entire implementation of Config for these tests.
139
+ const mockToolRegistry = {
140
+ getFunctionDeclarations: vi.fn().mockReturnValue([]),
141
+ getTool: vi.fn().mockReturnValue(null),
142
+ };
143
+ const fileService = new FileDiscoveryService('/test/dir');
144
+ const contentGeneratorConfig = {
145
+ model: 'test-model',
146
+ apiKey: 'test-key',
147
+ vertexai: false,
148
+ authType: AuthType.USE_GEMINI,
149
+ };
150
+ const mockConfigObject = {
151
+ getContentGeneratorConfig: vi
152
+ .fn()
153
+ .mockReturnValue(contentGeneratorConfig),
154
+ getToolRegistry: vi.fn().mockResolvedValue(mockToolRegistry),
155
+ getModel: vi.fn().mockReturnValue('test-model'),
156
+ getEmbeddingModel: vi.fn().mockReturnValue('test-embedding-model'),
157
+ getApiKey: vi.fn().mockReturnValue('test-key'),
158
+ getVertexAI: vi.fn().mockReturnValue(false),
159
+ getUserAgent: vi.fn().mockReturnValue('test-agent'),
160
+ getUserMemory: vi.fn().mockReturnValue(''),
161
+ getFullContext: vi.fn().mockReturnValue(false),
162
+ getSessionId: vi.fn().mockReturnValue('test-session-id'),
163
+ getProxy: vi.fn().mockReturnValue(undefined),
164
+ getWorkingDir: vi.fn().mockReturnValue('/test/dir'),
165
+ getFileService: vi.fn().mockReturnValue(fileService),
166
+ getMaxSessionTurns: vi.fn().mockReturnValue(0),
167
+ getQuotaErrorOccurred: vi.fn().mockReturnValue(false),
168
+ setQuotaErrorOccurred: vi.fn(),
169
+ getNoBrowser: vi.fn().mockReturnValue(false),
170
+ getUsageStatisticsEnabled: vi.fn().mockReturnValue(true),
171
+ getIdeModeFeature: vi.fn().mockReturnValue(false),
172
+ getIdeMode: vi.fn().mockReturnValue(true),
173
+ getWorkspaceContext: vi.fn().mockReturnValue({
174
+ getDirectories: vi.fn().mockReturnValue(['/test/dir']),
175
+ }),
176
+ getGeminiClient: vi.fn(),
177
+ setFallbackMode: vi.fn(),
178
+ getChatCompression: vi.fn().mockReturnValue(undefined),
179
+ };
180
+ const MockedConfig = vi.mocked(Config, true);
181
+ MockedConfig.mockImplementation(() => mockConfigObject);
182
+ // We can instantiate the client here since Config is mocked
183
+ // and the constructor will use the mocked GoogleGenAI
184
+ client = new GeminiClient(new Config({ sessionId: 'test-session-id' }));
185
+ mockConfigObject.getGeminiClient.mockReturnValue(client);
186
+ await client.initialize(contentGeneratorConfig);
187
+ });
188
+ afterEach(() => {
189
+ vi.restoreAllMocks();
190
+ });
191
+ // NOTE: The following tests for startChat were removed due to persistent issues with
192
+ // the @google/genai mock. Specifically, the mockChatCreateFn (representing instance.chats.create)
193
+ // was not being detected as called by the GeminiClient instance.
194
+ // This likely points to a subtle issue in how the GoogleGenerativeAI class constructor
195
+ // and its instance methods are mocked and then used by the class under test.
196
+ // For future debugging, ensure that the `this.client` in `GeminiClient` (which is an
197
+ // instance of the mocked GoogleGenerativeAI) correctly has its `chats.create` method
198
+ // pointing to `mockChatCreateFn`.
199
+ // it('startChat should call getCoreSystemPrompt with userMemory and pass to chats.create', async () => { ... });
200
+ // it('startChat should call getCoreSystemPrompt with empty string if userMemory is empty', async () => { ... });
201
+ // NOTE: The following tests for generateJson were removed due to persistent issues with
202
+ // the @google/genai mock, similar to the startChat tests. The mockGenerateContentFn
203
+ // (representing instance.models.generateContent) was not being detected as called, or the mock
204
+ // was not preventing an actual API call (leading to API key errors).
205
+ // For future debugging, ensure `this.client.models.generateContent` in `GeminiClient` correctly
206
+ // uses the `mockGenerateContentFn`.
207
+ // it('generateJson should call getCoreSystemPrompt with userMemory and pass to generateContent', async () => { ... });
208
+ // it('generateJson should call getCoreSystemPrompt with empty string if userMemory is empty', async () => { ... });
209
+ describe('generateEmbedding', () => {
210
+ const texts = ['hello world', 'goodbye world'];
211
+ const testEmbeddingModel = 'test-embedding-model';
212
+ it('should call embedContent with correct parameters and return embeddings', async () => {
213
+ const mockEmbeddings = [
214
+ [0.1, 0.2, 0.3],
215
+ [0.4, 0.5, 0.6],
216
+ ];
217
+ const mockResponse = {
218
+ embeddings: [
219
+ { values: mockEmbeddings[0] },
220
+ { values: mockEmbeddings[1] },
221
+ ],
222
+ };
223
+ mockEmbedContentFn.mockResolvedValue(mockResponse);
224
+ const result = await client.generateEmbedding(texts);
225
+ expect(mockEmbedContentFn).toHaveBeenCalledTimes(1);
226
+ expect(mockEmbedContentFn).toHaveBeenCalledWith({
227
+ model: testEmbeddingModel,
228
+ contents: texts,
229
+ });
230
+ expect(result).toEqual(mockEmbeddings);
231
+ });
232
+ it('should return an empty array if an empty array is passed', async () => {
233
+ const result = await client.generateEmbedding([]);
234
+ expect(result).toEqual([]);
235
+ expect(mockEmbedContentFn).not.toHaveBeenCalled();
236
+ });
237
+ it('should throw an error if API response has no embeddings array', async () => {
238
+ mockEmbedContentFn.mockResolvedValue({}); // No `embeddings` key
239
+ await expect(client.generateEmbedding(texts)).rejects.toThrow('No embeddings found in API response.');
240
+ });
241
+ it('should throw an error if API response has an empty embeddings array', async () => {
242
+ const mockResponse = {
243
+ embeddings: [],
244
+ };
245
+ mockEmbedContentFn.mockResolvedValue(mockResponse);
246
+ await expect(client.generateEmbedding(texts)).rejects.toThrow('No embeddings found in API response.');
247
+ });
248
+ it('should throw an error if API returns a mismatched number of embeddings', async () => {
249
+ const mockResponse = {
250
+ embeddings: [{ values: [1, 2, 3] }], // Only one for two texts
251
+ };
252
+ mockEmbedContentFn.mockResolvedValue(mockResponse);
253
+ await expect(client.generateEmbedding(texts)).rejects.toThrow('API returned a mismatched number of embeddings. Expected 2, got 1.');
254
+ });
255
+ it('should throw an error if any embedding has nullish values', async () => {
256
+ const mockResponse = {
257
+ embeddings: [{ values: [1, 2, 3] }, { values: undefined }], // Second one is bad
258
+ };
259
+ mockEmbedContentFn.mockResolvedValue(mockResponse);
260
+ await expect(client.generateEmbedding(texts)).rejects.toThrow('API returned an empty embedding for input text at index 1: "goodbye world"');
261
+ });
262
+ it('should throw an error if any embedding has an empty values array', async () => {
263
+ const mockResponse = {
264
+ embeddings: [{ values: [] }, { values: [1, 2, 3] }], // First one is bad
265
+ };
266
+ mockEmbedContentFn.mockResolvedValue(mockResponse);
267
+ await expect(client.generateEmbedding(texts)).rejects.toThrow('API returned an empty embedding for input text at index 0: "hello world"');
268
+ });
269
+ it('should propagate errors from the API call', async () => {
270
+ const apiError = new Error('API Failure');
271
+ mockEmbedContentFn.mockRejectedValue(apiError);
272
+ await expect(client.generateEmbedding(texts)).rejects.toThrow('API Failure');
273
+ });
274
+ });
275
+ describe('generateContent', () => {
276
+ it('should call generateContent with the correct parameters', async () => {
277
+ const contents = [{ role: 'user', parts: [{ text: 'hello' }] }];
278
+ const generationConfig = { temperature: 0.5 };
279
+ const abortSignal = new AbortController().signal;
280
+ // Mock countTokens
281
+ const mockGenerator = {
282
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 1 }),
283
+ generateContent: mockGenerateContentFn,
284
+ };
285
+ client['contentGenerator'] = mockGenerator;
286
+ await client.generateContent(contents, generationConfig, abortSignal);
287
+ expect(mockGenerateContentFn).toHaveBeenCalledWith({
288
+ model: 'test-model',
289
+ config: {
290
+ abortSignal,
291
+ systemInstruction: getCoreSystemPrompt(''),
292
+ temperature: 0.5,
293
+ topP: 1,
294
+ },
295
+ contents,
296
+ }, 'test-session-id');
297
+ });
298
+ });
299
+ describe('generateJson', () => {
300
+ it('should call generateContent with the correct parameters', async () => {
301
+ const contents = [{ role: 'user', parts: [{ text: 'hello' }] }];
302
+ const schema = { type: 'string' };
303
+ const abortSignal = new AbortController().signal;
304
+ // Mock countTokens
305
+ const mockGenerator = {
306
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 1 }),
307
+ generateContent: mockGenerateContentFn,
308
+ };
309
+ client['contentGenerator'] = mockGenerator;
310
+ await client.generateJson(contents, schema, abortSignal);
311
+ expect(mockGenerateContentFn).toHaveBeenCalledWith({
312
+ model: 'test-model', // Should use current model from config
313
+ config: {
314
+ abortSignal,
315
+ systemInstruction: getCoreSystemPrompt(''),
316
+ temperature: 0,
317
+ topP: 1,
318
+ responseSchema: schema,
319
+ responseMimeType: 'application/json',
320
+ },
321
+ contents,
322
+ }, 'test-session-id');
323
+ });
324
+ it('should allow overriding model and config', async () => {
325
+ const contents = [{ role: 'user', parts: [{ text: 'hello' }] }];
326
+ const schema = { type: 'string' };
327
+ const abortSignal = new AbortController().signal;
328
+ const customModel = 'custom-json-model';
329
+ const customConfig = { temperature: 0.9, topK: 20 };
330
+ const mockGenerator = {
331
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 1 }),
332
+ generateContent: mockGenerateContentFn,
333
+ };
334
+ client['contentGenerator'] = mockGenerator;
335
+ await client.generateJson(contents, schema, abortSignal, customModel, customConfig);
336
+ expect(mockGenerateContentFn).toHaveBeenCalledWith({
337
+ model: customModel,
338
+ config: {
339
+ abortSignal,
340
+ systemInstruction: getCoreSystemPrompt(''),
341
+ temperature: 0.9,
342
+ topP: 1, // from default
343
+ topK: 20,
344
+ responseSchema: schema,
345
+ responseMimeType: 'application/json',
346
+ },
347
+ contents,
348
+ }, 'test-session-id');
349
+ });
350
+ });
351
+ describe('addHistory', () => {
352
+ it('should call chat.addHistory with the provided content', async () => {
353
+ const mockChat = {
354
+ addHistory: vi.fn(),
355
+ };
356
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
357
+ client['chat'] = mockChat;
358
+ const newContent = {
359
+ role: 'user',
360
+ parts: [{ text: 'New history item' }],
361
+ };
362
+ await client.addHistory(newContent);
363
+ expect(mockChat.addHistory).toHaveBeenCalledWith(newContent);
364
+ });
365
+ });
366
+ describe('resetChat', () => {
367
+ it('should create a new chat session, clearing the old history', async () => {
368
+ // 1. Get the initial chat instance and add some history.
369
+ const initialChat = client.getChat();
370
+ const initialHistory = await client.getHistory();
371
+ await client.addHistory({
372
+ role: 'user',
373
+ parts: [{ text: 'some old message' }],
374
+ });
375
+ const historyWithOldMessage = await client.getHistory();
376
+ expect(historyWithOldMessage.length).toBeGreaterThan(initialHistory.length);
377
+ // 2. Call resetChat.
378
+ await client.resetChat();
379
+ // 3. Get the new chat instance and its history.
380
+ const newChat = client.getChat();
381
+ const newHistory = await client.getHistory();
382
+ // 4. Assert that the chat instance is new and the history is reset.
383
+ expect(newChat).not.toBe(initialChat);
384
+ expect(newHistory.length).toBe(initialHistory.length);
385
+ expect(JSON.stringify(newHistory)).not.toContain('some old message');
386
+ });
387
+ });
388
+ describe('tryCompressChat', () => {
389
+ const mockCountTokens = vi.fn();
390
+ const mockSendMessage = vi.fn();
391
+ const mockGetHistory = vi.fn();
392
+ beforeEach(() => {
393
+ vi.mock('./tokenLimits', () => ({
394
+ tokenLimit: vi.fn(),
395
+ }));
396
+ client['contentGenerator'] = {
397
+ countTokens: mockCountTokens,
398
+ };
399
+ client['chat'] = {
400
+ getHistory: mockGetHistory,
401
+ addHistory: vi.fn(),
402
+ setHistory: vi.fn(),
403
+ sendMessage: mockSendMessage,
404
+ };
405
+ });
406
+ it('should not trigger summarization if token count is below threshold', async () => {
407
+ const MOCKED_TOKEN_LIMIT = 1000;
408
+ vi.mocked(tokenLimit).mockReturnValue(MOCKED_TOKEN_LIMIT);
409
+ mockGetHistory.mockReturnValue([
410
+ { role: 'user', parts: [{ text: '...history...' }] },
411
+ ]);
412
+ mockCountTokens.mockResolvedValue({
413
+ totalTokens: MOCKED_TOKEN_LIMIT * 0.699, // TOKEN_THRESHOLD_FOR_SUMMARIZATION = 0.7
414
+ });
415
+ const initialChat = client.getChat();
416
+ const result = await client.tryCompressChat('prompt-id-2');
417
+ const newChat = client.getChat();
418
+ expect(tokenLimit).toHaveBeenCalled();
419
+ expect(result).toBeNull();
420
+ expect(newChat).toBe(initialChat);
421
+ });
422
+ it('should trigger summarization if token count is at threshold with contextPercentageThreshold setting', async () => {
423
+ const MOCKED_TOKEN_LIMIT = 1000;
424
+ const MOCKED_CONTEXT_PERCENTAGE_THRESHOLD = 0.5;
425
+ vi.mocked(tokenLimit).mockReturnValue(MOCKED_TOKEN_LIMIT);
426
+ vi.spyOn(client['config'], 'getChatCompression').mockReturnValue({
427
+ contextPercentageThreshold: MOCKED_CONTEXT_PERCENTAGE_THRESHOLD,
428
+ });
429
+ mockGetHistory.mockReturnValue([
430
+ { role: 'user', parts: [{ text: '...history...' }] },
431
+ ]);
432
+ const originalTokenCount = MOCKED_TOKEN_LIMIT * MOCKED_CONTEXT_PERCENTAGE_THRESHOLD;
433
+ const newTokenCount = 100;
434
+ mockCountTokens
435
+ .mockResolvedValueOnce({ totalTokens: originalTokenCount }) // First call for the check
436
+ .mockResolvedValueOnce({ totalTokens: newTokenCount }); // Second call for the new history
437
+ // Mock the summary response from the chat
438
+ mockSendMessage.mockResolvedValue({
439
+ role: 'model',
440
+ parts: [{ text: 'This is a summary.' }],
441
+ });
442
+ const initialChat = client.getChat();
443
+ const result = await client.tryCompressChat('prompt-id-3');
444
+ const newChat = client.getChat();
445
+ expect(tokenLimit).toHaveBeenCalled();
446
+ expect(mockSendMessage).toHaveBeenCalled();
447
+ // Assert that summarization happened and returned the correct stats
448
+ expect(result).toEqual({
449
+ originalTokenCount,
450
+ newTokenCount,
451
+ });
452
+ // Assert that the chat was reset
453
+ expect(newChat).not.toBe(initialChat);
454
+ });
455
+ it('should not compress across a function call response', async () => {
456
+ const MOCKED_TOKEN_LIMIT = 1000;
457
+ vi.mocked(tokenLimit).mockReturnValue(MOCKED_TOKEN_LIMIT);
458
+ mockGetHistory.mockReturnValue([
459
+ { role: 'user', parts: [{ text: '...history 1...' }] },
460
+ { role: 'model', parts: [{ text: '...history 2...' }] },
461
+ { role: 'user', parts: [{ text: '...history 3...' }] },
462
+ { role: 'model', parts: [{ text: '...history 4...' }] },
463
+ { role: 'user', parts: [{ text: '...history 5...' }] },
464
+ { role: 'model', parts: [{ text: '...history 6...' }] },
465
+ { role: 'user', parts: [{ text: '...history 7...' }] },
466
+ { role: 'model', parts: [{ text: '...history 8...' }] },
467
+ // Normally we would break here, but we have a function response.
468
+ {
469
+ role: 'user',
470
+ parts: [{ functionResponse: { name: '...history 8...' } }],
471
+ },
472
+ { role: 'model', parts: [{ text: '...history 10...' }] },
473
+ // Instead we will break here.
474
+ { role: 'user', parts: [{ text: '...history 10...' }] },
475
+ ]);
476
+ const originalTokenCount = 1000 * 0.7;
477
+ const newTokenCount = 100;
478
+ mockCountTokens
479
+ .mockResolvedValueOnce({ totalTokens: originalTokenCount }) // First call for the check
480
+ .mockResolvedValueOnce({ totalTokens: newTokenCount }); // Second call for the new history
481
+ // Mock the summary response from the chat
482
+ mockSendMessage.mockResolvedValue({
483
+ role: 'model',
484
+ parts: [{ text: 'This is a summary.' }],
485
+ });
486
+ const initialChat = client.getChat();
487
+ const result = await client.tryCompressChat('prompt-id-3');
488
+ const newChat = client.getChat();
489
+ expect(tokenLimit).toHaveBeenCalled();
490
+ expect(mockSendMessage).toHaveBeenCalled();
491
+ // Assert that summarization happened and returned the correct stats
492
+ expect(result).toEqual({
493
+ originalTokenCount,
494
+ newTokenCount,
495
+ });
496
+ // Assert that the chat was reset
497
+ expect(newChat).not.toBe(initialChat);
498
+ // 1. standard start context message
499
+ // 2. standard canned user start message
500
+ // 3. compressed summary message
501
+ // 4. standard canned user summary message
502
+ // 5. The last user message (not the last 3 because that would start with a function response)
503
+ expect(newChat.getHistory().length).toEqual(5);
504
+ });
505
+ it('should always trigger summarization when force is true, regardless of token count', async () => {
506
+ mockGetHistory.mockReturnValue([
507
+ { role: 'user', parts: [{ text: '...history...' }] },
508
+ ]);
509
+ const originalTokenCount = 10; // Well below threshold
510
+ const newTokenCount = 5;
511
+ mockCountTokens
512
+ .mockResolvedValueOnce({ totalTokens: originalTokenCount })
513
+ .mockResolvedValueOnce({ totalTokens: newTokenCount });
514
+ // Mock the summary response from the chat
515
+ mockSendMessage.mockResolvedValue({
516
+ role: 'model',
517
+ parts: [{ text: 'This is a summary.' }],
518
+ });
519
+ const initialChat = client.getChat();
520
+ const result = await client.tryCompressChat('prompt-id-1', true); // force = true
521
+ const newChat = client.getChat();
522
+ expect(mockSendMessage).toHaveBeenCalled();
523
+ expect(result).toEqual({
524
+ originalTokenCount,
525
+ newTokenCount,
526
+ });
527
+ // Assert that the chat was reset
528
+ expect(newChat).not.toBe(initialChat);
529
+ });
530
+ });
531
+ describe('sendMessageStream', () => {
532
+ it('should include IDE context when ideModeFeature is enabled', async () => {
533
+ // Arrange
534
+ vi.mocked(ideContext.getIdeContext).mockReturnValue({
535
+ workspaceState: {
536
+ openFiles: [
537
+ {
538
+ path: '/path/to/active/file.ts',
539
+ timestamp: Date.now(),
540
+ isActive: true,
541
+ selectedText: 'hello',
542
+ cursor: { line: 5, character: 10 },
543
+ },
544
+ {
545
+ path: '/path/to/recent/file1.ts',
546
+ timestamp: Date.now(),
547
+ },
548
+ {
549
+ path: '/path/to/recent/file2.ts',
550
+ timestamp: Date.now(),
551
+ },
552
+ ],
553
+ },
554
+ });
555
+ vi.spyOn(client['config'], 'getIdeModeFeature').mockReturnValue(true);
556
+ const mockStream = (async function* () {
557
+ yield { type: 'content', value: 'Hello' };
558
+ })();
559
+ mockTurnRunFn.mockReturnValue(mockStream);
560
+ const mockChat = {
561
+ addHistory: vi.fn(),
562
+ getHistory: vi.fn().mockReturnValue([]),
563
+ };
564
+ client['chat'] = mockChat;
565
+ const mockGenerator = {
566
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
567
+ generateContent: mockGenerateContentFn,
568
+ };
569
+ client['contentGenerator'] = mockGenerator;
570
+ const initialRequest = [{ text: 'Hi' }];
571
+ // Act
572
+ const stream = client.sendMessageStream(initialRequest, new AbortController().signal, 'prompt-id-ide');
573
+ for await (const _ of stream) {
574
+ // consume stream
575
+ }
576
+ // Assert
577
+ expect(ideContext.getIdeContext).toHaveBeenCalled();
578
+ const expectedContext = `
579
+ This is the file that the user is looking at:
580
+ - Path: /path/to/active/file.ts
581
+ This is the cursor position in the file:
582
+ - Cursor Position: Line 5, Character 10
583
+ This is the selected text in the file:
584
+ - hello
585
+ Here are some other files the user has open, with the most recent at the top:
586
+ - /path/to/recent/file1.ts
587
+ - /path/to/recent/file2.ts
588
+ `.trim();
589
+ const expectedRequest = [{ text: expectedContext }, ...initialRequest];
590
+ expect(mockTurnRunFn).toHaveBeenCalledWith(expectedRequest, expect.any(Object));
591
+ });
592
+ it('should not add context if ideModeFeature is enabled but no open files', async () => {
593
+ // Arrange
594
+ vi.mocked(ideContext.getIdeContext).mockReturnValue({
595
+ workspaceState: {
596
+ openFiles: [],
597
+ },
598
+ });
599
+ vi.spyOn(client['config'], 'getIdeModeFeature').mockReturnValue(true);
600
+ const mockStream = (async function* () {
601
+ yield { type: 'content', value: 'Hello' };
602
+ })();
603
+ mockTurnRunFn.mockReturnValue(mockStream);
604
+ const mockChat = {
605
+ addHistory: vi.fn(),
606
+ getHistory: vi.fn().mockReturnValue([]),
607
+ };
608
+ client['chat'] = mockChat;
609
+ const mockGenerator = {
610
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
611
+ generateContent: mockGenerateContentFn,
612
+ };
613
+ client['contentGenerator'] = mockGenerator;
614
+ const initialRequest = [{ text: 'Hi' }];
615
+ // Act
616
+ const stream = client.sendMessageStream(initialRequest, new AbortController().signal, 'prompt-id-ide');
617
+ for await (const _ of stream) {
618
+ // consume stream
619
+ }
620
+ // Assert
621
+ expect(ideContext.getIdeContext).toHaveBeenCalled();
622
+ expect(mockTurnRunFn).toHaveBeenCalledWith(initialRequest, expect.any(Object));
623
+ });
624
+ it('should add context if ideModeFeature is enabled and there is one active file', async () => {
625
+ // Arrange
626
+ vi.mocked(ideContext.getIdeContext).mockReturnValue({
627
+ workspaceState: {
628
+ openFiles: [
629
+ {
630
+ path: '/path/to/active/file.ts',
631
+ timestamp: Date.now(),
632
+ isActive: true,
633
+ selectedText: 'hello',
634
+ cursor: { line: 5, character: 10 },
635
+ },
636
+ ],
637
+ },
638
+ });
639
+ vi.spyOn(client['config'], 'getIdeModeFeature').mockReturnValue(true);
640
+ const mockStream = (async function* () {
641
+ yield { type: 'content', value: 'Hello' };
642
+ })();
643
+ mockTurnRunFn.mockReturnValue(mockStream);
644
+ const mockChat = {
645
+ addHistory: vi.fn(),
646
+ getHistory: vi.fn().mockReturnValue([]),
647
+ };
648
+ client['chat'] = mockChat;
649
+ const mockGenerator = {
650
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
651
+ generateContent: mockGenerateContentFn,
652
+ };
653
+ client['contentGenerator'] = mockGenerator;
654
+ const initialRequest = [{ text: 'Hi' }];
655
+ // Act
656
+ const stream = client.sendMessageStream(initialRequest, new AbortController().signal, 'prompt-id-ide');
657
+ for await (const _ of stream) {
658
+ // consume stream
659
+ }
660
+ // Assert
661
+ expect(ideContext.getIdeContext).toHaveBeenCalled();
662
+ const expectedContext = `
663
+ This is the file that the user is looking at:
664
+ - Path: /path/to/active/file.ts
665
+ This is the cursor position in the file:
666
+ - Cursor Position: Line 5, Character 10
667
+ This is the selected text in the file:
668
+ - hello
669
+ `.trim();
670
+ const expectedRequest = [{ text: expectedContext }, ...initialRequest];
671
+ expect(mockTurnRunFn).toHaveBeenCalledWith(expectedRequest, expect.any(Object));
672
+ });
673
+ it('should add context if ideModeFeature is enabled and there are open files but no active file', async () => {
674
+ // Arrange
675
+ vi.mocked(ideContext.getIdeContext).mockReturnValue({
676
+ workspaceState: {
677
+ openFiles: [
678
+ {
679
+ path: '/path/to/recent/file1.ts',
680
+ timestamp: Date.now(),
681
+ },
682
+ {
683
+ path: '/path/to/recent/file2.ts',
684
+ timestamp: Date.now(),
685
+ },
686
+ ],
687
+ },
688
+ });
689
+ vi.spyOn(client['config'], 'getIdeModeFeature').mockReturnValue(true);
690
+ const mockStream = (async function* () {
691
+ yield { type: 'content', value: 'Hello' };
692
+ })();
693
+ mockTurnRunFn.mockReturnValue(mockStream);
694
+ const mockChat = {
695
+ addHistory: vi.fn(),
696
+ getHistory: vi.fn().mockReturnValue([]),
697
+ };
698
+ client['chat'] = mockChat;
699
+ const mockGenerator = {
700
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
701
+ generateContent: mockGenerateContentFn,
702
+ };
703
+ client['contentGenerator'] = mockGenerator;
704
+ const initialRequest = [{ text: 'Hi' }];
705
+ // Act
706
+ const stream = client.sendMessageStream(initialRequest, new AbortController().signal, 'prompt-id-ide');
707
+ for await (const _ of stream) {
708
+ // consume stream
709
+ }
710
+ // Assert
711
+ expect(ideContext.getIdeContext).toHaveBeenCalled();
712
+ const expectedContext = `
713
+ Here are some files the user has open, with the most recent at the top:
714
+ - /path/to/recent/file1.ts
715
+ - /path/to/recent/file2.ts
716
+ `.trim();
717
+ const expectedRequest = [{ text: expectedContext }, ...initialRequest];
718
+ expect(mockTurnRunFn).toHaveBeenCalledWith(expectedRequest, expect.any(Object));
719
+ });
720
+ it('should return the turn instance after the stream is complete', async () => {
721
+ // Arrange
722
+ const mockStream = (async function* () {
723
+ yield { type: 'content', value: 'Hello' };
724
+ })();
725
+ mockTurnRunFn.mockReturnValue(mockStream);
726
+ const mockChat = {
727
+ addHistory: vi.fn(),
728
+ getHistory: vi.fn().mockReturnValue([]),
729
+ };
730
+ client['chat'] = mockChat;
731
+ const mockGenerator = {
732
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
733
+ generateContent: mockGenerateContentFn,
734
+ };
735
+ client['contentGenerator'] = mockGenerator;
736
+ // Act
737
+ const stream = client.sendMessageStream([{ text: 'Hi' }], new AbortController().signal, 'prompt-id-1');
738
+ // Consume the stream manually to get the final return value.
739
+ let finalResult;
740
+ while (true) {
741
+ const result = await stream.next();
742
+ if (result.done) {
743
+ finalResult = result.value;
744
+ break;
745
+ }
746
+ }
747
+ // Assert
748
+ expect(finalResult).toBeInstanceOf(Turn);
749
+ });
750
+ it('should stop infinite loop after MAX_TURNS when nextSpeaker always returns model', async () => {
751
+ // Get the mocked checkNextSpeaker function and configure it to trigger infinite loop
752
+ const { checkNextSpeaker } = await import('../utils/nextSpeakerChecker.js');
753
+ const mockCheckNextSpeaker = vi.mocked(checkNextSpeaker);
754
+ mockCheckNextSpeaker.mockResolvedValue({
755
+ next_speaker: 'model',
756
+ reasoning: 'Test case - always continue',
757
+ });
758
+ // Mock Turn to have no pending tool calls (which would allow nextSpeaker check)
759
+ const mockStream = (async function* () {
760
+ yield { type: 'content', value: 'Continue...' };
761
+ })();
762
+ mockTurnRunFn.mockReturnValue(mockStream);
763
+ const mockChat = {
764
+ addHistory: vi.fn(),
765
+ getHistory: vi.fn().mockReturnValue([]),
766
+ };
767
+ client['chat'] = mockChat;
768
+ const mockGenerator = {
769
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
770
+ generateContent: mockGenerateContentFn,
771
+ };
772
+ client['contentGenerator'] = mockGenerator;
773
+ // Use a signal that never gets aborted
774
+ const abortController = new AbortController();
775
+ const signal = abortController.signal;
776
+ // Act - Start the stream that should loop
777
+ const stream = client.sendMessageStream([{ text: 'Start conversation' }], signal, 'prompt-id-2');
778
+ // Count how many stream events we get
779
+ let eventCount = 0;
780
+ let finalResult;
781
+ // Consume the stream and count iterations
782
+ while (true) {
783
+ const result = await stream.next();
784
+ if (result.done) {
785
+ finalResult = result.value;
786
+ break;
787
+ }
788
+ eventCount++;
789
+ // Safety check to prevent actual infinite loop in test
790
+ if (eventCount > 200) {
791
+ abortController.abort();
792
+ throw new Error('Test exceeded expected event limit - possible actual infinite loop');
793
+ }
794
+ }
795
+ // Assert
796
+ expect(finalResult).toBeInstanceOf(Turn);
797
+ // Debug: Check how many times checkNextSpeaker was called
798
+ const callCount = mockCheckNextSpeaker.mock.calls.length;
799
+ // If infinite loop protection is working, checkNextSpeaker should be called many times
800
+ // but stop at MAX_TURNS (100). Since each recursive call should trigger checkNextSpeaker,
801
+ // we expect it to be called multiple times before hitting the limit
802
+ expect(mockCheckNextSpeaker).toHaveBeenCalled();
803
+ // The test should demonstrate that the infinite loop protection works:
804
+ // - If checkNextSpeaker is called many times (close to MAX_TURNS), it shows the loop was happening
805
+ // - If it's only called once, the recursive behavior might not be triggered
806
+ if (callCount === 0) {
807
+ throw new Error('checkNextSpeaker was never called - the recursive condition was not met');
808
+ }
809
+ else if (callCount === 1) {
810
+ // This might be expected behavior if the turn has pending tool calls or other conditions prevent recursion
811
+ console.log('checkNextSpeaker called only once - no infinite loop occurred');
812
+ }
813
+ else {
814
+ console.log(`checkNextSpeaker called ${callCount} times - infinite loop protection worked`);
815
+ // If called multiple times, we expect it to be stopped before MAX_TURNS
816
+ expect(callCount).toBeLessThanOrEqual(100); // Should not exceed MAX_TURNS
817
+ }
818
+ // The stream should produce events and eventually terminate
819
+ expect(eventCount).toBeGreaterThanOrEqual(1);
820
+ expect(eventCount).toBeLessThan(200); // Should not exceed our safety limit
821
+ });
822
+ it('should yield MaxSessionTurns and stop when session turn limit is reached', async () => {
823
+ // Arrange
824
+ const MAX_SESSION_TURNS = 5;
825
+ vi.spyOn(client['config'], 'getMaxSessionTurns').mockReturnValue(MAX_SESSION_TURNS);
826
+ const mockStream = (async function* () {
827
+ yield { type: 'content', value: 'Hello' };
828
+ })();
829
+ mockTurnRunFn.mockReturnValue(mockStream);
830
+ const mockChat = {
831
+ addHistory: vi.fn(),
832
+ getHistory: vi.fn().mockReturnValue([]),
833
+ };
834
+ client['chat'] = mockChat;
835
+ const mockGenerator = {
836
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
837
+ generateContent: mockGenerateContentFn,
838
+ };
839
+ client['contentGenerator'] = mockGenerator;
840
+ // Act & Assert
841
+ // Run up to the limit
842
+ for (let i = 0; i < MAX_SESSION_TURNS; i++) {
843
+ const stream = client.sendMessageStream([{ text: 'Hi' }], new AbortController().signal, 'prompt-id-4');
844
+ // consume stream
845
+ for await (const _event of stream) {
846
+ // do nothing
847
+ }
848
+ }
849
+ // This call should exceed the limit
850
+ const stream = client.sendMessageStream([{ text: 'Hi' }], new AbortController().signal, 'prompt-id-5');
851
+ const events = [];
852
+ for await (const event of stream) {
853
+ events.push(event);
854
+ }
855
+ expect(events).toEqual([{ type: GeminiEventType.MaxSessionTurns }]);
856
+ expect(mockTurnRunFn).toHaveBeenCalledTimes(MAX_SESSION_TURNS);
857
+ });
858
+ it('should respect MAX_TURNS limit even when turns parameter is set to a large value', async () => {
859
+ // This test verifies that the infinite loop protection works even when
860
+ // someone tries to bypass it by calling with a very large turns value
861
+ // Get the mocked checkNextSpeaker function and configure it to trigger infinite loop
862
+ const { checkNextSpeaker } = await import('../utils/nextSpeakerChecker.js');
863
+ const mockCheckNextSpeaker = vi.mocked(checkNextSpeaker);
864
+ mockCheckNextSpeaker.mockResolvedValue({
865
+ next_speaker: 'model',
866
+ reasoning: 'Test case - always continue',
867
+ });
868
+ // Mock Turn to have no pending tool calls (which would allow nextSpeaker check)
869
+ const mockStream = (async function* () {
870
+ yield { type: 'content', value: 'Continue...' };
871
+ })();
872
+ mockTurnRunFn.mockReturnValue(mockStream);
873
+ const mockChat = {
874
+ addHistory: vi.fn(),
875
+ getHistory: vi.fn().mockReturnValue([]),
876
+ };
877
+ client['chat'] = mockChat;
878
+ const mockGenerator = {
879
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 0 }),
880
+ generateContent: mockGenerateContentFn,
881
+ };
882
+ client['contentGenerator'] = mockGenerator;
883
+ // Use a signal that never gets aborted
884
+ const abortController = new AbortController();
885
+ const signal = abortController.signal;
886
+ // Act - Start the stream with an extremely high turns value
887
+ // This simulates a case where the turns protection is bypassed
888
+ const stream = client.sendMessageStream([{ text: 'Start conversation' }], signal, 'prompt-id-3', Number.MAX_SAFE_INTEGER);
889
+ // Count how many stream events we get
890
+ let eventCount = 0;
891
+ const maxTestIterations = 1000; // Higher limit to show the loop continues
892
+ // Consume the stream and count iterations
893
+ try {
894
+ while (true) {
895
+ const result = await stream.next();
896
+ if (result.done) {
897
+ break;
898
+ }
899
+ eventCount++;
900
+ // This test should hit this limit, demonstrating the infinite loop
901
+ if (eventCount > maxTestIterations) {
902
+ abortController.abort();
903
+ // This is the expected behavior - we hit the infinite loop
904
+ break;
905
+ }
906
+ }
907
+ }
908
+ catch (error) {
909
+ // If the test framework times out, that also demonstrates the infinite loop
910
+ console.error('Test timed out or errored:', error);
911
+ }
912
+ // Assert that the fix works - the loop should stop at MAX_TURNS
913
+ const callCount = mockCheckNextSpeaker.mock.calls.length;
914
+ // With the fix: even when turns is set to a very high value,
915
+ // the loop should stop at MAX_TURNS (100)
916
+ expect(callCount).toBeLessThanOrEqual(100); // Should not exceed MAX_TURNS
917
+ expect(eventCount).toBeLessThanOrEqual(200); // Should have reasonable number of events
918
+ console.log(`Infinite loop protection working: checkNextSpeaker called ${callCount} times, ` +
919
+ `${eventCount} events generated (properly bounded by MAX_TURNS)`);
920
+ });
921
+ });
922
+ describe('generateContent', () => {
923
+ it('should use current model from config for content generation', async () => {
924
+ const initialModel = client['config'].getModel();
925
+ const contents = [{ role: 'user', parts: [{ text: 'test' }] }];
926
+ const currentModel = initialModel + '-changed';
927
+ vi.spyOn(client['config'], 'getModel').mockReturnValueOnce(currentModel);
928
+ const mockGenerator = {
929
+ countTokens: vi.fn().mockResolvedValue({ totalTokens: 1 }),
930
+ generateContent: mockGenerateContentFn,
931
+ };
932
+ client['contentGenerator'] = mockGenerator;
933
+ await client.generateContent(contents, {}, new AbortController().signal);
934
+ expect(mockGenerateContentFn).not.toHaveBeenCalledWith({
935
+ model: initialModel,
936
+ config: expect.any(Object),
937
+ contents,
938
+ });
939
+ expect(mockGenerateContentFn).toHaveBeenCalledWith({
940
+ model: currentModel,
941
+ config: expect.any(Object),
942
+ contents,
943
+ }, 'test-session-id');
944
+ });
945
+ });
946
+ describe('tryCompressChat', () => {
947
+ it('should use current model from config for token counting after sendMessage', async () => {
948
+ const initialModel = client['config'].getModel();
949
+ const mockCountTokens = vi
950
+ .fn()
951
+ .mockResolvedValueOnce({ totalTokens: 100000 })
952
+ .mockResolvedValueOnce({ totalTokens: 5000 });
953
+ const mockSendMessage = vi.fn().mockResolvedValue({ text: 'Summary' });
954
+ const mockChatHistory = [
955
+ { role: 'user', parts: [{ text: 'Long conversation' }] },
956
+ { role: 'model', parts: [{ text: 'Long response' }] },
957
+ ];
958
+ const mockChat = {
959
+ getHistory: vi.fn().mockReturnValue(mockChatHistory),
960
+ setHistory: vi.fn(),
961
+ sendMessage: mockSendMessage,
962
+ };
963
+ const mockGenerator = {
964
+ countTokens: mockCountTokens,
965
+ };
966
+ // mock the model has been changed between calls of `countTokens`
967
+ const firstCurrentModel = initialModel + '-changed-1';
968
+ const secondCurrentModel = initialModel + '-changed-2';
969
+ vi.spyOn(client['config'], 'getModel')
970
+ .mockReturnValueOnce(firstCurrentModel)
971
+ .mockReturnValueOnce(secondCurrentModel);
972
+ client['chat'] = mockChat;
973
+ client['contentGenerator'] = mockGenerator;
974
+ client['startChat'] = vi.fn().mockResolvedValue(mockChat);
975
+ const result = await client.tryCompressChat('prompt-id-4', true);
976
+ expect(mockCountTokens).toHaveBeenCalledTimes(2);
977
+ expect(mockCountTokens).toHaveBeenNthCalledWith(1, {
978
+ model: firstCurrentModel,
979
+ contents: mockChatHistory,
980
+ });
981
+ expect(mockCountTokens).toHaveBeenNthCalledWith(2, {
982
+ model: secondCurrentModel,
983
+ contents: expect.any(Array),
984
+ });
985
+ expect(result).toEqual({
986
+ originalTokenCount: 100000,
987
+ newTokenCount: 5000,
988
+ });
989
+ });
990
+ });
991
+ describe('handleFlashFallback', () => {
992
+ it('should use current model from config when checking for fallback', async () => {
993
+ const initialModel = client['config'].getModel();
994
+ const fallbackModel = DEFAULT_GEMINI_FLASH_MODEL;
995
+ // mock config been changed
996
+ const currentModel = initialModel + '-changed';
997
+ const getModelSpy = vi.spyOn(client['config'], 'getModel');
998
+ getModelSpy.mockReturnValue(currentModel);
999
+ const mockFallbackHandler = vi.fn().mockResolvedValue(true);
1000
+ client['config'].flashFallbackHandler = mockFallbackHandler;
1001
+ client['config'].setModel = vi.fn();
1002
+ const result = await client['handleFlashFallback'](AuthType.LOGIN_WITH_GOOGLE);
1003
+ expect(result).toBe(fallbackModel);
1004
+ expect(mockFallbackHandler).toHaveBeenCalledWith(currentModel, fallbackModel, undefined);
1005
+ });
1006
+ });
1007
+ });
1008
+ //# sourceMappingURL=client.test.js.map