@google/gemini-cli-core 0.19.0-nightly.20251126.03845198c → 0.20.0-nightly.20251127.5bed97064

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 (101) hide show
  1. package/dist/google-gemini-cli-core-0.20.0-nightly.20251126.d2a6cff4d.tgz +0 -0
  2. package/dist/src/availability/modelAvailabilityService.d.ts +1 -1
  3. package/dist/src/availability/modelAvailabilityService.js +2 -2
  4. package/dist/src/availability/modelAvailabilityService.js.map +1 -1
  5. package/dist/src/availability/modelAvailabilityService.test.js +3 -3
  6. package/dist/src/availability/modelAvailabilityService.test.js.map +1 -1
  7. package/dist/src/availability/policyHelpers.d.ts +21 -0
  8. package/dist/src/availability/policyHelpers.js +41 -0
  9. package/dist/src/availability/policyHelpers.js.map +1 -0
  10. package/dist/src/availability/policyHelpers.test.d.ts +6 -0
  11. package/dist/src/availability/policyHelpers.test.js +51 -0
  12. package/dist/src/availability/policyHelpers.test.js.map +1 -0
  13. package/dist/src/config/config.d.ts +8 -1
  14. package/dist/src/config/config.js +17 -1
  15. package/dist/src/config/config.js.map +1 -1
  16. package/dist/src/config/config.test.js +14 -0
  17. package/dist/src/config/config.test.js.map +1 -1
  18. package/dist/src/core/client.js +4 -37
  19. package/dist/src/core/client.js.map +1 -1
  20. package/dist/src/core/client.test.js +45 -0
  21. package/dist/src/core/client.test.js.map +1 -1
  22. package/dist/src/core/contentGenerator.js +11 -0
  23. package/dist/src/core/contentGenerator.js.map +1 -1
  24. package/dist/src/core/contentGenerator.test.js +108 -0
  25. package/dist/src/core/contentGenerator.test.js.map +1 -1
  26. package/dist/src/core/coreToolHookTriggers.d.ts +55 -0
  27. package/dist/src/core/coreToolHookTriggers.js +244 -0
  28. package/dist/src/core/coreToolHookTriggers.js.map +1 -0
  29. package/dist/src/core/coreToolScheduler.js +11 -2
  30. package/dist/src/core/coreToolScheduler.js.map +1 -1
  31. package/dist/src/core/coreToolScheduler.test.js +66 -1
  32. package/dist/src/core/coreToolScheduler.test.js.map +1 -1
  33. package/dist/src/core/geminiChat.js +90 -18
  34. package/dist/src/core/geminiChat.js.map +1 -1
  35. package/dist/src/core/geminiChat.test.js +14 -3
  36. package/dist/src/core/geminiChat.test.js.map +1 -1
  37. package/dist/src/core/geminiChatHookTriggers.d.ts +64 -0
  38. package/dist/src/core/geminiChatHookTriggers.js +136 -0
  39. package/dist/src/core/geminiChatHookTriggers.js.map +1 -0
  40. package/dist/src/core/prompts.js +38 -19
  41. package/dist/src/core/prompts.js.map +1 -1
  42. package/dist/src/fallback/handler.js +105 -28
  43. package/dist/src/fallback/handler.js.map +1 -1
  44. package/dist/src/fallback/handler.test.js +145 -0
  45. package/dist/src/fallback/handler.test.js.map +1 -1
  46. package/dist/src/fallback/types.d.ts +8 -0
  47. package/dist/src/generated/git-commit.d.ts +2 -2
  48. package/dist/src/generated/git-commit.js +2 -2
  49. package/dist/src/index.d.ts +1 -0
  50. package/dist/src/index.js +1 -0
  51. package/dist/src/index.js.map +1 -1
  52. package/dist/src/mcp/auth-provider.d.ts +16 -0
  53. package/dist/src/mcp/auth-provider.js +7 -0
  54. package/dist/src/mcp/auth-provider.js.map +1 -0
  55. package/dist/src/mcp/google-auth-provider.d.ts +10 -2
  56. package/dist/src/mcp/google-auth-provider.js +28 -0
  57. package/dist/src/mcp/google-auth-provider.js.map +1 -1
  58. package/dist/src/mcp/google-auth-provider.test.js +45 -0
  59. package/dist/src/mcp/google-auth-provider.test.js.map +1 -1
  60. package/dist/src/mcp/sa-impersonation-provider.d.ts +2 -2
  61. package/dist/src/mcp/sa-impersonation-provider.js.map +1 -1
  62. package/dist/src/services/chatCompressionService.js +2 -2
  63. package/dist/src/services/chatCompressionService.js.map +1 -1
  64. package/dist/src/services/chatCompressionService.test.js +7 -0
  65. package/dist/src/services/chatCompressionService.test.js.map +1 -1
  66. package/dist/src/tools/mcp-client-manager.d.ts +1 -0
  67. package/dist/src/tools/mcp-client-manager.js +13 -0
  68. package/dist/src/tools/mcp-client-manager.js.map +1 -1
  69. package/dist/src/tools/mcp-client-manager.test.js +35 -0
  70. package/dist/src/tools/mcp-client-manager.test.js.map +1 -1
  71. package/dist/src/tools/mcp-client.d.ts +1 -0
  72. package/dist/src/tools/mcp-client.js +4 -1
  73. package/dist/src/tools/mcp-client.js.map +1 -1
  74. package/dist/src/tools/mcp-client.test.js +64 -16
  75. package/dist/src/tools/mcp-client.test.js.map +1 -1
  76. package/dist/src/tools/shell.js +43 -3
  77. package/dist/src/tools/shell.js.map +1 -1
  78. package/dist/src/tools/shell.test.js +23 -4
  79. package/dist/src/tools/shell.test.js.map +1 -1
  80. package/dist/src/utils/customHeaderUtils.d.ts +9 -0
  81. package/dist/src/utils/customHeaderUtils.js +34 -0
  82. package/dist/src/utils/customHeaderUtils.js.map +1 -0
  83. package/dist/src/utils/customHeaderUtils.test.d.ts +6 -0
  84. package/dist/src/utils/customHeaderUtils.test.js +77 -0
  85. package/dist/src/utils/customHeaderUtils.test.js.map +1 -0
  86. package/dist/src/utils/exitCodes.d.ts +12 -0
  87. package/dist/src/utils/exitCodes.js +13 -0
  88. package/dist/src/utils/exitCodes.js.map +1 -0
  89. package/dist/src/utils/memoryDiscovery.js +5 -1
  90. package/dist/src/utils/memoryDiscovery.js.map +1 -1
  91. package/dist/src/utils/memoryDiscovery.test.js +28 -0
  92. package/dist/src/utils/memoryDiscovery.test.js.map +1 -1
  93. package/dist/src/utils/tokenCalculation.d.ts +19 -0
  94. package/dist/src/utils/tokenCalculation.js +70 -0
  95. package/dist/src/utils/tokenCalculation.js.map +1 -0
  96. package/dist/src/utils/tokenCalculation.test.d.ts +6 -0
  97. package/dist/src/utils/tokenCalculation.test.js +78 -0
  98. package/dist/src/utils/tokenCalculation.test.js.map +1 -0
  99. package/dist/tsconfig.tsbuildinfo +1 -1
  100. package/package.json +2 -2
  101. package/dist/google-gemini-cli-core-0.19.0-nightly.20251125.f6d97d448.tgz +0 -0
