@office-ai/aioncli-core 0.2.2 → 0.8.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 (758) hide show
  1. package/dist/index.d.ts +10 -3
  2. package/dist/index.js +10 -3
  3. package/dist/index.js.map +1 -1
  4. package/dist/src/agents/codebase-investigator.d.ts +11 -0
  5. package/dist/src/agents/codebase-investigator.js +73 -0
  6. package/dist/src/agents/codebase-investigator.js.map +1 -0
  7. package/dist/src/agents/executor.d.ts +88 -0
  8. package/dist/src/agents/executor.js +417 -0
  9. package/dist/src/agents/executor.js.map +1 -0
  10. package/dist/src/agents/executor.test.js +419 -0
  11. package/dist/src/agents/executor.test.js.map +1 -0
  12. package/dist/src/agents/invocation.d.ts +43 -0
  13. package/dist/src/agents/invocation.js +100 -0
  14. package/dist/src/agents/invocation.js.map +1 -0
  15. package/dist/src/agents/invocation.test.js +206 -0
  16. package/dist/src/agents/invocation.test.js.map +1 -0
  17. package/dist/src/agents/registry.d.ts +35 -0
  18. package/dist/src/agents/registry.js +58 -0
  19. package/dist/src/agents/registry.js.map +1 -0
  20. package/dist/src/agents/registry.test.js +146 -0
  21. package/dist/src/agents/registry.test.js.map +1 -0
  22. package/dist/src/agents/schema-utils.d.ts +39 -0
  23. package/dist/src/agents/schema-utils.js +57 -0
  24. package/dist/src/agents/schema-utils.js.map +1 -0
  25. package/dist/src/agents/schema-utils.test.d.ts +6 -0
  26. package/dist/src/agents/schema-utils.test.js +144 -0
  27. package/dist/src/agents/schema-utils.test.js.map +1 -0
  28. package/dist/src/agents/subagent-tool-wrapper.d.ts +36 -0
  29. package/dist/src/agents/subagent-tool-wrapper.js +47 -0
  30. package/dist/src/agents/subagent-tool-wrapper.js.map +1 -0
  31. package/dist/src/agents/subagent-tool-wrapper.test.d.ts +6 -0
  32. package/dist/src/agents/subagent-tool-wrapper.test.js +105 -0
  33. package/dist/src/agents/subagent-tool-wrapper.test.js.map +1 -0
  34. package/dist/src/agents/types.d.ts +116 -0
  35. package/dist/src/agents/types.js +17 -0
  36. package/dist/src/agents/types.js.map +1 -0
  37. package/dist/src/agents/utils.d.ts +15 -0
  38. package/dist/src/agents/utils.js +29 -0
  39. package/dist/src/agents/utils.js.map +1 -0
  40. package/dist/src/agents/utils.test.d.ts +6 -0
  41. package/dist/src/agents/utils.test.js +87 -0
  42. package/dist/src/agents/utils.test.js.map +1 -0
  43. package/dist/src/code_assist/codeAssist.d.ts +6 -3
  44. package/dist/src/code_assist/codeAssist.js +12 -0
  45. package/dist/src/code_assist/codeAssist.js.map +1 -1
  46. package/dist/src/code_assist/converter.d.ts +4 -1
  47. package/dist/src/code_assist/converter.js +38 -5
  48. package/dist/src/code_assist/converter.js.map +1 -1
  49. package/dist/src/code_assist/converter.test.js +93 -0
  50. package/dist/src/code_assist/converter.test.js.map +1 -1
  51. package/dist/src/code_assist/oauth-credential-storage.d.ts +25 -0
  52. package/dist/src/code_assist/oauth-credential-storage.js +109 -0
  53. package/dist/src/code_assist/oauth-credential-storage.js.map +1 -0
  54. package/dist/src/code_assist/oauth-credential-storage.test.d.ts +6 -0
  55. package/dist/src/code_assist/oauth-credential-storage.test.js +136 -0
  56. package/dist/src/code_assist/oauth-credential-storage.test.js.map +1 -0
  57. package/dist/src/code_assist/oauth2.d.ts +1 -1
  58. package/dist/src/code_assist/oauth2.js +107 -48
  59. package/dist/src/code_assist/oauth2.js.map +1 -1
  60. package/dist/src/code_assist/oauth2.test.js +735 -343
  61. package/dist/src/code_assist/oauth2.test.js.map +1 -1
  62. package/dist/src/code_assist/server.d.ts +4 -4
  63. package/dist/src/code_assist/server.js +25 -2
  64. package/dist/src/code_assist/server.js.map +1 -1
  65. package/dist/src/code_assist/server.test.js +25 -0
  66. package/dist/src/code_assist/server.test.js.map +1 -1
  67. package/dist/src/code_assist/setup.d.ts +1 -1
  68. package/dist/src/code_assist/setup.js +1 -1
  69. package/dist/src/code_assist/setup.js.map +1 -1
  70. package/dist/src/code_assist/setup.test.js.map +1 -1
  71. package/dist/src/code_assist/types.d.ts +17 -2
  72. package/dist/src/config/config.d.ts +121 -25
  73. package/dist/src/config/config.js +298 -87
  74. package/dist/src/config/config.js.map +1 -1
  75. package/dist/src/config/config.test.js +370 -131
  76. package/dist/src/config/config.test.js.map +1 -1
  77. package/dist/src/config/constants.d.ts +11 -0
  78. package/dist/src/config/constants.js +16 -0
  79. package/dist/src/config/constants.js.map +1 -0
  80. package/dist/src/config/models.d.ts +16 -0
  81. package/dist/src/config/models.js +29 -0
  82. package/dist/src/config/models.js.map +1 -1
  83. package/dist/src/config/models.test.d.ts +6 -0
  84. package/dist/src/config/models.test.js +55 -0
  85. package/dist/src/config/models.test.js.map +1 -0
  86. package/dist/src/config/storage.d.ts +34 -0
  87. package/dist/src/config/storage.js +95 -0
  88. package/dist/src/config/storage.js.map +1 -0
  89. package/dist/src/config/storage.test.d.ts +6 -0
  90. package/dist/src/config/storage.test.js +47 -0
  91. package/dist/src/config/storage.test.js.map +1 -0
  92. package/dist/src/confirmation-bus/index.d.ts +7 -0
  93. package/dist/src/confirmation-bus/index.js +8 -0
  94. package/dist/src/confirmation-bus/index.js.map +1 -0
  95. package/dist/src/confirmation-bus/message-bus.d.ts +17 -0
  96. package/dist/src/confirmation-bus/message-bus.js +81 -0
  97. package/dist/src/confirmation-bus/message-bus.js.map +1 -0
  98. package/dist/src/confirmation-bus/message-bus.test.d.ts +6 -0
  99. package/dist/src/confirmation-bus/message-bus.test.js +164 -0
  100. package/dist/src/confirmation-bus/message-bus.test.js.map +1 -0
  101. package/dist/src/confirmation-bus/types.d.ts +38 -0
  102. package/dist/src/confirmation-bus/types.js +15 -0
  103. package/dist/src/confirmation-bus/types.js.map +1 -0
  104. package/dist/src/core/baseLlmClient.d.ts +54 -0
  105. package/dist/src/core/baseLlmClient.js +190 -0
  106. package/dist/src/core/baseLlmClient.js.map +1 -0
  107. package/dist/src/core/baseLlmClient.test.d.ts +6 -0
  108. package/dist/src/core/baseLlmClient.test.js +316 -0
  109. package/dist/src/core/baseLlmClient.test.js.map +1 -0
  110. package/dist/src/core/client.d.ts +28 -28
  111. package/dist/src/core/client.js +187 -333
  112. package/dist/src/core/client.js.map +1 -1
  113. package/dist/src/core/client.test.js +745 -500
  114. package/dist/src/core/client.test.js.map +1 -1
  115. package/dist/src/core/contentGenerator.d.ts +4 -4
  116. package/dist/src/core/contentGenerator.js +6 -7
  117. package/dist/src/core/contentGenerator.js.map +1 -1
  118. package/dist/src/core/contentGenerator.test.js +1 -3
  119. package/dist/src/core/contentGenerator.test.js.map +1 -1
  120. package/dist/src/core/coreToolScheduler.d.ts +20 -7
  121. package/dist/src/core/coreToolScheduler.js +216 -53
  122. package/dist/src/core/coreToolScheduler.js.map +1 -1
  123. package/dist/src/core/coreToolScheduler.test.js +564 -88
  124. package/dist/src/core/coreToolScheduler.test.js.map +1 -1
  125. package/dist/src/core/geminiChat.d.ts +54 -43
  126. package/dist/src/core/geminiChat.js +298 -280
  127. package/dist/src/core/geminiChat.js.map +1 -1
  128. package/dist/src/core/geminiChat.test.js +1255 -321
  129. package/dist/src/core/geminiChat.test.js.map +1 -1
  130. package/dist/src/core/geminiRequest.js +1 -0
  131. package/dist/src/core/geminiRequest.js.map +1 -1
  132. package/dist/src/core/logger.d.ts +4 -2
  133. package/dist/src/core/logger.js +4 -3
  134. package/dist/src/core/logger.js.map +1 -1
  135. package/dist/src/core/logger.test.js +17 -16
  136. package/dist/src/core/logger.test.js.map +1 -1
  137. package/dist/src/core/loggingContentGenerator.d.ts +3 -3
  138. package/dist/src/core/loggingContentGenerator.js +15 -16
  139. package/dist/src/core/loggingContentGenerator.js.map +1 -1
  140. package/dist/src/core/nonInteractiveToolExecutor.d.ts +3 -5
  141. package/dist/src/core/nonInteractiveToolExecutor.js +14 -122
  142. package/dist/src/core/nonInteractiveToolExecutor.js.map +1 -1
  143. package/dist/src/core/nonInteractiveToolExecutor.test.js +158 -78
  144. package/dist/src/core/nonInteractiveToolExecutor.test.js.map +1 -1
  145. package/dist/src/core/openaiContentGenerator.d.ts +4 -3
  146. package/dist/src/core/openaiContentGenerator.js +21 -14
  147. package/dist/src/core/openaiContentGenerator.js.map +1 -1
  148. package/dist/src/core/openaiContentGenerator.test.js +1 -0
  149. package/dist/src/core/openaiContentGenerator.test.js.map +1 -1
  150. package/dist/src/core/prompts.d.ts +5 -0
  151. package/dist/src/core/prompts.js +66 -44
  152. package/dist/src/core/prompts.js.map +1 -1
  153. package/dist/src/core/prompts.test.js +130 -1
  154. package/dist/src/core/prompts.test.js.map +1 -1
  155. package/dist/src/core/subagent.d.ts +24 -18
  156. package/dist/src/core/subagent.js +125 -90
  157. package/dist/src/core/subagent.js.map +1 -1
  158. package/dist/src/core/subagent.test.js +59 -44
  159. package/dist/src/core/subagent.test.js.map +1 -1
  160. package/dist/src/core/turn.d.ts +37 -13
  161. package/dist/src/core/turn.js +63 -28
  162. package/dist/src/core/turn.js.map +1 -1
  163. package/dist/src/core/turn.test.js +359 -100
  164. package/dist/src/core/turn.test.js.map +1 -1
  165. package/dist/src/fallback/handler.d.ts +7 -0
  166. package/dist/src/fallback/handler.js +129 -0
  167. package/dist/src/fallback/handler.js.map +1 -0
  168. package/dist/src/fallback/handler.test.d.ts +6 -0
  169. package/dist/src/fallback/handler.test.js +130 -0
  170. package/dist/src/fallback/handler.test.js.map +1 -0
  171. package/dist/src/fallback/types.d.ts +14 -0
  172. package/dist/src/fallback/types.js +7 -0
  173. package/dist/src/fallback/types.js.map +1 -0
  174. package/dist/src/generated/git-commit.d.ts +1 -1
  175. package/dist/src/generated/git-commit.js +1 -1
  176. package/dist/src/ide/constants.d.ts +3 -0
  177. package/dist/src/ide/constants.js +3 -0
  178. package/dist/src/ide/constants.js.map +1 -1
  179. package/dist/src/ide/detect-ide.d.ts +48 -12
  180. package/dist/src/ide/detect-ide.js +47 -66
  181. package/dist/src/ide/detect-ide.js.map +1 -1
  182. package/dist/src/ide/detect-ide.test.js +79 -52
  183. package/dist/src/ide/detect-ide.test.js.map +1 -1
  184. package/dist/src/ide/ide-client.d.ts +69 -23
  185. package/dist/src/ide/ide-client.js +372 -78
  186. package/dist/src/ide/ide-client.js.map +1 -1
  187. package/dist/src/ide/ide-client.test.js +375 -30
  188. package/dist/src/ide/ide-client.test.js.map +1 -1
  189. package/dist/src/ide/ide-installer.d.ts +2 -2
  190. package/dist/src/ide/ide-installer.js +37 -24
  191. package/dist/src/ide/ide-installer.js.map +1 -1
  192. package/dist/src/ide/ide-installer.test.js +104 -26
  193. package/dist/src/ide/ide-installer.test.js.map +1 -1
  194. package/dist/src/ide/ideContext.d.ts +35 -365
  195. package/dist/src/ide/ideContext.js +60 -106
  196. package/dist/src/ide/ideContext.js.map +1 -1
  197. package/dist/src/ide/ideContext.test.js +152 -24
  198. package/dist/src/ide/ideContext.test.js.map +1 -1
  199. package/dist/src/ide/process-utils.d.ts +7 -5
  200. package/dist/src/ide/process-utils.js +81 -50
  201. package/dist/src/ide/process-utils.js.map +1 -1
  202. package/dist/src/ide/process-utils.test.d.ts +6 -0
  203. package/dist/src/ide/process-utils.test.js +158 -0
  204. package/dist/src/ide/process-utils.test.js.map +1 -0
  205. package/dist/src/ide/types.d.ts +486 -0
  206. package/dist/src/ide/types.js +138 -0
  207. package/dist/src/ide/types.js.map +1 -0
  208. package/dist/src/index.d.ts +20 -2
  209. package/dist/src/index.js +20 -2
  210. package/dist/src/index.js.map +1 -1
  211. package/dist/src/mcp/google-auth-provider.d.ts +3 -3
  212. package/dist/src/mcp/google-auth-provider.test.js.map +1 -1
  213. package/dist/src/mcp/oauth-provider.d.ts +17 -13
  214. package/dist/src/mcp/oauth-provider.js +81 -69
  215. package/dist/src/mcp/oauth-provider.js.map +1 -1
  216. package/dist/src/mcp/oauth-provider.test.js +212 -37
  217. package/dist/src/mcp/oauth-provider.test.js.map +1 -1
  218. package/dist/src/mcp/oauth-token-storage.d.ts +14 -32
  219. package/dist/src/mcp/oauth-token-storage.js +54 -25
  220. package/dist/src/mcp/oauth-token-storage.js.map +1 -1
  221. package/dist/src/mcp/oauth-token-storage.test.js +256 -162
  222. package/dist/src/mcp/oauth-token-storage.test.js.map +1 -1
  223. package/dist/src/mcp/oauth-utils.d.ts +9 -1
  224. package/dist/src/mcp/oauth-utils.js +42 -27
  225. package/dist/src/mcp/oauth-utils.js.map +1 -1
  226. package/dist/src/mcp/oauth-utils.test.js +41 -1
  227. package/dist/src/mcp/oauth-utils.test.js.map +1 -1
  228. package/dist/src/mcp/sa-impersonation-provider.d.ts +33 -0
  229. package/dist/src/mcp/sa-impersonation-provider.js +130 -0
  230. package/dist/src/mcp/sa-impersonation-provider.js.map +1 -0
  231. package/dist/src/mcp/sa-impersonation-provider.test.d.ts +6 -0
  232. package/dist/src/mcp/sa-impersonation-provider.test.js +117 -0
  233. package/dist/src/mcp/sa-impersonation-provider.test.js.map +1 -0
  234. package/dist/src/mcp/token-storage/base-token-storage.d.ts +19 -0
  235. package/dist/src/mcp/token-storage/base-token-storage.js +36 -0
  236. package/dist/src/mcp/token-storage/base-token-storage.js.map +1 -0
  237. package/dist/src/mcp/token-storage/base-token-storage.test.d.ts +6 -0
  238. package/dist/src/mcp/token-storage/base-token-storage.test.js +160 -0
  239. package/dist/src/mcp/token-storage/base-token-storage.test.js.map +1 -0
  240. package/dist/src/mcp/token-storage/file-token-storage.d.ts +24 -0
  241. package/dist/src/mcp/token-storage/file-token-storage.js +144 -0
  242. package/dist/src/mcp/token-storage/file-token-storage.js.map +1 -0
  243. package/dist/src/mcp/token-storage/file-token-storage.test.d.ts +6 -0
  244. package/dist/src/mcp/token-storage/file-token-storage.test.js +235 -0
  245. package/dist/src/mcp/token-storage/file-token-storage.test.js.map +1 -0
  246. package/dist/src/mcp/token-storage/hybrid-token-storage.d.ts +23 -0
  247. package/dist/src/mcp/token-storage/hybrid-token-storage.js +78 -0
  248. package/dist/src/mcp/token-storage/hybrid-token-storage.js.map +1 -0
  249. package/dist/src/mcp/token-storage/hybrid-token-storage.test.d.ts +6 -0
  250. package/dist/src/mcp/token-storage/hybrid-token-storage.test.js +193 -0
  251. package/dist/src/mcp/token-storage/hybrid-token-storage.test.js.map +1 -0
  252. package/dist/src/mcp/token-storage/index.d.ts +11 -0
  253. package/dist/src/mcp/token-storage/index.js +12 -0
  254. package/dist/src/mcp/token-storage/index.js.map +1 -0
  255. package/dist/src/mcp/token-storage/keychain-token-storage.d.ts +31 -0
  256. package/dist/src/mcp/token-storage/keychain-token-storage.js +190 -0
  257. package/dist/src/mcp/token-storage/keychain-token-storage.js.map +1 -0
  258. package/dist/src/mcp/token-storage/keychain-token-storage.test.d.ts +6 -0
  259. package/dist/src/mcp/token-storage/keychain-token-storage.test.js +254 -0
  260. package/dist/src/mcp/token-storage/keychain-token-storage.test.js.map +1 -0
  261. package/dist/src/mcp/token-storage/types.d.ts +38 -0
  262. package/dist/src/mcp/token-storage/types.js +11 -0
  263. package/dist/src/mcp/token-storage/types.js.map +1 -0
  264. package/dist/src/output/json-formatter.d.ts +11 -0
  265. package/dist/src/output/json-formatter.js +30 -0
  266. package/dist/src/output/json-formatter.js.map +1 -0
  267. package/dist/src/output/json-formatter.test.d.ts +6 -0
  268. package/dist/src/output/json-formatter.test.js +266 -0
  269. package/dist/src/output/json-formatter.test.js.map +1 -0
  270. package/dist/src/output/types.d.ts +20 -0
  271. package/dist/src/output/types.js +11 -0
  272. package/dist/src/output/types.js.map +1 -0
  273. package/dist/src/policy/index.d.ts +7 -0
  274. package/dist/src/policy/index.js +8 -0
  275. package/dist/src/policy/index.js.map +1 -0
  276. package/dist/src/policy/policy-engine.d.ts +30 -0
  277. package/dist/src/policy/policy-engine.js +92 -0
  278. package/dist/src/policy/policy-engine.js.map +1 -0
  279. package/dist/src/policy/policy-engine.test.d.ts +6 -0
  280. package/dist/src/policy/policy-engine.test.js +515 -0
  281. package/dist/src/policy/policy-engine.test.js.map +1 -0
  282. package/dist/src/policy/stable-stringify.d.ts +58 -0
  283. package/dist/src/policy/stable-stringify.js +122 -0
  284. package/dist/src/policy/stable-stringify.js.map +1 -0
  285. package/dist/src/policy/types.d.ts +47 -0
  286. package/dist/src/policy/types.js +12 -0
  287. package/dist/src/policy/types.js.map +1 -0
  288. package/dist/src/prompts/mcp-prompts.d.ts +2 -2
  289. package/dist/src/prompts/prompt-registry.d.ts +1 -1
  290. package/dist/src/routing/modelRouterService.d.ts +23 -0
  291. package/dist/src/routing/modelRouterService.js +70 -0
  292. package/dist/src/routing/modelRouterService.js.map +1 -0
  293. package/dist/src/routing/modelRouterService.test.d.ts +6 -0
  294. package/dist/src/routing/modelRouterService.test.js +98 -0
  295. package/dist/src/routing/modelRouterService.test.js.map +1 -0
  296. package/dist/src/routing/routingStrategy.d.ts +62 -0
  297. package/dist/src/routing/routingStrategy.js +7 -0
  298. package/dist/src/routing/routingStrategy.js.map +1 -0
  299. package/dist/src/routing/strategies/classifierStrategy.d.ts +12 -0
  300. package/dist/src/routing/strategies/classifierStrategy.js +173 -0
  301. package/dist/src/routing/strategies/classifierStrategy.js.map +1 -0
  302. package/dist/src/routing/strategies/classifierStrategy.test.d.ts +6 -0
  303. package/dist/src/routing/strategies/classifierStrategy.test.js +192 -0
  304. package/dist/src/routing/strategies/classifierStrategy.test.js.map +1 -0
  305. package/dist/src/routing/strategies/compositeStrategy.d.ts +26 -0
  306. package/dist/src/routing/strategies/compositeStrategy.js +68 -0
  307. package/dist/src/routing/strategies/compositeStrategy.js.map +1 -0
  308. package/dist/src/routing/strategies/compositeStrategy.test.d.ts +6 -0
  309. package/dist/src/routing/strategies/compositeStrategy.test.js +123 -0
  310. package/dist/src/routing/strategies/compositeStrategy.test.js.map +1 -0
  311. package/dist/src/routing/strategies/defaultStrategy.d.ts +12 -0
  312. package/dist/src/routing/strategies/defaultStrategy.js +20 -0
  313. package/dist/src/routing/strategies/defaultStrategy.js.map +1 -0
  314. package/dist/src/routing/strategies/defaultStrategy.test.d.ts +6 -0
  315. package/dist/src/routing/strategies/defaultStrategy.test.js +26 -0
  316. package/dist/src/routing/strategies/defaultStrategy.test.js.map +1 -0
  317. package/dist/src/routing/strategies/fallbackStrategy.d.ts +12 -0
  318. package/dist/src/routing/strategies/fallbackStrategy.js +25 -0
  319. package/dist/src/routing/strategies/fallbackStrategy.js.map +1 -0
  320. package/dist/src/routing/strategies/fallbackStrategy.test.d.ts +6 -0
  321. package/dist/src/routing/strategies/fallbackStrategy.test.js +55 -0
  322. package/dist/src/routing/strategies/fallbackStrategy.test.js.map +1 -0
  323. package/dist/src/routing/strategies/overrideStrategy.d.ts +15 -0
  324. package/dist/src/routing/strategies/overrideStrategy.js +28 -0
  325. package/dist/src/routing/strategies/overrideStrategy.js.map +1 -0
  326. package/dist/src/routing/strategies/overrideStrategy.test.d.ts +6 -0
  327. package/dist/src/routing/strategies/overrideStrategy.test.js +42 -0
  328. package/dist/src/routing/strategies/overrideStrategy.test.js.map +1 -0
  329. package/dist/src/services/chatRecordingService.d.ts +8 -14
  330. package/dist/src/services/chatRecordingService.js +33 -21
  331. package/dist/src/services/chatRecordingService.js.map +1 -1
  332. package/dist/src/services/chatRecordingService.test.js +69 -25
  333. package/dist/src/services/chatRecordingService.test.js.map +1 -1
  334. package/dist/src/services/fileDiscoveryService.d.ts +10 -0
  335. package/dist/src/services/fileDiscoveryService.js +32 -18
  336. package/dist/src/services/fileDiscoveryService.js.map +1 -1
  337. package/dist/src/services/fileDiscoveryService.test.js +3 -3
  338. package/dist/src/services/fileDiscoveryService.test.js.map +1 -1
  339. package/dist/src/services/fileSystemService.d.ts +9 -0
  340. package/dist/src/services/fileSystemService.js +12 -1
  341. package/dist/src/services/fileSystemService.js.map +1 -1
  342. package/dist/src/services/fileSystemService.test.js +1 -1
  343. package/dist/src/services/fileSystemService.test.js.map +1 -1
  344. package/dist/src/services/gitService.d.ts +3 -1
  345. package/dist/src/services/gitService.js +30 -24
  346. package/dist/src/services/gitService.js.map +1 -1
  347. package/dist/src/services/gitService.test.js +30 -37
  348. package/dist/src/services/gitService.test.js.map +1 -1
  349. package/dist/src/services/loopDetectionService.d.ts +8 -2
  350. package/dist/src/services/loopDetectionService.js +64 -24
  351. package/dist/src/services/loopDetectionService.js.map +1 -1
  352. package/dist/src/services/loopDetectionService.test.js +64 -13
  353. package/dist/src/services/loopDetectionService.test.js.map +1 -1
  354. package/dist/src/services/shellExecutionService.d.ts +36 -2
  355. package/dist/src/services/shellExecutionService.js +238 -47
  356. package/dist/src/services/shellExecutionService.js.map +1 -1
  357. package/dist/src/services/shellExecutionService.test.js +197 -58
  358. package/dist/src/services/shellExecutionService.test.js.map +1 -1
  359. package/dist/src/telemetry/activity-detector.d.ts +41 -0
  360. package/dist/src/telemetry/activity-detector.js +61 -0
  361. package/dist/src/telemetry/activity-detector.js.map +1 -0
  362. package/dist/src/telemetry/activity-detector.test.d.ts +6 -0
  363. package/dist/src/telemetry/activity-detector.test.js +136 -0
  364. package/dist/src/telemetry/activity-detector.test.js.map +1 -0
  365. package/dist/src/telemetry/activity-types.d.ts +19 -0
  366. package/dist/src/telemetry/activity-types.js +21 -0
  367. package/dist/src/telemetry/activity-types.js.map +1 -0
  368. package/dist/src/telemetry/clearcut-logger/clearcut-logger.d.ts +34 -4
  369. package/dist/src/telemetry/clearcut-logger/clearcut-logger.js +322 -15
  370. package/dist/src/telemetry/clearcut-logger/clearcut-logger.js.map +1 -1
  371. package/dist/src/telemetry/clearcut-logger/clearcut-logger.test.d.ts +1 -0
  372. package/dist/src/telemetry/clearcut-logger/clearcut-logger.test.js +321 -11
  373. package/dist/src/telemetry/clearcut-logger/clearcut-logger.test.js.map +1 -1
  374. package/dist/src/telemetry/clearcut-logger/event-metadata-key.d.ts +51 -2
  375. package/dist/src/telemetry/clearcut-logger/event-metadata-key.js +124 -2
  376. package/dist/src/telemetry/clearcut-logger/event-metadata-key.js.map +1 -1
  377. package/dist/src/telemetry/config.d.ts +31 -0
  378. package/dist/src/telemetry/config.js +76 -0
  379. package/dist/src/telemetry/config.js.map +1 -0
  380. package/dist/src/telemetry/config.test.d.ts +6 -0
  381. package/dist/src/telemetry/config.test.js +124 -0
  382. package/dist/src/telemetry/config.test.js.map +1 -0
  383. package/dist/src/telemetry/constants.d.ts +17 -7
  384. package/dist/src/telemetry/constants.js +18 -7
  385. package/dist/src/telemetry/constants.js.map +1 -1
  386. package/dist/src/telemetry/file-exporters.d.ts +5 -4
  387. package/dist/src/telemetry/file-exporters.js +1 -1
  388. package/dist/src/telemetry/file-exporters.js.map +1 -1
  389. package/dist/src/telemetry/gcp-exporters.d.ts +34 -0
  390. package/dist/src/telemetry/gcp-exporters.js +117 -0
  391. package/dist/src/telemetry/gcp-exporters.js.map +1 -0
  392. package/dist/src/telemetry/gcp-exporters.test.d.ts +6 -0
  393. package/dist/src/telemetry/gcp-exporters.test.js +318 -0
  394. package/dist/src/telemetry/gcp-exporters.test.js.map +1 -0
  395. package/dist/src/telemetry/high-water-mark-tracker.d.ts +43 -0
  396. package/dist/src/telemetry/high-water-mark-tracker.js +88 -0
  397. package/dist/src/telemetry/high-water-mark-tracker.js.map +1 -0
  398. package/dist/src/telemetry/high-water-mark-tracker.test.d.ts +6 -0
  399. package/dist/src/telemetry/high-water-mark-tracker.test.js +152 -0
  400. package/dist/src/telemetry/high-water-mark-tracker.test.js.map +1 -0
  401. package/dist/src/telemetry/index.d.ts +12 -2
  402. package/dist/src/telemetry/index.js +16 -2
  403. package/dist/src/telemetry/index.js.map +1 -1
  404. package/dist/src/telemetry/loggers.d.ts +17 -2
  405. package/dist/src/telemetry/loggers.js +316 -14
  406. package/dist/src/telemetry/loggers.js.map +1 -1
  407. package/dist/src/telemetry/loggers.test.circular.js +3 -3
  408. package/dist/src/telemetry/loggers.test.circular.js.map +1 -1
  409. package/dist/src/telemetry/loggers.test.js +452 -48
  410. package/dist/src/telemetry/loggers.test.js.map +1 -1
  411. package/dist/src/telemetry/metrics.d.ts +323 -12
  412. package/dist/src/telemetry/metrics.js +464 -83
  413. package/dist/src/telemetry/metrics.js.map +1 -1
  414. package/dist/src/telemetry/metrics.test.js +583 -38
  415. package/dist/src/telemetry/metrics.test.js.map +1 -1
  416. package/dist/src/telemetry/rate-limiter.d.ts +48 -0
  417. package/dist/src/telemetry/rate-limiter.js +100 -0
  418. package/dist/src/telemetry/rate-limiter.js.map +1 -0
  419. package/dist/src/telemetry/rate-limiter.test.d.ts +6 -0
  420. package/dist/src/telemetry/rate-limiter.test.js +207 -0
  421. package/dist/src/telemetry/rate-limiter.test.js.map +1 -0
  422. package/dist/src/telemetry/sdk.d.ts +1 -1
  423. package/dist/src/telemetry/sdk.js +20 -2
  424. package/dist/src/telemetry/sdk.js.map +1 -1
  425. package/dist/src/telemetry/sdk.test.js +108 -0
  426. package/dist/src/telemetry/sdk.test.js.map +1 -1
  427. package/dist/src/telemetry/telemetry-utils.d.ts +6 -0
  428. package/dist/src/telemetry/telemetry-utils.js +14 -0
  429. package/dist/src/telemetry/telemetry-utils.js.map +1 -0
  430. package/dist/src/telemetry/telemetry-utils.test.d.ts +6 -0
  431. package/dist/src/telemetry/telemetry-utils.test.js +40 -0
  432. package/dist/src/telemetry/telemetry-utils.test.js.map +1 -0
  433. package/dist/src/telemetry/types.d.ts +136 -8
  434. package/dist/src/telemetry/types.js +233 -11
  435. package/dist/src/telemetry/types.js.map +1 -1
  436. package/dist/src/telemetry/uiTelemetry.d.ts +3 -3
  437. package/dist/src/telemetry/uiTelemetry.js +7 -8
  438. package/dist/src/telemetry/uiTelemetry.js.map +1 -1
  439. package/dist/src/telemetry/uiTelemetry.test.js +33 -29
  440. package/dist/src/telemetry/uiTelemetry.test.js.map +1 -1
  441. package/dist/src/test-utils/config.d.ts +2 -1
  442. package/dist/src/test-utils/config.js.map +1 -1
  443. package/dist/src/test-utils/index.d.ts +6 -0
  444. package/dist/src/test-utils/index.js +7 -0
  445. package/dist/src/test-utils/index.js.map +1 -0
  446. package/dist/src/test-utils/mock-tool.d.ts +66 -0
  447. package/dist/src/test-utils/{tools.js → mock-tool.js} +45 -29
  448. package/dist/src/test-utils/mock-tool.js.map +1 -0
  449. package/dist/src/test-utils/mockWorkspaceContext.d.ts +1 -1
  450. package/dist/src/tools/diffOptions.d.ts +1 -1
  451. package/dist/src/tools/diffOptions.js +21 -13
  452. package/dist/src/tools/diffOptions.js.map +1 -1
  453. package/dist/src/tools/diffOptions.test.js +58 -22
  454. package/dist/src/tools/diffOptions.test.js.map +1 -1
  455. package/dist/src/tools/edit.d.ts +6 -5
  456. package/dist/src/tools/edit.js +58 -40
  457. package/dist/src/tools/edit.js.map +1 -1
  458. package/dist/src/tools/edit.test.js +192 -16
  459. package/dist/src/tools/edit.test.js.map +1 -1
  460. package/dist/src/tools/glob.d.ts +7 -2
  461. package/dist/src/tools/glob.js +42 -23
  462. package/dist/src/tools/glob.js.map +1 -1
  463. package/dist/src/tools/glob.test.js +80 -4
  464. package/dist/src/tools/glob.test.js.map +1 -1
  465. package/dist/src/tools/grep.d.ts +3 -2
  466. package/dist/src/tools/grep.js +35 -15
  467. package/dist/src/tools/grep.js.map +1 -1
  468. package/dist/src/tools/grep.test.js +26 -3
  469. package/dist/src/tools/grep.test.js.map +1 -1
  470. package/dist/src/tools/ls.d.ts +3 -2
  471. package/dist/src/tools/ls.js +31 -39
  472. package/dist/src/tools/ls.js.map +1 -1
  473. package/dist/src/tools/ls.test.js +145 -280
  474. package/dist/src/tools/ls.test.js.map +1 -1
  475. package/dist/src/tools/mcp-client-manager.d.ts +8 -6
  476. package/dist/src/tools/mcp-client-manager.js +13 -4
  477. package/dist/src/tools/mcp-client-manager.js.map +1 -1
  478. package/dist/src/tools/mcp-client-manager.test.js +20 -1
  479. package/dist/src/tools/mcp-client-manager.test.js.map +1 -1
  480. package/dist/src/tools/mcp-client.d.ts +18 -21
  481. package/dist/src/tools/mcp-client.js +87 -120
  482. package/dist/src/tools/mcp-client.js.map +1 -1
  483. package/dist/src/tools/mcp-client.test.js +32 -152
  484. package/dist/src/tools/mcp-client.test.js.map +1 -1
  485. package/dist/src/tools/mcp-tool.d.ts +6 -4
  486. package/dist/src/tools/mcp-tool.js +51 -13
  487. package/dist/src/tools/mcp-tool.js.map +1 -1
  488. package/dist/src/tools/mcp-tool.test.js +166 -12
  489. package/dist/src/tools/mcp-tool.test.js.map +1 -1
  490. package/dist/src/tools/memoryTool.d.ts +3 -2
  491. package/dist/src/tools/memoryTool.js +14 -37
  492. package/dist/src/tools/memoryTool.js.map +1 -1
  493. package/dist/src/tools/memoryTool.test.js +16 -4
  494. package/dist/src/tools/memoryTool.test.js.map +1 -1
  495. package/dist/src/tools/message-bus-integration.test.d.ts +6 -0
  496. package/dist/src/tools/message-bus-integration.test.js +183 -0
  497. package/dist/src/tools/message-bus-integration.test.js.map +1 -0
  498. package/dist/src/tools/modifiable-tool.d.ts +2 -2
  499. package/dist/src/tools/modifiable-tool.js +3 -3
  500. package/dist/src/tools/modifiable-tool.js.map +1 -1
  501. package/dist/src/tools/modifiable-tool.test.js +4 -4
  502. package/dist/src/tools/modifiable-tool.test.js.map +1 -1
  503. package/dist/src/tools/read-file.d.ts +3 -2
  504. package/dist/src/tools/read-file.js +33 -43
  505. package/dist/src/tools/read-file.js.map +1 -1
  506. package/dist/src/tools/read-file.test.js +39 -7
  507. package/dist/src/tools/read-file.test.js.map +1 -1
  508. package/dist/src/tools/read-many-files.d.ts +3 -2
  509. package/dist/src/tools/read-many-files.js +52 -107
  510. package/dist/src/tools/read-many-files.js.map +1 -1
  511. package/dist/src/tools/read-many-files.test.js +64 -11
  512. package/dist/src/tools/read-many-files.test.js.map +1 -1
  513. package/dist/src/tools/ripGrep.d.ts +55 -0
  514. package/dist/src/tools/ripGrep.js +393 -0
  515. package/dist/src/tools/ripGrep.js.map +1 -0
  516. package/dist/src/tools/ripGrep.test.d.ts +6 -0
  517. package/dist/src/tools/ripGrep.test.js +976 -0
  518. package/dist/src/tools/ripGrep.test.js.map +1 -0
  519. package/dist/src/tools/shell.d.ts +13 -2
  520. package/dist/src/tools/shell.js +42 -32
  521. package/dist/src/tools/shell.js.map +1 -1
  522. package/dist/src/tools/shell.test.js +57 -75
  523. package/dist/src/tools/shell.test.js.map +1 -1
  524. package/dist/src/tools/smart-edit.d.ts +91 -0
  525. package/dist/src/tools/smart-edit.js +702 -0
  526. package/dist/src/tools/smart-edit.js.map +1 -0
  527. package/dist/src/tools/smart-edit.test.d.ts +6 -0
  528. package/dist/src/tools/smart-edit.test.js +542 -0
  529. package/dist/src/tools/smart-edit.test.js.map +1 -0
  530. package/dist/src/tools/tool-error.d.ts +18 -1
  531. package/dist/src/tools/tool-error.js +27 -0
  532. package/dist/src/tools/tool-error.js.map +1 -1
  533. package/dist/src/tools/tool-registry.d.ts +10 -4
  534. package/dist/src/tools/tool-registry.js +20 -7
  535. package/dist/src/tools/tool-registry.js.map +1 -1
  536. package/dist/src/tools/tool-registry.test.js +93 -10
  537. package/dist/src/tools/tool-registry.test.js.map +1 -1
  538. package/dist/src/tools/tools.d.ts +33 -16
  539. package/dist/src/tools/tools.js +115 -5
  540. package/dist/src/tools/tools.js.map +1 -1
  541. package/dist/src/tools/tools.test.js +1 -2
  542. package/dist/src/tools/tools.test.js.map +1 -1
  543. package/dist/src/tools/web-fetch.d.ts +3 -2
  544. package/dist/src/tools/web-fetch.js +14 -10
  545. package/dist/src/tools/web-fetch.js.map +1 -1
  546. package/dist/src/tools/web-fetch.test.js +55 -16
  547. package/dist/src/tools/web-fetch.test.js.map +1 -1
  548. package/dist/src/tools/web-search.d.ts +4 -3
  549. package/dist/src/tools/web-search.js +31 -8
  550. package/dist/src/tools/web-search.js.map +1 -1
  551. package/dist/src/tools/web-search.test.js +69 -1
  552. package/dist/src/tools/web-search.test.js.map +1 -1
  553. package/dist/src/tools/write-file.d.ts +4 -3
  554. package/dist/src/tools/write-file.js +17 -18
  555. package/dist/src/tools/write-file.js.map +1 -1
  556. package/dist/src/tools/write-file.test.js +108 -24
  557. package/dist/src/tools/write-file.test.js.map +1 -1
  558. package/dist/src/tools/write-todos.d.ts +25 -0
  559. package/dist/src/tools/write-todos.js +150 -0
  560. package/dist/src/tools/write-todos.js.map +1 -0
  561. package/dist/src/tools/write-todos.test.d.ts +6 -0
  562. package/dist/src/tools/write-todos.test.js +89 -0
  563. package/dist/src/tools/write-todos.test.js.map +1 -0
  564. package/dist/src/utils/bfsFileSearch.d.ts +2 -2
  565. package/dist/src/utils/bfsFileSearch.js +13 -7
  566. package/dist/src/utils/bfsFileSearch.js.map +1 -1
  567. package/dist/src/utils/bfsFileSearch.test.js +3 -3
  568. package/dist/src/utils/bfsFileSearch.test.js.map +1 -1
  569. package/dist/src/utils/editCorrector.d.ts +9 -8
  570. package/dist/src/utils/editCorrector.js +62 -19
  571. package/dist/src/utils/editCorrector.js.map +1 -1
  572. package/dist/src/utils/editCorrector.test.js +33 -82
  573. package/dist/src/utils/editCorrector.test.js.map +1 -1
  574. package/dist/src/utils/editor.js +32 -45
  575. package/dist/src/utils/editor.js.map +1 -1
  576. package/dist/src/utils/editor.test.js +62 -76
  577. package/dist/src/utils/editor.test.js.map +1 -1
  578. package/dist/src/utils/environmentContext.d.ts +2 -2
  579. package/dist/src/utils/errorParsing.js +2 -2
  580. package/dist/src/utils/errorParsing.js.map +1 -1
  581. package/dist/src/utils/errorParsing.test.js +7 -7
  582. package/dist/src/utils/errorParsing.test.js.map +1 -1
  583. package/dist/src/utils/errorReporting.d.ts +1 -1
  584. package/dist/src/utils/errors.d.ts +25 -0
  585. package/dist/src/utils/errors.js +42 -0
  586. package/dist/src/utils/errors.js.map +1 -1
  587. package/dist/src/utils/fetch.js +1 -1
  588. package/dist/src/utils/fetch.js.map +1 -1
  589. package/dist/src/utils/fileUtils.d.ts +24 -12
  590. package/dist/src/utils/fileUtils.js +170 -79
  591. package/dist/src/utils/fileUtils.js.map +1 -1
  592. package/dist/src/utils/fileUtils.test.js +347 -29
  593. package/dist/src/utils/fileUtils.test.js.map +1 -1
  594. package/dist/src/utils/filesearch/crawler.d.ts +1 -1
  595. package/dist/src/utils/filesearch/crawler.test.js +2 -2
  596. package/dist/src/utils/filesearch/crawler.test.js.map +1 -1
  597. package/dist/src/utils/filesearch/fileSearch.d.ts +1 -0
  598. package/dist/src/utils/filesearch/fileSearch.js +14 -9
  599. package/dist/src/utils/filesearch/fileSearch.js.map +1 -1
  600. package/dist/src/utils/filesearch/fileSearch.test.js +90 -0
  601. package/dist/src/utils/filesearch/fileSearch.test.js.map +1 -1
  602. package/dist/src/utils/flashFallback.test.d.ts +6 -0
  603. package/dist/src/utils/{flashFallback.integration.test.js → flashFallback.test.js} +33 -29
  604. package/dist/src/utils/flashFallback.test.js.map +1 -0
  605. package/dist/src/utils/geminiIgnoreParser.d.ts +18 -0
  606. package/dist/src/utils/geminiIgnoreParser.js +61 -0
  607. package/dist/src/utils/geminiIgnoreParser.js.map +1 -0
  608. package/dist/src/utils/geminiIgnoreParser.test.d.ts +6 -0
  609. package/dist/src/utils/geminiIgnoreParser.test.js +50 -0
  610. package/dist/src/utils/geminiIgnoreParser.test.js.map +1 -0
  611. package/dist/src/utils/generateContentResponseUtilities.d.ts +1 -2
  612. package/dist/src/utils/generateContentResponseUtilities.js +1 -13
  613. package/dist/src/utils/generateContentResponseUtilities.js.map +1 -1
  614. package/dist/src/utils/generateContentResponseUtilities.test.js +2 -40
  615. package/dist/src/utils/generateContentResponseUtilities.test.js.map +1 -1
  616. package/dist/src/utils/getFolderStructure.d.ts +2 -2
  617. package/dist/src/utils/getFolderStructure.js +3 -3
  618. package/dist/src/utils/getFolderStructure.js.map +1 -1
  619. package/dist/src/utils/getFolderStructure.test.js +4 -4
  620. package/dist/src/utils/getFolderStructure.test.js.map +1 -1
  621. package/dist/src/utils/gitIgnoreParser.d.ts +3 -7
  622. package/dist/src/utils/gitIgnoreParser.js +126 -35
  623. package/dist/src/utils/gitIgnoreParser.js.map +1 -1
  624. package/dist/src/utils/gitIgnoreParser.test.js +69 -38
  625. package/dist/src/utils/gitIgnoreParser.test.js.map +1 -1
  626. package/dist/src/utils/gitUtils.js +2 -2
  627. package/dist/src/utils/gitUtils.js.map +1 -1
  628. package/dist/src/utils/ignorePatterns.d.ts +103 -0
  629. package/dist/src/utils/ignorePatterns.js +220 -0
  630. package/dist/src/utils/ignorePatterns.js.map +1 -0
  631. package/dist/src/utils/ignorePatterns.test.d.ts +6 -0
  632. package/dist/src/utils/ignorePatterns.test.js +250 -0
  633. package/dist/src/utils/ignorePatterns.test.js.map +1 -0
  634. package/dist/src/utils/installationManager.d.ts +16 -0
  635. package/dist/src/utils/installationManager.js +50 -0
  636. package/dist/src/utils/installationManager.js.map +1 -0
  637. package/dist/src/utils/installationManager.test.d.ts +6 -0
  638. package/dist/src/utils/installationManager.test.js +83 -0
  639. package/dist/src/utils/installationManager.test.js.map +1 -0
  640. package/dist/src/utils/language-detection.d.ts +6 -0
  641. package/dist/src/utils/language-detection.js +101 -0
  642. package/dist/src/utils/language-detection.js.map +1 -0
  643. package/dist/src/utils/llm-edit-fixer.d.ts +26 -0
  644. package/dist/src/utils/llm-edit-fixer.js +131 -0
  645. package/dist/src/utils/llm-edit-fixer.js.map +1 -0
  646. package/dist/src/utils/llm-edit-fixer.test.d.ts +6 -0
  647. package/dist/src/utils/llm-edit-fixer.test.js +186 -0
  648. package/dist/src/utils/llm-edit-fixer.test.js.map +1 -0
  649. package/dist/src/utils/memoryDiscovery.d.ts +7 -6
  650. package/dist/src/utils/memoryDiscovery.js +68 -33
  651. package/dist/src/utils/memoryDiscovery.js.map +1 -1
  652. package/dist/src/utils/memoryDiscovery.test.js +88 -26
  653. package/dist/src/utils/memoryDiscovery.test.js.map +1 -1
  654. package/dist/src/utils/memoryImportProcessor.js +15 -22
  655. package/dist/src/utils/memoryImportProcessor.js.map +1 -1
  656. package/dist/src/utils/memoryImportProcessor.test.js +16 -141
  657. package/dist/src/utils/memoryImportProcessor.test.js.map +1 -1
  658. package/dist/src/utils/messageInspectors.d.ts +1 -1
  659. package/dist/src/utils/nextSpeakerChecker.d.ts +3 -3
  660. package/dist/src/utils/nextSpeakerChecker.js +8 -2
  661. package/dist/src/utils/nextSpeakerChecker.js.map +1 -1
  662. package/dist/src/utils/nextSpeakerChecker.test.js +75 -64
  663. package/dist/src/utils/nextSpeakerChecker.test.js.map +1 -1
  664. package/dist/src/utils/partUtils.d.ts +22 -1
  665. package/dist/src/utils/partUtils.js +68 -0
  666. package/dist/src/utils/partUtils.js.map +1 -1
  667. package/dist/src/utils/partUtils.test.js +112 -1
  668. package/dist/src/utils/partUtils.test.js.map +1 -1
  669. package/dist/src/utils/pathReader.d.ts +17 -0
  670. package/dist/src/utils/pathReader.js +92 -0
  671. package/dist/src/utils/pathReader.js.map +1 -0
  672. package/dist/src/utils/pathReader.test.d.ts +6 -0
  673. package/dist/src/utils/pathReader.test.js +363 -0
  674. package/dist/src/utils/pathReader.test.js.map +1 -0
  675. package/dist/src/utils/paths.d.ts +0 -17
  676. package/dist/src/utils/paths.js +2 -28
  677. package/dist/src/utils/paths.js.map +1 -1
  678. package/dist/src/utils/promptIdContext.d.ts +7 -0
  679. package/dist/src/utils/promptIdContext.js +8 -0
  680. package/dist/src/utils/promptIdContext.js.map +1 -0
  681. package/dist/src/utils/quotaErrorDetection.d.ts +1 -1
  682. package/dist/src/utils/retry.d.ts +3 -1
  683. package/dist/src/utils/retry.js +60 -5
  684. package/dist/src/utils/retry.js.map +1 -1
  685. package/dist/src/utils/retry.test.js +35 -3
  686. package/dist/src/utils/retry.test.js.map +1 -1
  687. package/dist/src/utils/schemaValidator.js +15 -1
  688. package/dist/src/utils/schemaValidator.js.map +1 -1
  689. package/dist/src/utils/schemaValidator.test.d.ts +6 -0
  690. package/dist/src/utils/schemaValidator.test.js +113 -0
  691. package/dist/src/utils/schemaValidator.test.js.map +1 -0
  692. package/dist/src/utils/session.js +1 -1
  693. package/dist/src/utils/session.js.map +1 -1
  694. package/dist/src/utils/shell-utils.d.ts +6 -1
  695. package/dist/src/utils/shell-utils.js +51 -30
  696. package/dist/src/utils/shell-utils.js.map +1 -1
  697. package/dist/src/utils/shell-utils.test.js +9 -0
  698. package/dist/src/utils/shell-utils.test.js.map +1 -1
  699. package/dist/src/utils/summarizer.d.ts +2 -2
  700. package/dist/src/utils/summarizer.test.js.map +1 -1
  701. package/dist/src/utils/systemEncoding.js +2 -2
  702. package/dist/src/utils/systemEncoding.js.map +1 -1
  703. package/dist/src/utils/systemEncoding.test.js +2 -2
  704. package/dist/src/utils/systemEncoding.test.js.map +1 -1
  705. package/dist/src/utils/terminalSerializer.d.ts +25 -0
  706. package/dist/src/utils/terminalSerializer.js +432 -0
  707. package/dist/src/utils/terminalSerializer.js.map +1 -0
  708. package/dist/src/utils/terminalSerializer.test.d.ts +6 -0
  709. package/dist/src/utils/terminalSerializer.test.js +176 -0
  710. package/dist/src/utils/terminalSerializer.test.js.map +1 -0
  711. package/dist/src/utils/textUtils.d.ts +5 -0
  712. package/dist/src/utils/textUtils.js +14 -0
  713. package/dist/src/utils/textUtils.js.map +1 -1
  714. package/dist/src/utils/textUtils.test.d.ts +6 -0
  715. package/dist/src/utils/textUtils.test.js +59 -0
  716. package/dist/src/utils/textUtils.test.js.map +1 -0
  717. package/dist/src/utils/thoughtUtils.d.ts +21 -0
  718. package/dist/src/utils/thoughtUtils.js +39 -0
  719. package/dist/src/utils/thoughtUtils.js.map +1 -0
  720. package/dist/src/utils/thoughtUtils.test.d.ts +6 -0
  721. package/dist/src/utils/thoughtUtils.test.js +78 -0
  722. package/dist/src/utils/thoughtUtils.test.js.map +1 -0
  723. package/dist/src/utils/tool-utils.d.ts +19 -0
  724. package/dist/src/utils/tool-utils.js +58 -0
  725. package/dist/src/utils/tool-utils.js.map +1 -0
  726. package/dist/src/utils/tool-utils.test.d.ts +6 -0
  727. package/dist/src/utils/tool-utils.test.js +61 -0
  728. package/dist/src/utils/tool-utils.test.js.map +1 -0
  729. package/dist/src/utils/userAccountManager.d.ts +20 -0
  730. package/dist/src/utils/userAccountManager.js +114 -0
  731. package/dist/src/utils/userAccountManager.js.map +1 -0
  732. package/dist/src/utils/userAccountManager.test.d.ts +6 -0
  733. package/dist/src/utils/{user_account.test.js → userAccountManager.test.js} +33 -30
  734. package/dist/src/utils/userAccountManager.test.js.map +1 -0
  735. package/dist/src/utils/workspaceContext.js +13 -7
  736. package/dist/src/utils/workspaceContext.js.map +1 -1
  737. package/dist/src/utils/workspaceContext.test.js +41 -16
  738. package/dist/src/utils/workspaceContext.test.js.map +1 -1
  739. package/dist/tsconfig.tsbuildinfo +1 -1
  740. package/package.json +18 -9
  741. package/dist/src/core/modelCheck.d.ts +0 -14
  742. package/dist/src/core/modelCheck.js +0 -62
  743. package/dist/src/core/modelCheck.js.map +0 -1
  744. package/dist/src/test-utils/tools.d.ts +0 -44
  745. package/dist/src/test-utils/tools.js.map +0 -1
  746. package/dist/src/utils/flashFallback.integration.test.js.map +0 -1
  747. package/dist/src/utils/user_account.d.ts +0 -9
  748. package/dist/src/utils/user_account.js +0 -109
  749. package/dist/src/utils/user_account.js.map +0 -1
  750. package/dist/src/utils/user_account.test.js.map +0 -1
  751. package/dist/src/utils/user_id.d.ts +0 -11
  752. package/dist/src/utils/user_id.js +0 -49
  753. package/dist/src/utils/user_id.js.map +0 -1
  754. package/dist/src/utils/user_id.test.js +0 -21
  755. package/dist/src/utils/user_id.test.js.map +0 -1
  756. /package/dist/src/{utils/flashFallback.integration.test.d.ts → agents/executor.test.d.ts} +0 -0
  757. /package/dist/src/{utils/user_account.test.d.ts → agents/invocation.test.d.ts} +0 -0
  758. /package/dist/src/{utils/user_id.test.d.ts → agents/registry.test.d.ts} +0 -0