@@ -75,7 +75,11 @@ export function getCoreSystemPrompt(config, userMemory) {
75
75
  }
76
76
  // TODO(joshualitt): Replace with system instructions on model configs.
77
77
  const desiredModel = getEffectiveModel(config.isInFallbackMode(), config.getModel(), config.getPreviewFeatures());
78
- const useChattySystemPrompt = desiredModel === PREVIEW_GEMINI_MODEL;
78
+ const isGemini3 = desiredModel === PREVIEW_GEMINI_MODEL;
79
+ const mandatesVariant = isGemini3
80
+ ? `
81
+ - **Do not call tools in silence:** You must provide to the user very short and concise natural explanation (one sentence) before calling tools.`
82
+ : ``;
79
83
  const enableCodebaseInvestigator = config
80
84
  .getToolRegistry()
81
85
  .getAllToolNames()
@@ -84,13 +88,14 @@ export function getCoreSystemPrompt(config, userMemory) {
84
88
  .getToolRegistry()
85
89
  .getAllToolNames()
86
90
  .includes(WriteTodosTool.Name);
91
+ const interactiveMode = config.isInteractiveShellEnabled();
87
92
  let basePrompt;
88
93
  if (systemMdEnabled) {
89
94
  basePrompt = fs.readFileSync(systemMdPath, 'utf8');
90
95
  }
91
96
  else {
92
97
  const promptConfig = {
93
- preamble: `You are an interactive CLI agent specializing in software engineering tasks. Your primary goal is to help users safely and efficiently, adhering strictly to the following instructions and utilizing your available tools.`,
98
+ preamble: `You are ${interactiveMode ? 'an interactive ' : 'a non-interactive '}CLI agent specializing in software engineering tasks. Your primary goal is to help users safely and efficiently, adhering strictly to the following instructions and utilizing your available tools.`,
94
99
  coreMandates: `
95
100
  # Core Mandates
96
101
 
@@ -100,9 +105,12 @@ export function getCoreSystemPrompt(config, userMemory) {
100
105
  - **Idiomatic Changes:** When editing, understand the local context (imports, functions/classes) to ensure your changes integrate naturally and idiomatically.
101
106
  - **Comments:** Add code comments sparingly. Focus on *why* something is done, especially for complex logic, rather than *what* is done. Only add high-value comments if necessary for clarity or if requested by the user. Do not edit comments that are separate from the code you are changing. *NEVER* talk to the user or describe your changes through comments.
102
107
  - **Proactiveness:** Fulfill the user's request thoroughly. When adding features or fixing bugs, this includes adding tests to ensure quality. Consider all created files, especially tests, to be permanent artifacts unless the user says otherwise.
103
- - **Confirm Ambiguity/Expansion:** Do not take significant actions beyond the clear scope of the request without confirming with the user. If asked *how* to do something, explain first, don't just do it.
108
+ - ${interactiveMode ? `**Confirm Ambiguity/Expansion:** Do not take significant actions beyond the clear scope of the request without confirming with the user. If asked *how* to do something, explain first, don't just do it.` : `**Handle Ambiguity/Expansion:** Do not take significant actions beyond the clear scope of the request.`}
104
109
  - **Explaining Changes:** After completing a code modification or file operation *do not* provide summaries unless asked.
105
- - **Do Not revert changes:** Do not revert changes to the codebase unless asked to do so by the user. Only revert changes made by you if they have resulted in an error or if the user has explicitly asked you to revert the changes.`,
110
+ - **Do Not revert changes:** Do not revert changes to the codebase unless asked to do so by the user. Only revert changes made by you if they have resulted in an error or if the user has explicitly asked you to revert the changes.${mandatesVariant}${!interactiveMode
111
+ ? `
112
+ - **Continue the work** You are not to interact with the user. Do your best to complete the task at hand, using your best judgement and avoid asking user for any additional information.`
113
+ : ''}`,
106
114
  primaryWorkflows_prefix: `
107
115
  # Primary Workflows
108
116
 
@@ -135,14 +143,14 @@ When requested to perform tasks like fixing bugs, adding features, refactoring,
135
143
  primaryWorkflows_suffix: `3. **Implement:** Use the available tools (e.g., '${EDIT_TOOL_NAME}', '${WRITE_FILE_TOOL_NAME}' '${SHELL_TOOL_NAME}' ...) to act on the plan, strictly adhering to the project's established conventions (detailed under 'Core
136
144
  Mandates').
137
145
  4. **Verify (Tests):** If applicable and feasible, verify the changes using the project's testing procedures. Identify the correct test commands and frameworks by examining 'README' files, build/package configuration (e.g., 'package.json'), or existing test execution patterns. NEVER assume standard test commands.
138
- 5. **Verify (Standards):** VERY IMPORTANT: After making code changes, execute the project-specific build, linting and type-checking commands (e.g., 'tsc', 'npm run lint', 'ruff check .') that you have identified for this project (or obtained from the user). This ensures code quality and adherence to standards. If unsure about these commands, you can ask the user if they'd like you to run them and if so how to.
146
+ 5. **Verify (Standards):** VERY IMPORTANT: After making code changes, execute the project-specific build, linting and type-checking commands (e.g., 'tsc', 'npm run lint', 'ruff check .') that you have identified for this project (or obtained from the user). This ensures code quality and adherence to standards.${interactiveMode ? " If unsure about these commands, you can ask the user if they'd like you to run them and if so how to." : ''}
139
147
  6. **Finalize:** After all verification passes, consider the task complete. Do not remove or revert any changes or created files (like tests). Await the user's next instruction.
140
148
 
141
149
  ## New Applications
142
150
 
143
151
  **Goal:** Autonomously implement and deliver a visually appealing, substantially complete, and functional prototype. Utilize all tools at your disposal to implement the application. Some tools you may especially find useful are '${WRITE_FILE_TOOL_NAME}', '${EDIT_TOOL_NAME}' and '${SHELL_TOOL_NAME}'.
144
152
 
145
- 1. **Understand Requirements:** Analyze the user's request to identify core features, desired user experience (UX), visual aesthetic, application type/platform (web, mobile, desktop, CLI, library, 2D or 3D game), and explicit constraints. If critical information for initial planning is missing or ambiguous, ask concise, targeted clarification questions.
153
+ 1. **Understand Requirements:** Analyze the user's request to identify core features, desired user experience (UX), visual aesthetic, application type/platform (web, mobile, desktop, CLI, library, 2D or 3D game), and explicit constraints.${interactiveMode ? ' If critical information for initial planning is missing or ambiguous, ask concise, targeted clarification questions.' : ''}
146
154
  2. **Propose Plan:** Formulate an internal development plan. Present a clear, concise, high-level summary to the user. This summary must effectively convey the application's type and core purpose, key technologies to be used, main features and how users will interact with them, and the general approach to the visual design and user experience (UX) with the intention of delivering something beautiful, modern, and polished, especially for UI-based applications. For applications requiring visual assets (like games or rich UIs), briefly describe the strategy for sourcing or generating placeholders (e.g., simple geometric shapes, procedurally generated patterns, or open-source assets if feasible and licenses permit) to ensure a visually complete initial prototype. Ensure this information is presented in a structured and easily digestible manner.
147
155
  - When key technologies aren't specified, prefer the following:
148
156
  - **Websites (Frontend):** React (JavaScript/TypeScript) or Angular with Bootstrap CSS, incorporating Material Design principles for UI/UX.
@@ -152,10 +160,18 @@ Mandates').
152
160
  - **Mobile App:** Compose Multiplatform (Kotlin Multiplatform) or Flutter (Dart) using Material Design libraries and principles, when sharing code between Android and iOS. Jetpack Compose (Kotlin JVM) with Material Design principles or SwiftUI (Swift) for native apps targeted at either Android or iOS, respectively.
153
161
  - **3d Games:** HTML/CSS/JavaScript with Three.js.
154
162
  - **2d Games:** HTML/CSS/JavaScript.
155
- 3. **User Approval:** Obtain user approval for the proposed plan.
163
+ ${(function () {
164
+ if (interactiveMode) {
165
+ return `3. **User Approval:** Obtain user approval for the proposed plan.
156
166
  4. **Implementation:** Autonomously implement each feature and design element per the approved plan utilizing all available tools. When starting ensure you scaffold the application using '${SHELL_TOOL_NAME}' for commands like 'npm init', 'npx create-react-app'. Aim for full scope completion. Proactively create or source necessary placeholder assets (e.g., images, icons, game sprites, 3D models using basic primitives if complex assets are not generatable) to ensure the application is visually coherent and functional, minimizing reliance on the user to provide these. If the model can generate simple assets (e.g., a uniformly colored square sprite, a simple 3D cube), it should do so. Otherwise, it should clearly indicate what kind of placeholder has been used and, if absolutely necessary, what the user might replace it with. Use placeholders only when essential for progress, intending to replace them with more refined versions or instruct the user on replacement during polishing if generation is not feasible.
157
167
  5. **Verify:** Review work against the original request, the approved plan. Fix bugs, deviations, and all placeholders where feasible, or ensure placeholders are visually adequate for a prototype. Ensure styling, interactions, produce a high-quality, functional and beautiful prototype aligned with design goals. Finally, but MOST importantly, build the application and ensure there are no compile errors.
158
- 6. **Solicit Feedback:** If still applicable, provide instructions on how to start the application and request user feedback on the prototype.`,
168
+ 6. **Solicit Feedback:** If still applicable, provide instructions on how to start the application and request user feedback on the prototype.`;
169
+ }
170
+ else {
171
+ return `3. **Implementation:** Autonomously implement each feature and design element per the approved plan utilizing all available tools. When starting ensure you scaffold the application using '${SHELL_TOOL_NAME}' for commands like 'npm init', 'npx create-react-app'. Aim for full scope completion. Proactively create or source necessary placeholder assets (e.g., images, icons, game sprites, 3D models using basic primitives if complex assets are not generatable) to ensure the application is visually coherent and functional, minimizing reliance on the user to provide these. If the model can generate simple assets (e.g., a uniformly colored square sprite, a simple 3D cube), it should do so. Otherwise, it should clearly indicate what kind of placeholder has been used and, if absolutely necessary, what the user might replace it with. Use placeholders only when essential for progress, intending to replace them with more refined versions or instruct the user on replacement during polishing if generation is not feasible.
172
+ 4. **Verify:** Review work against the original request, the approved plan. Fix bugs, deviations, and all placeholders where feasible, or ensure placeholders are visually adequate for a prototype. Ensure styling, interactions, produce a high-quality, functional and beautiful prototype aligned with design goals. Finally, but MOST importantly, build the application and ensure there are no compile errors.`;
173
+ }
174
+ })()}`,
159
175
  operationalGuidelines: `
160
176
  # Operational Guidelines
161
177
  ${(function () {
@@ -179,13 +195,13 @@ IT IS CRITICAL TO FOLLOW THESE GUIDELINES TO AVOID EXCESSIVE TOKEN CONSUMPTION.
179
195
  ## Tone and Style (CLI Interaction)
180
196
  - **Concise & Direct:** Adopt a professional, direct, and concise tone suitable for a CLI environment.
181
197
  - **Minimal Output:** Aim for fewer than 3 lines of text output (excluding tool use/code generation) per response whenever practical. Focus strictly on the user's query.
182
- - **Clarity over Brevity (When Needed):** While conciseness is key, prioritize clarity for essential explanations or when seeking necessary clarification if a request is ambiguous.
183
- ${(function () {
184
- if (useChattySystemPrompt) {
198
+ - **Clarity over Brevity (When Needed):** While conciseness is key, prioritize clarity for essential explanations or when seeking necessary clarification if a request is ambiguous.${(function () {
199
+ if (isGemini3) {
185
200
  return '';
186
201
  }
187
202
  else {
188
- return '- **No Chitchat:** Avoid conversational filler, preambles ("Okay, I will now..."), or postambles ("I have finished the changes..."). Get straight to the action or answer.';
203
+ return `
204
+ - **No Chitchat:** Avoid conversational filler, preambles ("Okay, I will now..."), or postambles ("I have finished the changes..."). Get straight to the action or answer.`;
189
205
  }
190
206
  })()}
191
207
  - **Formatting:** Use GitHub-flavored Markdown. Responses will be rendered in monospace.
@@ -199,16 +215,17 @@ ${(function () {
199
215
  ## Tool Usage
200
216
  - **Parallelism:** Execute multiple independent tool calls in parallel when feasible (i.e. searching the codebase).
201
217
  - **Command Execution:** Use the '${SHELL_TOOL_NAME}' tool for running shell commands, remembering the safety rule to explain modifying commands first.
202
- - **Background Processes:** Use background processes (via \`&\`) for commands that are unlikely to stop on their own, e.g. \`node server.js &\`. If unsure, ask the user.
203
218
  ${(function () {
204
- if (!config.isInteractiveShellEnabled()) {
205
- return `- **Interactive Commands:** Some commands are interactive, meaning they can accept user input during their execution (e.g. ssh, vim). Only execute non-interactive commands. Use non-interactive versions of commands (e.g. \`npm init -y\` instead of \`npm init\`) when available. Interactive shell commands are not supported and may cause hangs until canceled by the user.`;
219
+ if (interactiveMode) {
220
+ return `- **Background Processes:** Use background processes (via \`&\`) for commands that are unlikely to stop on their own, e.g. \`node server.js &\`. If unsure, ask the user.
221
+ - **Interactive Commands:** Prefer non-interactive commands when it makes sense; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`ctrl + f\` to focus into the shell to provide input.`;
206
222
  }
207
223
  else {
208
- return `- **Interactive Commands:** Prefer non-interactive commands when it makes sense; however, some commands are only interactive and expect user input during their execution (e.g. ssh, vim). If you choose to execute an interactive command consider letting the user know they can press \`ctrl + f\` to focus into the shell to provide input.`;
224
+ return `- **Background Processes:** Use background processes (via \`&\`) for commands that are unlikely to stop on their own, e.g. \`node server.js &\`.
225
+ - **Interactive Commands:** Only execute non-interactive commands.`;
209
226
  }
210
227
  })()}
211
- - **Remembering Facts:** Use the '${MEMORY_TOOL_NAME}' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information. If unsure whether to save something, you can ask the user, "Should I remember that for you?"
228
+ - **Remembering Facts:** Use the '${MEMORY_TOOL_NAME}' tool to remember specific, *user-related* facts or preferences when the user explicitly asks, or when they state a clear, concise piece of information that would help personalize or streamline *your future interactions with them* (e.g., preferred coding style, common project paths they use, personal tool aliases). This tool is for user-specific information that should persist across sessions. Do *not* use it for general project context or information.${interactiveMode ? ` If unsure whether to save something, you can ask the user, "Should I remember that for you?"` : ''}
212
229
  - **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
213
230
 
214
231
  ## Interaction Details
@@ -251,8 +268,10 @@ ${(function () {
251
268
  - \`git log -n 3\` to review recent commit messages and match their style (verbosity, formatting, signature line, etc.)
252
269
  - Combine shell commands whenever possible to save time/steps, e.g. \`git status && git diff HEAD && git log -n 3\`.
253
270
  - Always propose a draft commit message. Never just ask the user to give you the full commit message.
254
- - Prefer commit messages that are clear, concise, and focused more on "why" and less on "what".
255
- - Keep the user informed and ask for clarification or confirmation where needed.
271
+ - Prefer commit messages that are clear, concise, and focused more on "why" and less on "what".${interactiveMode
272
+ ? `
273
+ - Keep the user informed and ask for clarification or confirmation where needed.`
274
+ : ''}
256
275
  - After each commit, confirm that it was successful by running \`git status\`.
257
276
  - If a commit fails, never attempt to work around the issues without being asked to do so.
258
277
  - Never push changes to a remote repository without being asked explicitly by the user.
@@ -1 +1 @@
1
- {"version":3,"file":"prompts.js","sourceRoot":"","sources":["../../../src/core/prompts.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,EACL,cAAc,EACd,cAAc,EACd,cAAc,EACd,gBAAgB,EAChB,mBAAmB,EACnB,eAAe,EACf,oBAAoB,EACpB,qBAAqB,GACtB,MAAM,wBAAwB,CAAC;AAChC,OAAO,OAAO,MAAM,cAAc,CAAC;AACnC,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,yBAAyB,EAAE,MAAM,oCAAoC,CAAC;AAE/E,OAAO,EAAE,UAAU,EAAE,M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AC,KAAK,CAAC;QAElC,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAC3D,EAAE,CAAC,aAAa,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;IAC1C,CAAC;IAED,MAAM,YAAY,GAChB,UAAU,IAAI,UAAU,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC;QACxC,CAAC,CAAC,cAAc,UAAU,CAAC,IAAI,EAAE,EAAE;QACnC,CAAC,CAAC,EAAE,CAAC;IAET,OAAO,GAAG,UAAU,GAAG,YAAY,EAAE,CAAC;AACxC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,oBAAoB;IAClC,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwDR,CAAC,IAAI,EAAE,CAAC;AACT,CAAC"}
@@ -11,10 +11,19 @@ import { openBrowserSecurely } from '../utils/secure-browser-launcher.js';
11
11
  import { debugLogger } from '../utils/debugLogger.js';
12
12
  import { getErrorMessage } from '../utils/errors.js';
13
13
  import { ModelNotFoundError } from '../utils/httpErrors.js';
14
- import { TerminalQuotaError } from '../utils/googleQuotaErrors.js';
14
+ import { RetryableQuotaError, TerminalQuotaError, } from '../utils/googleQuotaErrors.js';
15
+ import { buildFallbackPolicyContext, resolvePolicyChain, resolvePolicyAction, } from '../availability/policyHelpers.js';
15
16
  const UPGRADE_URL_PAGE = 'https://goo.gle/set-up-gemini-code-assist';
16
17
  export async function handleFallback(config, failedModel, authType, error) {
17
- // Applicability Checks
18
+ if (config.isModelAvailabilityServiceEnabled()) {
19
+ return handlePolicyDrivenFallback(config, failedModel, authType, error);
20
+ }
21
+ return legacyHandleFallback(config, failedModel, authType, error);
22
+ }
23
+ /**
24
+ * Old fallback logic relying on hard coded strings
25
+ */
26
+ async function legacyHandleFallback(config, failedModel, authType, error) {
18
27
  if (authType !== AuthType.LOGIN_WITH_GOOGLE)
19
28
  return null;
20
29
  // Guardrail: If it's a ModelNotFoundError but NOT the preview model, do not handle it.
@@ -46,34 +55,63 @@ export async function handleFallback(config, failedModel, authType, error) {
46
55
  // Pass the specific failed model to the UI handler.
47
56
  const intent = await fallbackModelHandler(failedModel, fallbackModel, error);
48
57
  // Process Intent and Update State
49
- switch (intent) {
50
- case 'retry_always':
51
- // If the error is non-retryable, e.g. TerminalQuota Error, trigger a regular fallback to flash.
52
- // For all other errors, activate previewModel fallback.
53
- if (shouldActivatePreviewFallback) {
54
- activatePreviewModelFallbackMode(config);
55
- }
56
- else {
57
- activateFallbackMode(config, authType);
58
- }
59
- return true; // Signal retryWithBackoff to continue.
60
- case 'retry_once':
61
- // Just retry this time, do NOT set sticky fallback mode.
62
- return true;
63
- case 'stop':
64
- activateFallbackMode(config, authType);
65
- return false;
66
- case 'retry_later':
67
- return false;
68
- case 'upgrade':
69
- await handleUpgrade();
70
- return false;
71
- default:
72
- throw new Error(`Unexpected fallback intent received from fallbackModelHandler: "${intent}"`);
73
- }
58
+ return await processIntent(config, intent, failedModel, fallbackModel, authType, error);
74
59
  }
75
60
  catch (handlerError) {
76
- debugLogger.error('Fallback UI handler failed:', handlerError);
61
+ console.error('Fallback UI handler failed:', handlerError);
62
+ return null;
63
+ }
64
+ }
65
+ /**
66
+ * New fallback logic using the ModelAvailabilityService
67
+ */
68
+ async function handlePolicyDrivenFallback(config, failedModel, authType, error) {
69
+ if (authType !== AuthType.LOGIN_WITH_GOOGLE) {
70
+ return null;
71
+ }
72
+ const chain = resolvePolicyChain(config);
73
+ const { failedPolicy, candidates } = buildFallbackPolicyContext(chain, failedModel);
74
+ if (!candidates.length) {
75
+ return null;
76
+ }
77
+ const availability = config.getModelAvailabilityService();
78
+ const selection = availability.selectFirstAvailable(candidates.map((policy) => policy.model));
79
+ let lastResortPolicy = candidates.find((policy) => policy.isLastResort);
80
+ if (!lastResortPolicy) {
81
+ debugLogger.warn('No isLastResort policy found in candidates, using last candidate as fallback.');
82
+ lastResortPolicy = candidates[candidates.length - 1];
83
+ }
84
+ const fallbackModel = selection.selectedModel ?? lastResortPolicy.model;
85
+ const selectedPolicy = candidates.find((policy) => policy.model === fallbackModel) ??
86
+ lastResortPolicy;
87
+ if (!fallbackModel || fallbackModel === failedModel) {
88
+ return null;
89
+ }
90
+ const failureKind = classifyFailureKind(error);
91
+ const action = resolvePolicyAction(failureKind, selectedPolicy);
92
+ if (action === 'silent') {
93
+ return processIntent(config, 'retry_always', failedModel, fallbackModel, authType, error);
94
+ }
95
+ // This will be used in the future when FallbackRecommendation is passed through UI
96
+ const recommendation = {
97
+ ...selection,
98
+ selectedModel: fallbackModel,
99
+ action,
100
+ failureKind,
101
+ failedPolicy,
102
+ selectedPolicy,
103
+ };
104
+ void recommendation;
105
+ const handler = config.getFallbackModelHandler();
106
+ if (typeof handler !== 'function') {
107
+ return null;
108
+ }
109
+ try {
110
+ const intent = await handler(failedModel, fallbackModel, error);
111
+ return await processIntent(config, intent, failedModel, fallbackModel, authType);
112
+ }
113
+ catch (handlerError) {
114
+ debugLogger.error('Fallback handler failed:', handlerError);
77
115
  return null;
78
116
  }
79
117
  }
@@ -85,6 +123,33 @@ async function handleUpgrade() {
85
123
  debugLogger.warn('Failed to open browser automatically:', getErrorMessage(error));
86
124
  }
87
125
  }
126
+ async function processIntent(config, intent, failedModel, fallbackModel, authType, error) {
127
+ switch (intent) {
128
+ case 'retry_always':
129
+ // If the error is non-retryable, e.g. TerminalQuota Error, trigger a regular fallback to flash.
130
+ // For all other errors, activate previewModel fallback.
131
+ if (failedModel === PREVIEW_GEMINI_MODEL &&
132
+ !(error instanceof TerminalQuotaError)) {
133
+ activatePreviewModelFallbackMode(config);
134
+ }
135
+ else {
136
+ activateFallbackMode(config, authType);
137
+ }
138
+ return true;
139
+ case 'retry_once':
140
+ return true;
141
+ case 'stop':
142
+ activateFallbackMode(config, authType);
143
+ return false;
144
+ case 'retry_later':
145
+ return false;
146
+ case 'upgrade':
147
+ await handleUpgrade();
148
+ return false;
149
+ default:
150
+ throw new Error(`Unexpected fallback intent received from fallbackModelHandler: "${intent}"`);
151
+ }
152
+ }
88
153
  function activateFallbackMode(config, authType) {
89
154
  if (!config.isInFallbackMode()) {
90
155
  config.setFallbackMode(true);
@@ -100,4 +165,16 @@ function activatePreviewModelFallbackMode(config) {
100
165
  // We might want a specific event for Preview Model fallback, but for now we just set the mode.
101
166
  }
102
167
  }
168
+ function classifyFailureKind(error) {
169
+ if (error instanceof TerminalQuotaError) {
170
+ return 'terminal';
171
+ }
172
+ if (error instanceof RetryableQuotaError) {
173
+ return 'transient';
174
+ }
175
+ if (error instanceof ModelNotFoundError) {
176
+ return 'not_found';
177
+ }
178
+ return 'unknown';
179
+ }
103
180
  //# sourceMappingURL=handler.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"handler.js","sourceRoot":"","sources":["../../../src/fallback/handler.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,0BAA0B,EAC1B,oBAAoB,EACpB,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC7E,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,mBAAmB,EAAE,MAAM,qCAAqC,CAAC;AAC1E,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAEnE,MAAM,gBAAgB,GAAG,2CAA2C,CAAC;AAErE,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,MAAc,EACd,WAAmB,EACnB,QAA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E,CAAC;QACxC,OAAO,WAAW,CAAC;IACrB,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC"}
@@ -9,6 +9,11 @@ import { AuthType } from '../core/contentGenerator.js';
9
9
  import { DEFAULT_GEMINI_FLASH_MODEL, DEFAULT_GEMINI_MODEL, PREVIEW_GEMINI_MODEL, } from '../config/models.js';
10
10
  import { logFlashFallback } from '../telemetry/index.js';
11
11
  import { ModelNotFoundError } from '../utils/httpErrors.js';
12
+ import { openBrowserSecurely } from '../utils/secure-browser-launcher.js';
13
+ import { coreEvents } from '../utils/events.js';
14
+ import { debugLogger } from '../utils/debugLogger.js';
15
+ import * as policyHelpers from '../availability/policyHelpers.js';
16
+ import { createDefaultPolicy } from '../availability/policyCatalog.js';
12
17
  import { RetryableQuotaError, TerminalQuotaError, } from '../utils/googleQuotaErrors.js';
13
18
  // Mock the telemetry logger and event class
14
19
  vi.mock('../telemetry/index.js', () => ({
@@ -16,19 +21,38 @@ vi.mock('../telemetry/index.js', () => ({
16
21
  FlashFallbackEvent: class {
17
22
  },
18
23
  }));
24
+ vi.mock('../utils/secure-browser-launcher.js', () => ({
25
+ openBrowserSecurely: vi.fn(),
26
+ }));
19
27
  const MOCK_PRO_MODEL = DEFAULT_GEMINI_MODEL;
20
28
  const FALLBACK_MODEL = DEFAULT_GEMINI_FLASH_MODEL;
21
29
  const AUTH_OAUTH = AuthType.LOGIN_WITH_GOOGLE;
22
30
  const AUTH_API_KEY = AuthType.USE_GEMINI;
31
+ function createAvailabilityMock(result) {
32
+ return {
33
+ markTerminal: vi.fn(),
34
+ markHealthy: vi.fn(),
35
+ markRetryOncePerTurn: vi.fn(),
36
+ consumeStickyAttempt: vi.fn(),
37
+ snapshot: vi.fn(),
38
+ selectFirstAvailable: vi.fn().mockReturnValue(result),
39
+ resetTurn: vi.fn(),
40
+ };
41
+ }
23
42
  const createMockConfig = (overrides = {}) => ({
24
43
  isInFallbackMode: vi.fn(() => false),
25
44
  setFallbackMode: vi.fn(),
45
+ isModelAvailabilityServiceEnabled: vi.fn(() => false),
26
46
  isPreviewModelFallbackMode: vi.fn(() => false),
27
47
  setPreviewModelFallbackMode: vi.fn(),
28
48
  isPreviewModelBypassMode: vi.fn(() => false),
29
49
  setPreviewModelBypassMode: vi.fn(),
30
50
  fallbackHandler: undefined,
31
51
  getFallbackModelHandler: vi.fn(),
52
+ getModelAvailabilityService: vi.fn(() => createAvailabilityMock({ selectedModel: FALLBACK_MODEL, skipped: [] })),
53
+ getModel: vi.fn(() => MOCK_PRO_MODEL),
54
+ getPreviewFeatures: vi.fn(() => false),
55
+ getUserTier: vi.fn(() => undefined),
32
56
  isInteractive: vi.fn(() => false),
33
57
  ...overrides,
34
58
  });
@@ -36,6 +60,7 @@ describe('handleFallback', () => {
36
60
  let mockConfig;
37
61
  let mockHandler;
38
62
  let consoleErrorSpy;
63
+ let fallbackEventSpy;
39
64
  beforeEach(() => {
40
65
  vi.clearAllMocks();
41
66
  mockHandler = vi.fn();
@@ -44,9 +69,11 @@ describe('handleFallback', () => {
44
69
  fallbackModelHandler: mockHandler,
45
70
  });
46
71
  consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => { });
72
+ fallbackEventSpy = vi.spyOn(coreEvents, 'emitFallbackModeChanged');
47
73
  });
48
74
  afterEach(() => {
49
75
  consoleErrorSpy.mockRestore();
76
+ fallbackEventSpy.mockRestore();
50
77
  });
51
78
  it('should return null immediately if authType is not OAuth', async () => {
52
79
  const result = await handleFallback(mockConfig, MOCK_PRO_MODEL, AUTH_API_KEY);
@@ -86,6 +113,39 @@ describe('handleFallback', () => {
86
113
  expect(logFlashFallback).toHaveBeenCalled();
87
114
  });
88
115
  });
116
+ it('should return false without toggling fallback when handler returns "retry_later"', async () => {
117
+ mockHandler.mockResolvedValue('retry_later');
118
+ const result = await handleFallback(mockConfig, MOCK_PRO_MODEL, AUTH_OAUTH);
119
+ expect(result).toBe(false);
120
+ expect(mockConfig.setFallbackMode).not.toHaveBeenCalled();
121
+ expect(logFlashFallback).not.toHaveBeenCalled();
122
+ expect(fallbackEventSpy).not.toHaveBeenCalled();
123
+ });
124
+ it('should launch upgrade flow and avoid fallback mode when handler returns "upgrade"', async () => {
125
+ mockHandler.mockResolvedValue('upgrade');
126
+ vi.mocked(openBrowserSecurely).mockResolvedValue(undefined);
127
+ const result = await handleFallback(mockConfig, MOCK_PRO_MODEL, AUTH_OAUTH);
128
+ expect(result).toBe(false);
129
+ expect(openBrowserSecurely).toHaveBeenCalledWith('https://goo.gle/set-up-gemini-code-assist');
130
+ expect(mockConfig.setFallbackMode).not.toHaveBeenCalled();
131
+ expect(logFlashFallback).not.toHaveBeenCalled();
132
+ expect(fallbackEventSpy).not.toHaveBeenCalled();
133
+ });
134
+ it('should log a warning and continue when upgrade flow fails to open a browser', async () => {
135
+ mockHandler.mockResolvedValue('upgrade');
136
+ const debugWarnSpy = vi.spyOn(debugLogger, 'warn');
137
+ const consoleWarnSpy = vi
138
+ .spyOn(console, 'warn')
139
+ .mockImplementation(() => { });
140
+ vi.mocked(openBrowserSecurely).mockRejectedValue(new Error('blocked'));
141
+ const result = await handleFallback(mockConfig, MOCK_PRO_MODEL, AUTH_OAUTH);
142
+ expect(result).toBe(false);
143
+ expect(debugWarnSpy).toHaveBeenCalledWith('Failed to open browser automatically:', 'blocked');
144
+ expect(mockConfig.setFallbackMode).not.toHaveBeenCalled();
145
+ expect(fallbackEventSpy).not.toHaveBeenCalled();
146
+ debugWarnSpy.mockRestore();
147
+ consoleWarnSpy.mockRestore();
148
+ });
89
149
  describe('when handler returns an unexpected value', () => {
90
150
  it('should log an error and return null', async () => {
91
151
  mockHandler.mockResolvedValue(null);
@@ -241,5 +301,90 @@ describe('handleFallback', () => {
241
301
  expect(result).toBe(true);
242
302
  expect(mockHandler).toHaveBeenCalled();
243
303
  });
304
+ describe('policy-driven flow', () => {
305
+ let policyConfig;
306
+ let availability;
307
+ let policyHandler;
308
+ beforeEach(() => {
309
+ vi.clearAllMocks();
310
+ availability = createAvailabilityMock({
311
+ selectedModel: 'gemini-1.5-flash',
312
+ skipped: [],
313
+ });
314
+ policyHandler = vi.fn().mockResolvedValue('retry_once');
315
+ policyConfig = createMockConfig();
316
+ vi.spyOn(policyConfig, 'isModelAvailabilityServiceEnabled').mockReturnValue(true);
317
+ vi.spyOn(policyConfig, 'getModelAvailabilityService').mockReturnValue(availability);
318
+ vi.spyOn(policyConfig, 'getFallbackModelHandler').mockReturnValue(policyHandler);
319
+ });
320
+ it('uses availability selection when enabled', async () => {
321
+ await handleFallback(policyConfig, MOCK_PRO_MODEL, AUTH_OAUTH);
322
+ expect(availability.selectFirstAvailable).toHaveBeenCalled();
323
+ });
324
+ it('falls back to last resort when availability returns null', async () => {
325
+ availability.selectFirstAvailable = vi
326
+ .fn()
327
+ .mockReturnValue({ selectedModel: null, skipped: [] });
328
+ policyHandler.mockResolvedValue('retry_once');
329
+ await handleFallback(policyConfig, MOCK_PRO_MODEL, AUTH_OAUTH);
330
+ expect(policyHandler).toHaveBeenCalledWith(MOCK_PRO_MODEL, DEFAULT_GEMINI_FLASH_MODEL, undefined);
331
+ });
332
+ it('executes silent policy action without invoking UI handler', async () => {
333
+ const proPolicy = createDefaultPolicy(MOCK_PRO_MODEL);
334
+ const flashPolicy = createDefaultPolicy(DEFAULT_GEMINI_FLASH_MODEL);
335
+ flashPolicy.actions = {
336
+ ...flashPolicy.actions,
337
+ terminal: 'silent',
338
+ unknown: 'silent',
339
+ };
340
+ flashPolicy.isLastResort = true;
341
+ const silentChain = [proPolicy, flashPolicy];
342
+ const chainSpy = vi
343
+ .spyOn(policyHelpers, 'resolvePolicyChain')
344
+ .mockReturnValue(silentChain);
345
+ try {
346
+ availability.selectFirstAvailable = vi.fn().mockReturnValue({
347
+ selectedModel: DEFAULT_GEMINI_FLASH_MODEL,
348
+ skipped: [],
349
+ });
350
+ const result = await handleFallback(policyConfig, MOCK_PRO_MODEL, AUTH_OAUTH);
351
+ expect(result).toBe(true);
352
+ expect(policyConfig.getFallbackModelHandler).not.toHaveBeenCalled();
353
+ expect(policyConfig.setFallbackMode).toHaveBeenCalledWith(true);
354
+ }
355
+ finally {
356
+ chainSpy.mockRestore();
357
+ }
358
+ });
359
+ it('logs and returns null when handler resolves to null', async () => {
360
+ policyHandler.mockResolvedValue(null);
361
+ const debugLoggerErrorSpy = vi.spyOn(debugLogger, 'error');
362
+ const result = await handleFallback(policyConfig, MOCK_PRO_MODEL, AUTH_OAUTH);
363
+ expect(result).toBeNull();
364
+ expect(debugLoggerErrorSpy).toHaveBeenCalledWith('Fallback handler failed:', new Error('Unexpected fallback intent received from fallbackModelHandler: "null"'));
365
+ debugLoggerErrorSpy.mockRestore();
366
+ });
367
+ it('successfully follows expected availability response for Preview Chain', async () => {
368
+ availability.selectFirstAvailable = vi
369
+ .fn()
370
+ .mockReturnValue({ selectedModel: DEFAULT_GEMINI_MODEL, skipped: [] });
371
+ policyHandler.mockResolvedValue('retry_once');
372
+ vi.spyOn(policyConfig, 'getPreviewFeatures').mockReturnValue(true);
373
+ vi.spyOn(policyConfig, 'getModel').mockReturnValue(PREVIEW_GEMINI_MODEL);
374
+ const result = await handleFallback(policyConfig, PREVIEW_GEMINI_MODEL, AUTH_OAUTH);
375
+ expect(result).toBe(true);
376
+ expect(availability.selectFirstAvailable).toHaveBeenCalledWith([
377
+ DEFAULT_GEMINI_MODEL,
378
+ DEFAULT_GEMINI_FLASH_MODEL,
379
+ ]);
380
+ expect(policyHandler).toHaveBeenCalledWith(PREVIEW_GEMINI_MODEL, DEFAULT_GEMINI_MODEL, undefined);
381
+ });
382
+ it('short-circuits when the failed model is already the last-resort policy', async () => {
383
+ const result = await handleFallback(policyConfig, DEFAULT_GEMINI_FLASH_MODEL, AUTH_OAUTH);
384
+ expect(result).toBeNull();
385
+ expect(policyConfig.getModelAvailabilityService).not.toHaveBeenCalled();
386
+ expect(policyConfig.getFallbackModelHandler).not.toHaveBeenCalled();
387
+ });
388
+ });
244
389
  });
245
390
  //# sourceMappingURL=handler.test.js.map