@@ -5,16 +5,17 @@
5
5
  */
6
6
  import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
7
7
  import { getOauthClient, resetOauthClientForTesting, clearCachedCredentialFile, clearOauthClientCache, } from './oauth2.js';
8
- import { getCachedGoogleAccount } from '../utils/user_account.js';
8
+ import { UserAccountManager } from '../utils/userAccountManager.js';
9
9
  import { OAuth2Client, Compute } from 'google-auth-library';
10
- import * as fs from 'fs';
11
- import * as path from 'path';
12
- import http from 'http';
10
+ import * as fs from 'node:fs';
11
+ import * as path from 'node:path';
12
+ import http from 'node:http';
13
13
  import open from 'open';
14
- import crypto from 'crypto';
15
- import * as os from 'os';
14
+ import crypto from 'node:crypto';
15
+ import * as os from 'node:os';
16
16
  import { AuthType } from '../core/contentGenerator.js';
17
17
  import readline from 'node:readline';
18
+ import { FORCE_ENCRYPTED_FILE_ENV_VAR } from '../mcp/token-storage/index.js';
18
19
  vi.mock('os', async (importOriginal) => {
19
20
  const os = await importOriginal();
20
21
  return {
@@ -30,6 +31,13 @@ vi.mock('node:readline');
30
31
  vi.mock('../utils/browser.js', () => ({
31
32
  shouldAttemptBrowserLaunch: () => true,
32
33
  }));
34
+ vi.mock('./oauth-credential-storage.js', () => ({
35
+ OAuthCredentialStorage: {
36
+ saveCredentials: vi.fn(),
37
+ loadCredentials: vi.fn(),
38
+ clearCredentials: vi.fn(),
39
+ },
40
+ }));
33
41
  const mockConfig = {
34
42
  getNoBrowser: () => false,
35
43
  getProxy: () => 'http://test.proxy.com:8080',
@@ -38,387 +46,771 @@ const mockConfig = {
38
46
  // Mock fetch globally
39
47
  global.fetch = vi.fn();
40
48
  describe('oauth2', () => {
41
- let tempHomeDir;
42
- beforeEach(() => {
43
- tempHomeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gemini-cli-test-home-'));
44
- os.homedir.mockReturnValue(tempHomeDir);
45
- });
46
- afterEach(() => {
47
- fs.rmSync(tempHomeDir, { recursive: true, force: true });
48
- vi.clearAllMocks();
49
- resetOauthClientForTesting();
50
- vi.unstubAllEnvs();
51
- });
52
- it('should perform a web login', async () => {
53
- const mockAuthUrl = 'https://example.com/auth';
54
- const mockCode = 'test-code';
55
- const mockState = 'test-state';
56
- const mockTokens = {
57
- access_token: 'test-access-token',
58
- refresh_token: 'test-refresh-token',
59
- };
60
- const mockGenerateAuthUrl = vi.fn().mockReturnValue(mockAuthUrl);
61
- const mockGetToken = vi.fn().mockResolvedValue({ tokens: mockTokens });
62
- const mockSetCredentials = vi.fn();
63
- const mockGetAccessToken = vi
64
- .fn()
65
- .mockResolvedValue({ token: 'mock-access-token' });
66
- const mockOAuth2Client = {
67
- generateAuthUrl: mockGenerateAuthUrl,
68
- getToken: mockGetToken,
69
- setCredentials: mockSetCredentials,
70
- getAccessToken: mockGetAccessToken,
71
- credentials: mockTokens,
72
- on: vi.fn(),
73
- };
74
- OAuth2Client.mockImplementation(() => mockOAuth2Client);
75
- vi.spyOn(crypto, 'randomBytes').mockReturnValue(mockState);
76
- open.mockImplementation(async () => ({ on: vi.fn() }));
77
- // Mock the UserInfo API response
78
- global.fetch.mockResolvedValue({
79
- ok: true,
80
- json: vi
81
- .fn()
82
- .mockResolvedValue({ email: 'test-google-account@gmail.com' }),
83
- });
84
- let requestCallback;
85
- let serverListeningCallback;
86
- const serverListeningPromise = new Promise((resolve) => (serverListeningCallback = resolve));
87
- let capturedPort = 0;
88
- const mockHttpServer = {
89
- listen: vi.fn((port, _host, callback) => {
90
- capturedPort = port;
91
- if (callback) {
92
- callback();
93
- }
94
- serverListeningCallback(undefined);
95
- }),
96
- close: vi.fn((callback) => {
97
- if (callback) {
98
- callback();
99
- }
100
- }),
101
- on: vi.fn(),
102
- address: () => ({ port: capturedPort }),
103
- };
104
- http.createServer.mockImplementation((cb) => {
105
- requestCallback = cb;
106
- return mockHttpServer;
107
- });
108
- const clientPromise = getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
109
- // wait for server to start listening.
110
- await serverListeningPromise;
111
- const mockReq = {
112
- url: `/oauth2callback?code=${mockCode}&state=${mockState}`,
113
- };
114
- const mockRes = {
115
- writeHead: vi.fn(),
116
- end: vi.fn(),
117
- };
118
- await requestCallback(mockReq, mockRes);
119
- const client = await clientPromise;
120
- expect(client).toBe(mockOAuth2Client);
121
- expect(open).toHaveBeenCalledWith(mockAuthUrl);
122
- expect(mockGetToken).toHaveBeenCalledWith({
123
- code: mockCode,
124
- redirect_uri: `http://localhost:${capturedPort}/oauth2callback`,
125
- });
126
- expect(mockSetCredentials).toHaveBeenCalledWith(mockTokens);
127
- // Verify Google Account was cached
128
- const googleAccountPath = path.join(tempHomeDir, '.gemini', 'google_accounts.json');
129
- expect(fs.existsSync(googleAccountPath)).toBe(true);
130
- const cachedGoogleAccount = fs.readFileSync(googleAccountPath, 'utf-8');
131
- expect(JSON.parse(cachedGoogleAccount)).toEqual({
132
- active: 'test-google-account@gmail.com',
133
- old: [],
134
- });
135
- // Verify the getCachedGoogleAccount function works
136
- expect(getCachedGoogleAccount()).toBe('test-google-account@gmail.com');
137
- });
138
- it('should perform login with user code', async () => {
139
- const mockConfigWithNoBrowser = {
140
- getNoBrowser: () => true,
141
- getProxy: () => 'http://test.proxy.com:8080',
142
- isBrowserLaunchSuppressed: () => true,
143
- };
144
- const mockCodeVerifier = {
145
- codeChallenge: 'test-challenge',
146
- codeVerifier: 'test-verifier',
147
- };
148
- const mockAuthUrl = 'https://example.com/auth-user-code';
149
- const mockCode = 'test-user-code';
150
- const mockTokens = {
151
- access_token: 'test-access-token-user-code',
152
- refresh_token: 'test-refresh-token-user-code',
153
- };
154
- const mockGenerateAuthUrl = vi.fn().mockReturnValue(mockAuthUrl);
155
- const mockGetToken = vi.fn().mockResolvedValue({ tokens: mockTokens });
156
- const mockSetCredentials = vi.fn();
157
- const mockGenerateCodeVerifierAsync = vi
158
- .fn()
159
- .mockResolvedValue(mockCodeVerifier);
160
- const mockOAuth2Client = {
161
- generateAuthUrl: mockGenerateAuthUrl,
162
- getToken: mockGetToken,
163
- setCredentials: mockSetCredentials,
164
- generateCodeVerifierAsync: mockGenerateCodeVerifierAsync,
165
- on: vi.fn(),
166
- };
167
- OAuth2Client.mockImplementation(() => mockOAuth2Client);
168
- const mockReadline = {
169
- question: vi.fn((_query, callback) => callback(mockCode)),
170
- close: vi.fn(),
171
- };
172
- readline.createInterface.mockReturnValue(mockReadline);
173
- const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => { });
174
- const client = await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfigWithNoBrowser);
175
- expect(client).toBe(mockOAuth2Client);
176
- // Verify the auth flow
177
- expect(mockGenerateCodeVerifierAsync).toHaveBeenCalled();
178
- expect(mockGenerateAuthUrl).toHaveBeenCalled();
179
- expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining(mockAuthUrl));
180
- expect(mockReadline.question).toHaveBeenCalledWith('Enter the authorization code: ', expect.any(Function));
181
- expect(mockGetToken).toHaveBeenCalledWith({
182
- code: mockCode,
183
- codeVerifier: mockCodeVerifier.codeVerifier,
184
- redirect_uri: 'https://codeassist.google.com/authcode',
185
- });
186
- expect(mockSetCredentials).toHaveBeenCalledWith(mockTokens);
187
- consoleLogSpy.mockRestore();
188
- });
189
- describe('in Cloud Shell', () => {
190
- const mockGetAccessToken = vi.fn();
191
- let mockComputeClient;
49
+ describe('with encrypted flag false', () => {
50
+ let tempHomeDir;
192
51
  beforeEach(() => {
193
- mockGetAccessToken.mockResolvedValue({ token: 'test-access-token' });
194
- mockComputeClient = {
195
- credentials: { refresh_token: 'test-refresh-token' },
196
- getAccessToken: mockGetAccessToken,
197
- };
198
- Compute.mockImplementation(() => mockComputeClient);
52
+ process.env[FORCE_ENCRYPTED_FILE_ENV_VAR] = 'false';
53
+ tempHomeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gemini-cli-test-home-'));
54
+ os.homedir.mockReturnValue(tempHomeDir);
199
55
  });
200
- it('should attempt to load cached credentials first', async () => {
201
- const cachedCreds = { refresh_token: 'cached-token' };
202
- const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
203
- await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
204
- await fs.promises.writeFile(credsPath, JSON.stringify(cachedCreds));
205
- const mockClient = {
206
- setCredentials: vi.fn(),
207
- getAccessToken: vi.fn().mockResolvedValue({ token: 'test-token' }),
208
- getTokenInfo: vi.fn().mockResolvedValue({}),
209
- on: vi.fn(),
210
- };
211
- // To mock the new OAuth2Client() inside the function
212
- OAuth2Client.mockImplementation(() => mockClient);
213
- await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
214
- expect(mockClient.setCredentials).toHaveBeenCalledWith(cachedCreds);
215
- expect(mockClient.getAccessToken).toHaveBeenCalled();
216
- expect(mockClient.getTokenInfo).toHaveBeenCalled();
217
- expect(Compute).not.toHaveBeenCalled(); // Should not fetch new client if cache is valid
218
- });
219
- it('should use Compute to get a client if no cached credentials exist', async () => {
220
- await getOauthClient(AuthType.CLOUD_SHELL, mockConfig);
221
- expect(Compute).toHaveBeenCalledWith({});
222
- expect(mockGetAccessToken).toHaveBeenCalled();
223
- });
224
- it('should not cache the credentials after fetching them via ADC', async () => {
225
- const newCredentials = { refresh_token: 'new-adc-token' };
226
- mockComputeClient.credentials = newCredentials;
227
- mockGetAccessToken.mockResolvedValue({ token: 'new-adc-token' });
228
- await getOauthClient(AuthType.CLOUD_SHELL, mockConfig);
229
- const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
230
- expect(fs.existsSync(credsPath)).toBe(false);
56
+ afterEach(() => {
57
+ fs.rmSync(tempHomeDir, { recursive: true, force: true });
58
+ vi.clearAllMocks();
59
+ resetOauthClientForTesting();
60
+ vi.unstubAllEnvs();
231
61
  });
232
- it('should return the Compute client on successful ADC authentication', async () => {
233
- const client = await getOauthClient(AuthType.CLOUD_SHELL, mockConfig);
234
- expect(client).toBe(mockComputeClient);
235
- });
236
- it('should throw an error if ADC fails', async () => {
237
- const testError = new Error('ADC Failed');
238
- mockGetAccessToken.mockRejectedValue(testError);
239
- await expect(getOauthClient(AuthType.CLOUD_SHELL, mockConfig)).rejects.toThrow('Could not authenticate using Cloud Shell credentials. Please select a different authentication method or ensure you are in a properly configured environment. Error: ADC Failed');
240
- });
241
- });
242
- describe('credential loading order', () => {
243
- it('should prioritize default cached credentials over GOOGLE_APPLICATION_CREDENTIALS', async () => {
244
- // Setup default cached credentials
245
- const defaultCreds = { refresh_token: 'default-cached-token' };
246
- const defaultCredsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
247
- await fs.promises.mkdir(path.dirname(defaultCredsPath), {
248
- recursive: true,
249
- });
250
- await fs.promises.writeFile(defaultCredsPath, JSON.stringify(defaultCreds));
251
- // Setup credentials via environment variable
252
- const envCreds = { refresh_token: 'env-var-token' };
253
- const envCredsPath = path.join(tempHomeDir, 'env_creds.json');
254
- await fs.promises.writeFile(envCredsPath, JSON.stringify(envCreds));
255
- vi.stubEnv('GOOGLE_APPLICATION_CREDENTIALS', envCredsPath);
256
- const mockClient = {
257
- setCredentials: vi.fn(),
258
- getAccessToken: vi.fn().mockResolvedValue({ token: 'test-token' }),
259
- getTokenInfo: vi.fn().mockResolvedValue({}),
260
- on: vi.fn(),
62
+ it('should perform a web login', async () => {
63
+ const mockAuthUrl = 'https://example.com/auth';
64
+ const mockCode = 'test-code';
65
+ const mockState = 'test-state';
66
+ const mockTokens = {
67
+ access_token: 'test-access-token',
68
+ refresh_token: 'test-refresh-token',
261
69
  };
262
- OAuth2Client.mockImplementation(() => mockClient);
263
- await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
264
- // Assert the correct credentials were used
265
- expect(mockClient.setCredentials).toHaveBeenCalledWith(defaultCreds);
266
- expect(mockClient.setCredentials).not.toHaveBeenCalledWith(envCreds);
267
- });
268
- it('should fall back to GOOGLE_APPLICATION_CREDENTIALS if default cache is missing', async () => {
269
- // Setup credentials via environment variable
270
- const envCreds = { refresh_token: 'env-var-token' };
271
- const envCredsPath = path.join(tempHomeDir, 'env_creds.json');
272
- await fs.promises.writeFile(envCredsPath, JSON.stringify(envCreds));
273
- vi.stubEnv('GOOGLE_APPLICATION_CREDENTIALS', envCredsPath);
274
- const mockClient = {
275
- setCredentials: vi.fn(),
276
- getAccessToken: vi.fn().mockResolvedValue({ token: 'test-token' }),
277
- getTokenInfo: vi.fn().mockResolvedValue({}),
278
- on: vi.fn(),
279
- };
280
- OAuth2Client.mockImplementation(() => mockClient);
281
- await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
282
- // Assert the correct credentials were used
283
- expect(mockClient.setCredentials).toHaveBeenCalledWith(envCreds);
284
- });
285
- });
286
- describe('with GCP environment variables', () => {
287
- it('should use GOOGLE_CLOUD_ACCESS_TOKEN when GOOGLE_GENAI_USE_GCA is true', async () => {
288
- vi.stubEnv('GOOGLE_GENAI_USE_GCA', 'true');
289
- vi.stubEnv('GOOGLE_CLOUD_ACCESS_TOKEN', 'gcp-access-token');
70
+ const mockGenerateAuthUrl = vi.fn().mockReturnValue(mockAuthUrl);
71
+ const mockGetToken = vi.fn().mockResolvedValue({ tokens: mockTokens });
290
72
  const mockSetCredentials = vi.fn();
291
73
  const mockGetAccessToken = vi
292
74
  .fn()
293
- .mockResolvedValue({ token: 'gcp-access-token' });
75
+ .mockResolvedValue({ token: 'mock-access-token' });
294
76
  const mockOAuth2Client = {
77
+ generateAuthUrl: mockGenerateAuthUrl,
78
+ getToken: mockGetToken,
295
79
  setCredentials: mockSetCredentials,
296
80
  getAccessToken: mockGetAccessToken,
81
+ credentials: mockTokens,
297
82
  on: vi.fn(),
298
83
  };
299
84
  OAuth2Client.mockImplementation(() => mockOAuth2Client);
300
- // Mock the UserInfo API response for fetchAndCacheUserInfo
85
+ vi.spyOn(crypto, 'randomBytes').mockReturnValue(mockState);
86
+ open.mockImplementation(async () => ({ on: vi.fn() }));
87
+ // Mock the UserInfo API response
301
88
  global.fetch.mockResolvedValue({
302
89
  ok: true,
303
90
  json: vi
304
91
  .fn()
305
- .mockResolvedValue({ email: 'test-gcp-account@gmail.com' }),
92
+ .mockResolvedValue({ email: 'test-google-account@gmail.com' }),
306
93
  });
307
- const client = await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
308
- expect(client).toBe(mockOAuth2Client);
309
- expect(mockSetCredentials).toHaveBeenCalledWith({
310
- access_token: 'gcp-access-token',
94
+ let requestCallback;
95
+ let serverListeningCallback;
96
+ const serverListeningPromise = new Promise((resolve) => (serverListeningCallback = resolve));
97
+ let capturedPort = 0;
98
+ const mockHttpServer = {
99
+ listen: vi.fn((port, _host, callback) => {
100
+ capturedPort = port;
101
+ if (callback) {
102
+ callback();
103
+ }
104
+ serverListeningCallback(undefined);
105
+ }),
106
+ close: vi.fn((callback) => {
107
+ if (callback) {
108
+ callback();
109
+ }
110
+ }),
111
+ on: vi.fn(),
112
+ address: () => ({ port: capturedPort }),
113
+ };
114
+ http.createServer.mockImplementation((cb) => {
115
+ requestCallback = cb;
116
+ return mockHttpServer;
311
117
  });
312
- // Verify fetchAndCacheUserInfo was effectively called
313
- expect(mockGetAccessToken).toHaveBeenCalled();
314
- expect(global.fetch).toHaveBeenCalledWith('https://www.googleapis.com/oauth2/v2/userinfo', {
315
- headers: {
316
- Authorization: 'Bearer gcp-access-token',
317
- },
118
+ const clientPromise = getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
119
+ // wait for server to start listening.
120
+ await serverListeningPromise;
121
+ const mockReq = {
122
+ url: `/oauth2callback?code=${mockCode}&state=${mockState}`,
123
+ };
124
+ const mockRes = {
125
+ writeHead: vi.fn(),
126
+ end: vi.fn(),
127
+ };
128
+ await requestCallback(mockReq, mockRes);
129
+ const client = await clientPromise;
130
+ expect(client).toBe(mockOAuth2Client);
131
+ expect(open).toHaveBeenCalledWith(mockAuthUrl);
132
+ expect(mockGetToken).toHaveBeenCalledWith({
133
+ code: mockCode,
134
+ redirect_uri: `http://localhost:${capturedPort}/oauth2callback`,
318
135
  });
136
+ expect(mockSetCredentials).toHaveBeenCalledWith(mockTokens);
319
137
  // Verify Google Account was cached
320
138
  const googleAccountPath = path.join(tempHomeDir, '.gemini', 'google_accounts.json');
321
- const cachedContent = fs.readFileSync(googleAccountPath, 'utf-8');
322
- expect(JSON.parse(cachedContent)).toEqual({
323
- active: 'test-gcp-account@gmail.com',
139
+ expect(fs.existsSync(googleAccountPath)).toBe(true);
140
+ const cachedGoogleAccount = fs.readFileSync(googleAccountPath, 'utf-8');
141
+ expect(JSON.parse(cachedGoogleAccount)).toEqual({
142
+ active: 'test-google-account@gmail.com',
324
143
  old: [],
325
144
  });
145
+ // Verify the getCachedGoogleAccount function works
146
+ const userAccountManager = new UserAccountManager();
147
+ expect(userAccountManager.getCachedGoogleAccount()).toBe('test-google-account@gmail.com');
326
148
  });
327
- it('should not use GCP token if GOOGLE_CLOUD_ACCESS_TOKEN is not set', async () => {
328
- vi.stubEnv('GOOGLE_GENAI_USE_GCA', 'true');
149
+ it('should perform login with user code', async () => {
150
+ const mockConfigWithNoBrowser = {
151
+ getNoBrowser: () => true,
152
+ getProxy: () => 'http://test.proxy.com:8080',
153
+ isBrowserLaunchSuppressed: () => true,
154
+ };
155
+ const mockCodeVerifier = {
156
+ codeChallenge: 'test-challenge',
157
+ codeVerifier: 'test-verifier',
158
+ };
159
+ const mockAuthUrl = 'https://example.com/auth-user-code';
160
+ const mockCode = 'test-user-code';
161
+ const mockTokens = {
162
+ access_token: 'test-access-token-user-code',
163
+ refresh_token: 'test-refresh-token-user-code',
164
+ };
165
+ const mockGenerateAuthUrl = vi.fn().mockReturnValue(mockAuthUrl);
166
+ const mockGetToken = vi.fn().mockResolvedValue({ tokens: mockTokens });
329
167
  const mockSetCredentials = vi.fn();
330
- const mockGetAccessToken = vi
168
+ const mockGenerateCodeVerifierAsync = vi
331
169
  .fn()
332
- .mockResolvedValue({ token: 'cached-access-token' });
333
- const mockGetTokenInfo = vi.fn().mockResolvedValue({});
170
+ .mockResolvedValue(mockCodeVerifier);
334
171
  const mockOAuth2Client = {
172
+ generateAuthUrl: mockGenerateAuthUrl,
173
+ getToken: mockGetToken,
335
174
  setCredentials: mockSetCredentials,
336
- getAccessToken: mockGetAccessToken,
337
- getTokenInfo: mockGetTokenInfo,
175
+ generateCodeVerifierAsync: mockGenerateCodeVerifierAsync,
338
176
  on: vi.fn(),
339
177
  };
340
178
  OAuth2Client.mockImplementation(() => mockOAuth2Client);
341
- // Make it fall through to cached credentials path
342
- const cachedCreds = { refresh_token: 'cached-token' };
343
- const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
344
- await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
345
- await fs.promises.writeFile(credsPath, JSON.stringify(cachedCreds));
346
- await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
347
- // It should be called with the cached credentials, not the GCP access token.
348
- expect(mockSetCredentials).toHaveBeenCalledTimes(1);
349
- expect(mockSetCredentials).toHaveBeenCalledWith(cachedCreds);
179
+ const mockReadline = {
180
+ question: vi.fn((_query, callback) => callback(mockCode)),
181
+ close: vi.fn(),
182
+ };
183
+ readline.createInterface.mockReturnValue(mockReadline);
184
+ const consoleLogSpy = vi
185
+ .spyOn(console, 'log')
186
+ .mockImplementation(() => { });
187
+ const client = await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfigWithNoBrowser);
188
+ expect(client).toBe(mockOAuth2Client);
189
+ // Verify the auth flow
190
+ expect(mockGenerateCodeVerifierAsync).toHaveBeenCalled();
191
+ expect(mockGenerateAuthUrl).toHaveBeenCalled();
192
+ expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining(mockAuthUrl));
193
+ expect(mockReadline.question).toHaveBeenCalledWith('Enter the authorization code: ', expect.any(Function));
194
+ expect(mockGetToken).toHaveBeenCalledWith({
195
+ code: mockCode,
196
+ codeVerifier: mockCodeVerifier.codeVerifier,
197
+ redirect_uri: 'https://codeassist.google.com/authcode',
198
+ });
199
+ expect(mockSetCredentials).toHaveBeenCalledWith(mockTokens);
200
+ consoleLogSpy.mockRestore();
350
201
  });
351
- it('should not use GCP token if GOOGLE_GENAI_USE_GCA is not set', async () => {
352
- vi.stubEnv('GOOGLE_CLOUD_ACCESS_TOKEN', 'gcp-access-token');
353
- const mockSetCredentials = vi.fn();
354
- const mockGetAccessToken = vi
355
- .fn()
356
- .mockResolvedValue({ token: 'cached-access-token' });
357
- const mockGetTokenInfo = vi.fn().mockResolvedValue({});
202
+ describe('in Cloud Shell', () => {
203
+ const mockGetAccessToken = vi.fn();
204
+ let mockComputeClient;
205
+ beforeEach(() => {
206
+ mockGetAccessToken.mockResolvedValue({ token: 'test-access-token' });
207
+ mockComputeClient = {
208
+ credentials: { refresh_token: 'test-refresh-token' },
209
+ getAccessToken: mockGetAccessToken,
210
+ };
211
+ Compute.mockImplementation(() => mockComputeClient);
212
+ });
213
+ it('should attempt to load cached credentials first', async () => {
214
+ const cachedCreds = { refresh_token: 'cached-token' };
215
+ const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
216
+ await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
217
+ await fs.promises.writeFile(credsPath, JSON.stringify(cachedCreds));
218
+ const mockClient = {
219
+ setCredentials: vi.fn(),
220
+ getAccessToken: vi.fn().mockResolvedValue({ token: 'test-token' }),
221
+ getTokenInfo: vi.fn().mockResolvedValue({}),
222
+ on: vi.fn(),
223
+ };
224
+ // To mock the new OAuth2Client() inside the function
225
+ OAuth2Client.mockImplementation(() => mockClient);
226
+ await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
227
+ expect(mockClient.setCredentials).toHaveBeenCalledWith(cachedCreds);
228
+ expect(mockClient.getAccessToken).toHaveBeenCalled();
229
+ expect(mockClient.getTokenInfo).toHaveBeenCalled();
230
+ expect(Compute).not.toHaveBeenCalled(); // Should not fetch new client if cache is valid
231
+ });
232
+ it('should use Compute to get a client if no cached credentials exist', async () => {
233
+ await getOauthClient(AuthType.CLOUD_SHELL, mockConfig);
234
+ expect(Compute).toHaveBeenCalledWith({});
235
+ expect(mockGetAccessToken).toHaveBeenCalled();
236
+ });
237
+ it('should not cache the credentials after fetching them via ADC', async () => {
238
+ const newCredentials = { refresh_token: 'new-adc-token' };
239
+ mockComputeClient.credentials = newCredentials;
240
+ mockGetAccessToken.mockResolvedValue({ token: 'new-adc-token' });
241
+ await getOauthClient(AuthType.CLOUD_SHELL, mockConfig);
242
+ const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
243
+ expect(fs.existsSync(credsPath)).toBe(false);
244
+ });
245
+ it('should return the Compute client on successful ADC authentication', async () => {
246
+ const client = await getOauthClient(AuthType.CLOUD_SHELL, mockConfig);
247
+ expect(client).toBe(mockComputeClient);
248
+ });
249
+ it('should throw an error if ADC fails', async () => {
250
+ const testError = new Error('ADC Failed');
251
+ mockGetAccessToken.mockRejectedValue(testError);
252
+ await expect(getOauthClient(AuthType.CLOUD_SHELL, mockConfig)).rejects.toThrow('Could not authenticate using Cloud Shell credentials. Please select a different authentication method or ensure you are in a properly configured environment. Error: ADC Failed');
253
+ });
254
+ });
255
+ describe('credential loading order', () => {
256
+ it('should prioritize default cached credentials over GOOGLE_APPLICATION_CREDENTIALS', async () => {
257
+ // Setup default cached credentials
258
+ const defaultCreds = { refresh_token: 'default-cached-token' };
259
+ const defaultCredsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
260
+ await fs.promises.mkdir(path.dirname(defaultCredsPath), {
261
+ recursive: true,
262
+ });
263
+ await fs.promises.writeFile(defaultCredsPath, JSON.stringify(defaultCreds));
264
+ // Setup credentials via environment variable
265
+ const envCreds = { refresh_token: 'env-var-token' };
266
+ const envCredsPath = path.join(tempHomeDir, 'env_creds.json');
267
+ await fs.promises.writeFile(envCredsPath, JSON.stringify(envCreds));
268
+ vi.stubEnv('GOOGLE_APPLICATION_CREDENTIALS', envCredsPath);
269
+ const mockClient = {
270
+ setCredentials: vi.fn(),
271
+ getAccessToken: vi.fn().mockResolvedValue({ token: 'test-token' }),
272
+ getTokenInfo: vi.fn().mockResolvedValue({}),
273
+ on: vi.fn(),
274
+ };
275
+ OAuth2Client.mockImplementation(() => mockClient);
276
+ await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
277
+ // Assert the correct credentials were used
278
+ expect(mockClient.setCredentials).toHaveBeenCalledWith(defaultCreds);
279
+ expect(mockClient.setCredentials).not.toHaveBeenCalledWith(envCreds);
280
+ });
281
+ it('should fall back to GOOGLE_APPLICATION_CREDENTIALS if default cache is missing', async () => {
282
+ // Setup credentials via environment variable
283
+ const envCreds = { refresh_token: 'env-var-token' };
284
+ const envCredsPath = path.join(tempHomeDir, 'env_creds.json');
285
+ await fs.promises.writeFile(envCredsPath, JSON.stringify(envCreds));
286
+ vi.stubEnv('GOOGLE_APPLICATION_CREDENTIALS', envCredsPath);
287
+ const mockClient = {
288
+ setCredentials: vi.fn(),
289
+ getAccessToken: vi.fn().mockResolvedValue({ token: 'test-token' }),
290
+ getTokenInfo: vi.fn().mockResolvedValue({}),
291
+ on: vi.fn(),
292
+ };
293
+ OAuth2Client.mockImplementation(() => mockClient);
294
+ await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
295
+ // Assert the correct credentials were used
296
+ expect(mockClient.setCredentials).toHaveBeenCalledWith(envCreds);
297
+ });
298
+ });
299
+ describe('with GCP environment variables', () => {
300
+ it('should use GOOGLE_CLOUD_ACCESS_TOKEN when GOOGLE_GENAI_USE_GCA is true', async () => {
301
+ vi.stubEnv('GOOGLE_GENAI_USE_GCA', 'true');
302
+ vi.stubEnv('GOOGLE_CLOUD_ACCESS_TOKEN', 'gcp-access-token');
303
+ const mockSetCredentials = vi.fn();
304
+ const mockGetAccessToken = vi
305
+ .fn()
306
+ .mockResolvedValue({ token: 'gcp-access-token' });
307
+ const mockOAuth2Client = {
308
+ setCredentials: mockSetCredentials,
309
+ getAccessToken: mockGetAccessToken,
310
+ on: vi.fn(),
311
+ };
312
+ OAuth2Client.mockImplementation(() => mockOAuth2Client);
313
+ // Mock the UserInfo API response for fetchAndCacheUserInfo
314
+ global.fetch.mockResolvedValue({
315
+ ok: true,
316
+ json: vi
317
+ .fn()
318
+ .mockResolvedValue({ email: 'test-gcp-account@gmail.com' }),
319
+ });
320
+ const client = await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
321
+ expect(client).toBe(mockOAuth2Client);
322
+ expect(mockSetCredentials).toHaveBeenCalledWith({
323
+ access_token: 'gcp-access-token',
324
+ });
325
+ // Verify fetchAndCacheUserInfo was effectively called
326
+ expect(mockGetAccessToken).toHaveBeenCalled();
327
+ expect(global.fetch).toHaveBeenCalledWith('https://www.googleapis.com/oauth2/v2/userinfo', {
328
+ headers: {
329
+ Authorization: 'Bearer gcp-access-token',
330
+ },
331
+ });
332
+ // Verify Google Account was cached
333
+ const googleAccountPath = path.join(tempHomeDir, '.gemini', 'google_accounts.json');
334
+ const cachedContent = fs.readFileSync(googleAccountPath, 'utf-8');
335
+ expect(JSON.parse(cachedContent)).toEqual({
336
+ active: 'test-gcp-account@gmail.com',
337
+ old: [],
338
+ });
339
+ });
340
+ it('should not use GCP token if GOOGLE_CLOUD_ACCESS_TOKEN is not set', async () => {
341
+ vi.stubEnv('GOOGLE_GENAI_USE_GCA', 'true');
342
+ const mockSetCredentials = vi.fn();
343
+ const mockGetAccessToken = vi
344
+ .fn()
345
+ .mockResolvedValue({ token: 'cached-access-token' });
346
+ const mockGetTokenInfo = vi.fn().mockResolvedValue({});
347
+ const mockOAuth2Client = {
348
+ setCredentials: mockSetCredentials,
349
+ getAccessToken: mockGetAccessToken,
350
+ getTokenInfo: mockGetTokenInfo,
351
+ on: vi.fn(),
352
+ };
353
+ OAuth2Client.mockImplementation(() => mockOAuth2Client);
354
+ // Make it fall through to cached credentials path
355
+ const cachedCreds = { refresh_token: 'cached-token' };
356
+ const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
357
+ await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
358
+ await fs.promises.writeFile(credsPath, JSON.stringify(cachedCreds));
359
+ await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
360
+ // It should be called with the cached credentials, not the GCP access token.
361
+ expect(mockSetCredentials).toHaveBeenCalledTimes(1);
362
+ expect(mockSetCredentials).toHaveBeenCalledWith(cachedCreds);
363
+ });
364
+ it('should not use GCP token if GOOGLE_GENAI_USE_GCA is not set', async () => {
365
+ vi.stubEnv('GOOGLE_CLOUD_ACCESS_TOKEN', 'gcp-access-token');
366
+ const mockSetCredentials = vi.fn();
367
+ const mockGetAccessToken = vi
368
+ .fn()
369
+ .mockResolvedValue({ token: 'cached-access-token' });
370
+ const mockGetTokenInfo = vi.fn().mockResolvedValue({});
371
+ const mockOAuth2Client = {
372
+ setCredentials: mockSetCredentials,
373
+ getAccessToken: mockGetAccessToken,
374
+ getTokenInfo: mockGetTokenInfo,
375
+ on: vi.fn(),
376
+ };
377
+ OAuth2Client.mockImplementation(() => mockOAuth2Client);
378
+ // Make it fall through to cached credentials path
379
+ const cachedCreds = { refresh_token: 'cached-token' };
380
+ const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
381
+ await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
382
+ await fs.promises.writeFile(credsPath, JSON.stringify(cachedCreds));
383
+ await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
384
+ // It should be called with the cached credentials, not the GCP access token.
385
+ expect(mockSetCredentials).toHaveBeenCalledTimes(1);
386
+ expect(mockSetCredentials).toHaveBeenCalledWith(cachedCreds);
387
+ });
388
+ });
389
+ describe('error handling', () => {
390
+ it('should handle browser launch failure with FatalAuthenticationError', async () => {
391
+ const mockError = new Error('Browser launch failed');
392
+ open.mockRejectedValue(mockError);
393
+ const mockOAuth2Client = {
394
+ generateAuthUrl: vi.fn().mockReturnValue('https://example.com/auth'),
395
+ on: vi.fn(),
396
+ };
397
+ OAuth2Client.mockImplementation(() => mockOAuth2Client);
398
+ await expect(getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig)).rejects.toThrow('Failed to open browser: Browser launch failed');
399
+ });
400
+ it('should handle authentication timeout with proper error message', async () => {
401
+ const mockAuthUrl = 'https://example.com/auth';
402
+ const mockOAuth2Client = {
403
+ generateAuthUrl: vi.fn().mockReturnValue(mockAuthUrl),
404
+ on: vi.fn(),
405
+ };
406
+ OAuth2Client.mockImplementation(() => mockOAuth2Client);
407
+ open.mockImplementation(async () => ({ on: vi.fn() }));
408
+ const mockHttpServer = {
409
+ listen: vi.fn(),
410
+ close: vi.fn(),
411
+ on: vi.fn(),
412
+ address: () => ({ port: 3000 }),
413
+ };
414
+ http.createServer.mockImplementation(() => mockHttpServer);
415
+ // Mock setTimeout to trigger timeout immediately
416
+ const originalSetTimeout = global.setTimeout;
417
+ global.setTimeout = vi.fn((callback) => (callback(), {}));
418
+ await expect(getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig)).rejects.toThrow('Authentication timed out after 5 minutes. The browser tab may have gotten stuck in a loading state. Please try again or use NO_BROWSER=true for manual authentication.');
419
+ global.setTimeout = originalSetTimeout;
420
+ });
421
+ it('should handle OAuth callback errors with descriptive messages', async () => {
422
+ const mockAuthUrl = 'https://example.com/auth';
423
+ const mockOAuth2Client = {
424
+ generateAuthUrl: vi.fn().mockReturnValue(mockAuthUrl),
425
+ on: vi.fn(),
426
+ };
427
+ OAuth2Client.mockImplementation(() => mockOAuth2Client);
428
+ open.mockImplementation(async () => ({ on: vi.fn() }));
429
+ let requestCallback;
430
+ let serverListeningCallback;
431
+ const serverListeningPromise = new Promise((resolve) => (serverListeningCallback = resolve));
432
+ const mockHttpServer = {
433
+ listen: vi.fn((_port, _host, callback) => {
434
+ if (callback)
435
+ callback();
436
+ serverListeningCallback(undefined);
437
+ }),
438
+ close: vi.fn(),
439
+ on: vi.fn(),
440
+ address: () => ({ port: 3000 }),
441
+ };
442
+ http.createServer.mockImplementation((cb) => {
443
+ requestCallback = cb;
444
+ return mockHttpServer;
445
+ });
446
+ const clientPromise = getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
447
+ await serverListeningPromise;
448
+ // Test OAuth error with description
449
+ const mockReq = {
450
+ url: '/oauth2callback?error=access_denied&error_description=User+denied+access',
451
+ };
452
+ const mockRes = {
453
+ writeHead: vi.fn(),
454
+ end: vi.fn(),
455
+ };
456
+ await expect(async () => {
457
+ await requestCallback(mockReq, mockRes);
458
+ await clientPromise;
459
+ }).rejects.toThrow('Google OAuth error: access_denied. User denied access');
460
+ });
461
+ it('should handle OAuth error without description', async () => {
462
+ const mockAuthUrl = 'https://example.com/auth';
463
+ const mockOAuth2Client = {
464
+ generateAuthUrl: vi.fn().mockReturnValue(mockAuthUrl),
465
+ on: vi.fn(),
466
+ };
467
+ OAuth2Client.mockImplementation(() => mockOAuth2Client);
468
+ open.mockImplementation(async () => ({ on: vi.fn() }));
469
+ let requestCallback;
470
+ let serverListeningCallback;
471
+ const serverListeningPromise = new Promise((resolve) => (serverListeningCallback = resolve));
472
+ const mockHttpServer = {
473
+ listen: vi.fn((_port, _host, callback) => {
474
+ if (callback)
475
+ callback();
476
+ serverListeningCallback(undefined);
477
+ }),
478
+ close: vi.fn(),
479
+ on: vi.fn(),
480
+ address: () => ({ port: 3000 }),
481
+ };
482
+ http.createServer.mockImplementation((cb) => {
483
+ requestCallback = cb;
484
+ return mockHttpServer;
485
+ });
486
+ const clientPromise = getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
487
+ await serverListeningPromise;
488
+ // Test OAuth error without description
489
+ const mockReq = {
490
+ url: '/oauth2callback?error=server_error',
491
+ };
492
+ const mockRes = {
493
+ writeHead: vi.fn(),
494
+ end: vi.fn(),
495
+ };
496
+ await expect(async () => {
497
+ await requestCallback(mockReq, mockRes);
498
+ await clientPromise;
499
+ }).rejects.toThrow('Google OAuth error: server_error. No additional details provided');
500
+ });
501
+ it('should handle token exchange failure with descriptive error', async () => {
502
+ const mockAuthUrl = 'https://example.com/auth';
503
+ const mockCode = 'test-code';
504
+ const mockState = 'test-state';
505
+ const mockOAuth2Client = {
506
+ generateAuthUrl: vi.fn().mockReturnValue(mockAuthUrl),
507
+ getToken: vi
508
+ .fn()
509
+ .mockRejectedValue(new Error('Token exchange failed')),
510
+ on: vi.fn(),
511
+ };
512
+ OAuth2Client.mockImplementation(() => mockOAuth2Client);
513
+ vi.spyOn(crypto, 'randomBytes').mockReturnValue(mockState);
514
+ open.mockImplementation(async () => ({ on: vi.fn() }));
515
+ let requestCallback;
516
+ let serverListeningCallback;
517
+ const serverListeningPromise = new Promise((resolve) => (serverListeningCallback = resolve));
518
+ const mockHttpServer = {
519
+ listen: vi.fn((_port, _host, callback) => {
520
+ if (callback)
521
+ callback();
522
+ serverListeningCallback(undefined);
523
+ }),
524
+ close: vi.fn(),
525
+ on: vi.fn(),
526
+ address: () => ({ port: 3000 }),
527
+ };
528
+ http.createServer.mockImplementation((cb) => {
529
+ requestCallback = cb;
530
+ return mockHttpServer;
531
+ });
532
+ const clientPromise = getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
533
+ await serverListeningPromise;
534
+ const mockReq = {
535
+ url: `/oauth2callback?code=${mockCode}&state=${mockState}`,
536
+ };
537
+ const mockRes = {
538
+ writeHead: vi.fn(),
539
+ end: vi.fn(),
540
+ };
541
+ await expect(async () => {
542
+ await requestCallback(mockReq, mockRes);
543
+ await clientPromise;
544
+ }).rejects.toThrow('Failed to exchange authorization code for tokens: Token exchange failed');
545
+ });
546
+ it('should handle fetchAndCacheUserInfo failure gracefully', async () => {
547
+ const mockAuthUrl = 'https://example.com/auth';
548
+ const mockCode = 'test-code';
549
+ const mockState = 'test-state';
550
+ const mockTokens = {
551
+ access_token: 'test-access-token',
552
+ refresh_token: 'test-refresh-token',
553
+ };
554
+ const mockOAuth2Client = {
555
+ generateAuthUrl: vi.fn().mockReturnValue(mockAuthUrl),
556
+ getToken: vi.fn().mockResolvedValue({ tokens: mockTokens }),
557
+ setCredentials: vi.fn(),
558
+ getAccessToken: vi
559
+ .fn()
560
+ .mockResolvedValue({ token: 'test-access-token' }),
561
+ on: vi.fn(),
562
+ };
563
+ OAuth2Client.mockImplementation(() => mockOAuth2Client);
564
+ vi.spyOn(crypto, 'randomBytes').mockReturnValue(mockState);
565
+ open.mockImplementation(async () => ({ on: vi.fn() }));
566
+ // Mock fetch to fail
567
+ global.fetch.mockResolvedValue({
568
+ ok: false,
569
+ status: 500,
570
+ statusText: 'Internal Server Error',
571
+ });
572
+ const consoleErrorSpy = vi
573
+ .spyOn(console, 'error')
574
+ .mockImplementation(() => { });
575
+ let requestCallback;
576
+ let serverListeningCallback;
577
+ const serverListeningPromise = new Promise((resolve) => (serverListeningCallback = resolve));
578
+ const mockHttpServer = {
579
+ listen: vi.fn((_port, _host, callback) => {
580
+ if (callback)
581
+ callback();
582
+ serverListeningCallback(undefined);
583
+ }),
584
+ close: vi.fn(),
585
+ on: vi.fn(),
586
+ address: () => ({ port: 3000 }),
587
+ };
588
+ http.createServer.mockImplementation((cb) => {
589
+ requestCallback = cb;
590
+ return mockHttpServer;
591
+ });
592
+ const clientPromise = getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
593
+ await serverListeningPromise;
594
+ const mockReq = {
595
+ url: `/oauth2callback?code=${mockCode}&state=${mockState}`,
596
+ };
597
+ const mockRes = {
598
+ writeHead: vi.fn(),
599
+ end: vi.fn(),
600
+ };
601
+ await requestCallback(mockReq, mockRes);
602
+ const client = await clientPromise;
603
+ // Authentication should succeed even if fetchAndCacheUserInfo fails
604
+ expect(client).toBe(mockOAuth2Client);
605
+ expect(consoleErrorSpy).toHaveBeenCalledWith('Failed to fetch user info:', 500, 'Internal Server Error');
606
+ consoleErrorSpy.mockRestore();
607
+ });
608
+ it('should handle user code authentication failure with descriptive error', async () => {
609
+ const mockConfigWithNoBrowser = {
610
+ getNoBrowser: () => true,
611
+ getProxy: () => 'http://test.proxy.com:8080',
612
+ isBrowserLaunchSuppressed: () => true,
613
+ };
614
+ const mockOAuth2Client = {
615
+ generateCodeVerifierAsync: vi.fn().mockResolvedValue({
616
+ codeChallenge: 'test-challenge',
617
+ codeVerifier: 'test-verifier',
618
+ }),
619
+ generateAuthUrl: vi.fn().mockReturnValue('https://example.com/auth'),
620
+ getToken: vi
621
+ .fn()
622
+ .mockRejectedValue(new Error('Invalid authorization code')),
623
+ on: vi.fn(),
624
+ };
625
+ OAuth2Client.mockImplementation(() => mockOAuth2Client);
626
+ const mockReadline = {
627
+ question: vi.fn((_query, callback) => callback('invalid-code')),
628
+ close: vi.fn(),
629
+ };
630
+ readline.createInterface.mockReturnValue(mockReadline);
631
+ const consoleLogSpy = vi
632
+ .spyOn(console, 'log')
633
+ .mockImplementation(() => { });
634
+ const consoleErrorSpy = vi
635
+ .spyOn(console, 'error')
636
+ .mockImplementation(() => { });
637
+ await expect(getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfigWithNoBrowser)).rejects.toThrow('Failed to authenticate with user code.');
638
+ expect(consoleErrorSpy).toHaveBeenCalledWith('Failed to authenticate with authorization code:', 'Invalid authorization code');
639
+ consoleLogSpy.mockRestore();
640
+ consoleErrorSpy.mockRestore();
641
+ });
642
+ });
643
+ describe('clearCachedCredentialFile', () => {
644
+ it('should clear cached credentials and Google account', async () => {
645
+ const cachedCreds = { refresh_token: 'test-token' };
646
+ const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
647
+ await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
648
+ await fs.promises.writeFile(credsPath, JSON.stringify(cachedCreds));
649
+ const googleAccountPath = path.join(tempHomeDir, '.gemini', 'google_accounts.json');
650
+ const accountData = { active: 'test@example.com', old: [] };
651
+ await fs.promises.writeFile(googleAccountPath, JSON.stringify(accountData));
652
+ const userAccountManager = new UserAccountManager();
653
+ expect(fs.existsSync(credsPath)).toBe(true);
654
+ expect(fs.existsSync(googleAccountPath)).toBe(true);
655
+ expect(userAccountManager.getCachedGoogleAccount()).toBe('test@example.com');
656
+ await clearCachedCredentialFile();
657
+ expect(fs.existsSync(credsPath)).toBe(false);
658
+ expect(userAccountManager.getCachedGoogleAccount()).toBeNull();
659
+ const updatedAccountData = JSON.parse(fs.readFileSync(googleAccountPath, 'utf-8'));
660
+ expect(updatedAccountData.active).toBeNull();
661
+ expect(updatedAccountData.old).toContain('test@example.com');
662
+ });
663
+ it('should clear the in-memory OAuth client cache', async () => {
664
+ const mockSetCredentials = vi.fn();
665
+ const mockGetAccessToken = vi
666
+ .fn()
667
+ .mockResolvedValue({ token: 'test-token' });
668
+ const mockGetTokenInfo = vi.fn().mockResolvedValue({});
669
+ const mockOAuth2Client = {
670
+ setCredentials: mockSetCredentials,
671
+ getAccessToken: mockGetAccessToken,
672
+ getTokenInfo: mockGetTokenInfo,
673
+ on: vi.fn(),
674
+ };
675
+ OAuth2Client.mockImplementation(() => mockOAuth2Client);
676
+ // Pre-populate credentials to make getOauthClient resolve quickly
677
+ const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
678
+ await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
679
+ await fs.promises.writeFile(credsPath, JSON.stringify({ refresh_token: 'token' }));
680
+ // First call, should create a client
681
+ await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
682
+ expect(OAuth2Client).toHaveBeenCalledTimes(1);
683
+ // Second call, should use cached client
684
+ await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
685
+ expect(OAuth2Client).toHaveBeenCalledTimes(1);
686
+ clearOauthClientCache();
687
+ // Third call, after clearing cache, should create a new client
688
+ await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
689
+ expect(OAuth2Client).toHaveBeenCalledTimes(2);
690
+ });
691
+ });
692
+ });
693
+ describe('with encrypted flag true', () => {
694
+ let tempHomeDir;
695
+ beforeEach(() => {
696
+ process.env[FORCE_ENCRYPTED_FILE_ENV_VAR] = 'true';
697
+ tempHomeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gemini-cli-test-home-'));
698
+ os.homedir.mockReturnValue(tempHomeDir);
699
+ });
700
+ afterEach(() => {
701
+ fs.rmSync(tempHomeDir, { recursive: true, force: true });
702
+ vi.clearAllMocks();
703
+ resetOauthClientForTesting();
704
+ vi.unstubAllEnvs();
705
+ });
706
+ it('should save credentials using OAuthCredentialStorage during web login', async () => {
707
+ const { OAuthCredentialStorage } = await import('./oauth-credential-storage.js');
708
+ const mockAuthUrl = 'https://example.com/auth';
709
+ const mockCode = 'test-code';
710
+ const mockState = 'test-state';
711
+ const mockTokens = {
712
+ access_token: 'test-access-token',
713
+ refresh_token: 'test-refresh-token',
714
+ };
715
+ let onTokensCallback = () => { };
716
+ const mockOn = vi.fn((event, callback) => {
717
+ if (event === 'tokens') {
718
+ onTokensCallback = callback;
719
+ }
720
+ });
721
+ const mockGetToken = vi.fn().mockImplementation(async () => {
722
+ onTokensCallback(mockTokens);
723
+ return { tokens: mockTokens };
724
+ });
358
725
  const mockOAuth2Client = {
359
- setCredentials: mockSetCredentials,
360
- getAccessToken: mockGetAccessToken,
361
- getTokenInfo: mockGetTokenInfo,
362
- on: vi.fn(),
726
+ generateAuthUrl: vi.fn().mockReturnValue(mockAuthUrl),
727
+ getToken: mockGetToken,
728
+ setCredentials: vi.fn(),
729
+ getAccessToken: vi
730
+ .fn()
731
+ .mockResolvedValue({ token: 'mock-access-token' }),
732
+ on: mockOn,
733
+ credentials: mockTokens,
363
734
  };
364
735
  OAuth2Client.mockImplementation(() => mockOAuth2Client);
365
- // Make it fall through to cached credentials path
366
- const cachedCreds = { refresh_token: 'cached-token' };
736
+ vi.spyOn(crypto, 'randomBytes').mockReturnValue(mockState);
737
+ open.mockImplementation(async () => ({ on: vi.fn() }));
738
+ global.fetch.mockResolvedValue({
739
+ ok: true,
740
+ json: vi
741
+ .fn()
742
+ .mockResolvedValue({ email: 'test-google-account@gmail.com' }),
743
+ });
744
+ let requestCallback;
745
+ let serverListeningCallback;
746
+ const serverListeningPromise = new Promise((resolve) => (serverListeningCallback = resolve));
747
+ let capturedPort = 0;
748
+ const mockHttpServer = {
749
+ listen: vi.fn((port, _host, callback) => {
750
+ capturedPort = port;
751
+ if (callback) {
752
+ callback();
753
+ }
754
+ serverListeningCallback(undefined);
755
+ }),
756
+ close: vi.fn((callback) => {
757
+ if (callback) {
758
+ callback();
759
+ }
760
+ }),
761
+ on: vi.fn(),
762
+ address: () => ({ port: capturedPort }),
763
+ };
764
+ http.createServer.mockImplementation((cb) => {
765
+ requestCallback = cb;
766
+ return mockHttpServer;
767
+ });
768
+ const clientPromise = getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
769
+ await serverListeningPromise;
770
+ const mockReq = {
771
+ url: `/oauth2callback?code=${mockCode}&state=${mockState}`,
772
+ };
773
+ const mockRes = {
774
+ writeHead: vi.fn(),
775
+ end: vi.fn(),
776
+ };
777
+ requestCallback(mockReq, mockRes);
778
+ await clientPromise;
779
+ expect(OAuthCredentialStorage.saveCredentials).toHaveBeenCalledWith(mockTokens);
367
780
  const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
368
- await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
369
- await fs.promises.writeFile(credsPath, JSON.stringify(cachedCreds));
370
- await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
371
- // It should be called with the cached credentials, not the GCP access token.
372
- expect(mockSetCredentials).toHaveBeenCalledTimes(1);
373
- expect(mockSetCredentials).toHaveBeenCalledWith(cachedCreds);
781
+ expect(fs.existsSync(credsPath)).toBe(false);
374
782
  });
375
- });
376
- describe('clearCachedCredentialFile', () => {
377
- it('should clear cached credentials and Google account', async () => {
378
- const cachedCreds = { refresh_token: 'test-token' };
783
+ it('should load credentials using OAuthCredentialStorage and not from file', async () => {
784
+ const { OAuthCredentialStorage } = await import('./oauth-credential-storage.js');
785
+ const cachedCreds = { refresh_token: 'cached-encrypted-token' };
786
+ OAuthCredentialStorage.loadCredentials.mockResolvedValue(cachedCreds);
787
+ // Create a dummy unencrypted credential file.
788
+ // If the logic is correct, this file should be ignored.
789
+ const unencryptedCreds = { refresh_token: 'unencrypted-token' };
379
790
  const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
380
791
  await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
381
- await fs.promises.writeFile(credsPath, JSON.stringify(cachedCreds));
382
- const googleAccountPath = path.join(tempHomeDir, '.gemini', 'google_accounts.json');
383
- const accountData = { active: 'test@example.com', old: [] };
384
- await fs.promises.writeFile(googleAccountPath, JSON.stringify(accountData));
385
- expect(fs.existsSync(credsPath)).toBe(true);
386
- expect(fs.existsSync(googleAccountPath)).toBe(true);
387
- expect(getCachedGoogleAccount()).toBe('test@example.com');
388
- await clearCachedCredentialFile();
389
- expect(fs.existsSync(credsPath)).toBe(false);
390
- expect(getCachedGoogleAccount()).toBeNull();
391
- const updatedAccountData = JSON.parse(fs.readFileSync(googleAccountPath, 'utf-8'));
392
- expect(updatedAccountData.active).toBeNull();
393
- expect(updatedAccountData.old).toContain('test@example.com');
394
- });
395
- it('should clear the in-memory OAuth client cache', async () => {
396
- const mockSetCredentials = vi.fn();
397
- const mockGetAccessToken = vi
398
- .fn()
399
- .mockResolvedValue({ token: 'test-token' });
400
- const mockGetTokenInfo = vi.fn().mockResolvedValue({});
401
- const mockOAuth2Client = {
402
- setCredentials: mockSetCredentials,
403
- getAccessToken: mockGetAccessToken,
404
- getTokenInfo: mockGetTokenInfo,
792
+ await fs.promises.writeFile(credsPath, JSON.stringify(unencryptedCreds));
793
+ const mockClient = {
794
+ setCredentials: vi.fn(),
795
+ getAccessToken: vi.fn().mockResolvedValue({ token: 'test-token' }),
796
+ getTokenInfo: vi.fn().mockResolvedValue({}),
405
797
  on: vi.fn(),
406
798
  };
407
- OAuth2Client.mockImplementation(() => mockOAuth2Client);
408
- // Pre-populate credentials to make getOauthClient resolve quickly
799
+ OAuth2Client.mockImplementation(() => mockClient);
800
+ await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
801
+ expect(OAuthCredentialStorage.loadCredentials).toHaveBeenCalled();
802
+ expect(mockClient.setCredentials).toHaveBeenCalledWith(cachedCreds);
803
+ expect(mockClient.setCredentials).not.toHaveBeenCalledWith(unencryptedCreds);
804
+ });
805
+ it('should clear credentials using OAuthCredentialStorage', async () => {
806
+ const { OAuthCredentialStorage } = await import('./oauth-credential-storage.js');
807
+ // Create a dummy unencrypted credential file. It should not be deleted.
409
808
  const credsPath = path.join(tempHomeDir, '.gemini', 'oauth_creds.json');
410
809
  await fs.promises.mkdir(path.dirname(credsPath), { recursive: true });
411
- await fs.promises.writeFile(credsPath, JSON.stringify({ refresh_token: 'token' }));
412
- // First call, should create a client
413
- await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
414
- expect(OAuth2Client).toHaveBeenCalledTimes(1);
415
- // Second call, should use cached client
416
- await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
417
- expect(OAuth2Client).toHaveBeenCalledTimes(1);
418
- clearOauthClientCache();
419
- // Third call, after clearing cache, should create a new client
420
- await getOauthClient(AuthType.LOGIN_WITH_GOOGLE, mockConfig);
421
- expect(OAuth2Client).toHaveBeenCalledTimes(2);
810
+ await fs.promises.writeFile(credsPath, '{}');
811
+ await clearCachedCredentialFile();
812
+ expect(OAuthCredentialStorage.clearCredentials).toHaveBeenCalled();
813
+ expect(fs.existsSync(credsPath)).toBe(true); // The unencrypted file should remain
422
814
  });
423
815
  });
424
816
  });