Compare commits

...

24 Commits

Author SHA1 Message Date
Coco Sheng ad5e01ceaf perf: batch label updates to improve efficiency and reduce audit log noise 2026-05-21 11:37:42 -04:00
Coco Sheng 957195be4c fix: restrict triage to issues only and remove PR write access 2026-05-20 17:29:52 -04:00
Coco Sheng ca91aab74e fix: add pull-requests write permission for triage workflow 2026-05-20 17:24:50 -04:00
Coco Sheng 651ad55357 fix: exclude label changes from meaningful activity check 2026-05-20 17:22:33 -04:00
Coco Sheng fc8c1bee0c fix: ignore bot activity when checking for meaningful issue interaction 2026-05-20 17:20:19 -04:00
Coco Sheng ac81288e1e chore: clarify dry run status in lifecycle manager logs 2026-05-20 17:17:48 -04:00
Coco Sheng 6cfef6d15d chore: remove accidental debugging limit 2026-05-20 17:10:15 -04:00
Coco Sheng ccd1854c66 temp: limit 2 for ci test 2026-05-14 18:26:56 -04:00
Coco Sheng 3fdc43734b ci: robust stale issue lifecycle and consolidated triage bot labels 2026-05-14 17:02:08 -04:00
Tommaso Sciortino 74e9079e5b chore: add execution permission to scripts/review.sh (#27009) 2026-05-13 12:22:00 -07:00
AK 9da30b8831 fix(core): isolate subagent thread context (#26449) 2026-05-13 18:55:17 +00:00
Dev Randalpura 71a2c0264e fix(ui): clamped table column widths (#26991)
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-05-13 18:43:49 +00:00
Sahil Kirad fd01cc03bf fix(core): refresh MCP OAuth token usage after re-auth (#26312)
Co-authored-by: Tommaso Sciortino <sciortino@gmail.com>
2026-05-13 12:01:27 -07:00
Coco Sheng fc4054446f ci: suppress bot comments during standard triage maintenance (#27006) 2026-05-13 18:43:07 +00:00
Coco Sheng 08abe4542d fix(cli): auto-approve shell redirections in AUTO_EDIT mode (#27003) 2026-05-13 18:28:30 +00:00
Coco Sheng 63b4bbfb5d fix(core): handle EISDIR on virtual drives in memory discovery (#26985) 2026-05-13 17:41:49 +00:00
Coco Sheng 1e7063bb0b fix(cli): allow keychain auth for --list-sessions and non-interactive mode (#26921) 2026-05-13 17:35:21 +00:00
Coco Sheng 297d3a3067 fix(core): preserve OAuth refresh tokens during rotation and retrieval (#26924) 2026-05-13 17:19:05 +00:00
David Pierce 749657cbf9 feat(cli): merge Auto modes into a single Auto mode (#26714) 2026-05-13 16:55:43 +00:00
Adam Weidman 8cda688fe2 feat(core): change agent registration to first-wins and prioritize project (#26953) 2026-05-13 01:33:12 +00:00
gemini-cli-robot 5ee05c775e Changelog for v0.43.0-preview.0 (#26959)
Co-authored-by: gemini-cli-robot <224641728+gemini-cli-robot@users.noreply.github.com>
2026-05-13 00:01:24 +00:00
mahadevan 31d5947d37 Refactor: Eliminate no-unsafe-return suppressions via strict type validation (#20668)
Signed-off-by: M-DEV-1 <mahadevankizhakkedathu@gmail.com>
Co-authored-by: Tommaso Sciortino <sciortino@gmail.com>
2026-05-12 23:45:58 +00:00
gemini-cli-robot 8f03aa320e Changelog for v0.42.0 (#26958)
Co-authored-by: gemini-cli-robot <224641728+gemini-cli-robot@users.noreply.github.com>
2026-05-12 22:54:14 +00:00
gemini-cli-robot 583839ba46 chore(release): bump version to 0.44.0-nightly.20260512.g022e8baef (#26957) 2026-05-12 22:44:04 +00:00
90 changed files with 2353 additions and 1177 deletions
+161 -128
View File
@@ -5,131 +5,178 @@
*/
module.exports = async ({ github, context, core }) => {
const rawLabels = process.env.LABELS_OUTPUT;
core.info(`Raw labels JSON: ${rawLabels}`);
let parsedLabels;
try {
// First, try to parse the raw output as JSON.
parsedLabels = JSON.parse(rawLabels);
} catch (jsonError) {
// If that fails, check for a markdown code block.
core.warning(
`Direct JSON parsing failed: ${jsonError.message}. Trying to extract from a markdown block.`,
);
const jsonMatch = rawLabels.match(/```json\s*([\s\S]*?)\s*```/);
if (jsonMatch && jsonMatch[1]) {
try {
parsedLabels = JSON.parse(jsonMatch[1].trim());
} catch (markdownError) {
core.setFailed(
`Failed to parse JSON even after extracting from markdown block: ${markdownError.message}\nRaw output: ${rawLabels}`,
);
return;
const extractJson = (raw) => {
if (!raw || raw === '[]' || raw === '') return [];
try {
// First, try to parse the raw output as JSON.
return JSON.parse(raw);
} catch (jsonError) {
// If that fails, check for a markdown code block.
core.info('Direct JSON parsing failed. Trying to extract from a markdown block.');
const jsonMatch = raw.match(/```json\s*([\s\S]*?)\s*```/);
if (jsonMatch && jsonMatch[1]) {
try {
return JSON.parse(jsonMatch[1].trim());
} catch (markdownError) {
core.warning(`Failed to parse extracted JSON from markdown block: ${markdownError.message}`);
}
}
} else {
// If no markdown block, try to find a raw JSON array in the output.
// The CLI may include debug/log lines (e.g. telemetry init, YOLO mode)
// before the actual JSON response.
const jsonArrayMatch = rawLabels.match(
/\[\s*\{\s*"issue_number"[\s\S]*\}\s*\]/,
);
// Try to find a raw JSON array in the output.
const jsonArrayMatch = raw.match(/\[\s*\{\s*"issue_number"[\s\S]*\}\s*\]/);
if (jsonArrayMatch) {
try {
parsedLabels = JSON.parse(jsonArrayMatch[0]);
return JSON.parse(jsonArrayMatch[0]);
} catch (extractError) {
// It's possible the regex matched from a `[STARTUP]` log all the way to the end
// of the JSON array. We need to be more aggressive and find the FIRST `[ { "issue_number"`
core.warning(
`Strict array match failed: ${extractError.message}. Attempting to clean leading noisy brackets.`,
);
const fallbackMatch = rawLabels.match(
/(\[\s*\{\s*"issue_number"[\s\S]*)/,
);
const fallbackMatch = raw.match(/(\[\s*\{\s*"issue_number"[\s\S]*)/);
if (fallbackMatch) {
try {
// We might have grabbed trailing noise too, so we find the last closing bracket
const cleaned = fallbackMatch[0].substring(
0,
fallbackMatch[0].lastIndexOf(']') + 1,
);
parsedLabels = JSON.parse(cleaned);
const cleaned = fallbackMatch[0].substring(0, fallbackMatch[0].lastIndexOf(']') + 1);
return JSON.parse(cleaned);
} catch (fallbackError) {
core.setFailed(
`Found JSON-like content but failed to parse: ${fallbackError.message}\nRaw output: ${rawLabels}`,
);
return;
core.warning(`Failed to parse extracted JSON using fallback regex: ${fallbackError.message}`);
}
} else {
core.setFailed(
`Found JSON-like content but failed to parse: ${extractError.message}\nRaw output: ${rawLabels}`,
);
return;
}
}
} else {
core.setFailed(
`Output is not valid JSON and does not contain extractable JSON.\nRaw output: ${rawLabels}`,
);
return;
}
}
}
core.info(`Parsed labels JSON: ${JSON.stringify(parsedLabels)}`);
core.warning('No valid JSON could be extracted from input.');
return [];
};
for (const entry of parsedLabels) {
const issueNumber = entry.issue_number;
if (!issueNumber) {
core.info(
`Skipping entry with no issue number: ${JSON.stringify(entry)}`,
);
continue;
// Collect all outputs from environment variables
// Prioritize EFFORT results over STANDARD results by processing Effort FIRST
// so that its labels appear first in the merged arrays (and thus win in mutually exclusive logic)
const effortRaw = process.env.LABELS_OUTPUT_EFFORT;
const standardRaw = process.env.LABELS_OUTPUT_STANDARD;
const genericRaw = process.env.LABELS_OUTPUT;
const resultsByIssue = new Map();
const processResults = (results, sourceName) => {
for (const entry of results) {
const issueNumber = entry.issue_number;
if (!issueNumber) continue;
if (!resultsByIssue.has(issueNumber)) {
resultsByIssue.set(issueNumber, {
issue_number: issueNumber,
labels_to_add: [...(entry.labels_to_add || [])],
labels_to_remove: [...(entry.labels_to_remove || [])],
explanation: entry.explanation || '',
effort_analysis: entry.effort_analysis || '',
});
} else {
const existing = resultsByIssue.get(issueNumber);
// Combine labels
existing.labels_to_add = [...new Set([...existing.labels_to_add, ...(entry.labels_to_add || [])])];
existing.labels_to_remove = [...new Set([...existing.labels_to_remove, ...(entry.labels_to_remove || [])])];
// Combine explanations (if different)
if (entry.explanation && !existing.explanation.includes(entry.explanation)) {
existing.explanation = existing.explanation
? `${existing.explanation}\n\n${entry.explanation}`
: entry.explanation;
}
// Take effort analysis if present
if (entry.effort_analysis && !existing.effort_analysis) {
existing.effort_analysis = entry.effort_analysis;
}
}
}
};
// Order matters: Effort first so its labels win in conflict resolution
processResults(extractJson(effortRaw), 'EFFORT');
processResults(extractJson(standardRaw), 'STANDARD');
processResults(extractJson(genericRaw), 'GENERIC');
const finalResults = Array.from(resultsByIssue.values());
core.info(`Aggregated triage results for ${finalResults.length} issues.`);
for (const entry of finalResults) {
const issueNumber = entry.issue_number;
let labelsToAdd = entry.labels_to_add || [];
let labelsToRemove = entry.labels_to_remove || [];
let existingLabels = [];
// Fetch existing labels early
try {
const { data: issueData } = await github.rest.issues.get({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
});
existingLabels = issueData.labels.map((l) =>
typeof l === 'string' ? l : l.name,
);
} catch (e) {
core.warning(
`Failed to fetch existing labels for #${issueNumber}: ${e.message}`,
);
}
// Programmatic Priority Downgrade Logic
if (labelsToAdd.includes('status/need-information')) {
const targetPriority = labelsToAdd.find((l) => l.startsWith('priority/'));
if (targetPriority) {
let downgradedPriority = null;
if (targetPriority === 'priority/p0') downgradedPriority = 'priority/p1';
if (targetPriority === 'priority/p1') downgradedPriority = 'priority/p2';
if (downgradedPriority) {
core.info(`Programmatically downgrading ${targetPriority} to ${downgradedPriority} due to status/need-information`);
labelsToAdd = labelsToAdd.filter((l) => l !== targetPriority);
labelsToAdd.push(downgradedPriority);
}
}
}
labelsToRemove.push('status/need-triage');
if (labelsToAdd.includes('status/manual-triage')) {
// If the AI flagged it for manual triage, remove bot-triaged if it exists
if (
labelsToAdd.includes('status/manual-triage') ||
existingLabels.includes('status/manual-triage')
) {
labelsToRemove.push('status/bot-triaged');
// Ensure we don't accidentally try to add bot-triaged if the AI returned it
labelsToAdd = labelsToAdd.filter((l) => l !== 'status/bot-triaged');
} else {
// Standard successful bot triage
labelsToAdd.push('status/bot-triaged');
}
// Deduplicate arrays
labelsToAdd = [...new Set(labelsToAdd)];
labelsToRemove = [...new Set(labelsToRemove)];
// Enforce mutually exclusive area labels
const areaLabelsToAdd = labelsToAdd.filter((l) => l.startsWith('area/'));
if (areaLabelsToAdd.length > 1) {
core.warning(
`Issue #${issueNumber} has multiple area labels to add: ${areaLabelsToAdd.join(', ')}. Keeping only the first one.`,
);
const firstArea = areaLabelsToAdd[0];
labelsToAdd = labelsToAdd.filter(
(l) => !l.startsWith('area/') || l === firstArea,
);
// Resolve internal conflicts (e.g., adding P1 and P2)
// We already resolved these by putting Effort first in the combined list
// Resolve external conflicts with existing labels
if (labelsToAdd.some((l) => l.startsWith('area/'))) {
labelsToRemove.push(...existingLabels.filter((l) => l.startsWith('area/')));
}
if (labelsToAdd.some((l) => l.startsWith('priority/'))) {
labelsToRemove.push(...existingLabels.filter((l) => l.startsWith('priority/')));
}
if (labelsToAdd.some((l) => l.startsWith('kind/'))) {
labelsToRemove.push(...existingLabels.filter((l) => l.startsWith('kind/')));
}
// Enforce mutually exclusive priority labels
const priorityLabelsToAdd = labelsToAdd.filter((l) =>
l.startsWith('priority/'),
// Enforce mutual exclusivity in the TO-ADD list (Architect wins)
const exclusivePrefixes = ['area/', 'priority/', 'kind/'];
for (const prefix of exclusivePrefixes) {
const filtered = labelsToAdd.filter(l => l.startsWith(prefix));
if (filtered.length > 1) {
const winner = filtered[0]; // First one wins
core.info(`Issue #${issueNumber} has multiple ${prefix} labels suggested. Keeping "${winner}" and discarding others.`);
labelsToAdd = labelsToAdd.filter(l => !l.startsWith(prefix) || l === winner);
}
}
// Final deduplication and cleanup
labelsToRemove = [...new Set(labelsToRemove)].filter(
(l) => !labelsToAdd.includes(l) && existingLabels.includes(l),
);
if (priorityLabelsToAdd.length > 1) {
core.warning(
`Issue #${issueNumber} has multiple priority labels to add: ${priorityLabelsToAdd.join(', ')}. Keeping only the first one.`,
);
const firstPriority = priorityLabelsToAdd[0];
labelsToAdd = labelsToAdd.filter(
(l) => !l.startsWith('priority/') || l === firstPriority,
);
}
labelsToAdd = [...new Set(labelsToAdd)].filter((l) => !existingLabels.includes(l));
// Batch label operations
if (labelsToAdd.length > 0) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
@@ -137,11 +184,7 @@ module.exports = async ({ github, context, core }) => {
issue_number: issueNumber,
labels: labelsToAdd,
});
const explanation = entry.explanation ? ` - ${entry.explanation}` : '';
core.info(
`Successfully added labels for #${issueNumber}: ${labelsToAdd.join(', ')}${explanation}`,
);
core.info(`Successfully added labels for #${issueNumber}: ${labelsToAdd.join(', ')}`);
}
if (labelsToRemove.length > 0) {
@@ -154,43 +197,33 @@ module.exports = async ({ github, context, core }) => {
name: label,
});
} catch (e) {
if (e.status !== 404) {
core.warning(
`Failed to remove label ${label} from #${issueNumber}: ${e.message}`,
);
}
if (e.status !== 404) core.warning(`Failed to remove label ${label} from #${issueNumber}: ${e.message}`);
}
}
core.info(
`Successfully removed labels for #${issueNumber}: ${labelsToRemove.join(', ')}`,
);
core.info(`Successfully removed labels for #${issueNumber}: ${labelsToRemove.join(', ')}`);
}
if (entry.explanation || entry.effort_analysis) {
// Post comment if needed
const needsInfoAdded = labelsToAdd.includes('status/need-information') && !existingLabels.includes('status/need-information');
const hasEffortAnalysis = !!entry.effort_analysis;
if (needsInfoAdded || hasEffortAnalysis) {
let commentBody = '';
if (entry.explanation) {
commentBody += entry.explanation;
}
if (entry.effort_analysis) {
if (needsInfoAdded && entry.explanation) commentBody += entry.explanation;
if (hasEffortAnalysis) {
if (commentBody) commentBody += '\n\n';
commentBody += `**Effort Analysis:**\n${entry.effort_analysis}`;
}
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
body: commentBody,
});
}
if (
(!entry.labels_to_add || entry.labels_to_add.length === 0) &&
(!entry.labels_to_remove || entry.labels_to_remove.length === 0)
) {
core.info(
`No labels to add or remove for #${issueNumber}, leaving as is`,
);
if (commentBody) {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
body: commentBody,
});
core.info(`Posted required comment for #${issueNumber}`);
}
}
}
};
+36 -12
View File
@@ -22,29 +22,53 @@ module.exports = async ({ github, context, core }) => {
for (const issue of issuesToCleanup) {
try {
await github.rest.issues.removeLabel({
const { data: issueData } = await github.rest.issues.get({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
name: 'status/need-triage',
});
core.info(
`Successfully removed status/need-triage from #${issue.number}`,
const labels = issueData.labels.map((l) =>
typeof l === 'string' ? l : l.name,
);
} catch (error) {
if (error.status === 404) {
if (
labels.includes('status/bot-triaged') &&
labels.includes('status/need-triage')
) {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
name: 'status/need-triage',
});
core.info(
`Label status/need-triage not found on #${issue.number}, skipping.`,
);
} else {
core.warning(
`Failed to remove label from #${issue.number}: ${error.message}`,
`Successfully removed status/need-triage from #${issue.number}`,
);
}
if (
labels.includes('status/bot-triaged') &&
labels.includes('status/manual-triage')
) {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
name: 'status/bot-triaged',
});
core.info(
`Successfully removed status/bot-triaged from #${issue.number} because it requires manual triage`,
);
}
} catch (error) {
core.warning(
`Failed to clean up labels for #${issue.number}: ${error.message}`,
);
}
}
core.info(
`Cleaned up status/need-triage from ${issuesToCleanup.length} issues.`,
`Cleaned up conflicting labels from ${issuesToCleanup.length} issues.`,
);
};
@@ -1,60 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
const fs = require('node:fs');
module.exports = async ({ github, context, core }) => {
core.info('Fetching open issues to check for conflicting labels...');
const issues = await github.paginate(github.rest.issues.listForRepo, {
owner: context.repo.owner,
repo: context.repo.repo,
state: 'open',
per_page: 100,
});
const conflictingLabelIssues = [];
for (const issue of issues) {
if (issue.pull_request) continue;
const areaLabels = issue.labels
.filter((l) => l.name && l.name.startsWith('area/'))
.map((l) => l.name);
const priorityLabels = issue.labels
.filter((l) => l.name && l.name.startsWith('priority/'))
.map((l) => l.name);
if (areaLabels.length > 1 || priorityLabels.length > 1) {
let message = `Issue #${issue.number} has conflicting labels:`;
if (areaLabels.length > 1)
message += ` multiple areas (${areaLabels.join(', ')}).`;
if (priorityLabels.length > 1)
message += ` multiple priorities (${priorityLabels.join(', ')}).`;
core.info(message);
conflictingLabelIssues.push({
number: issue.number,
title: issue.title,
body: issue.body || '',
});
}
}
// Limit to 50 to avoid overwhelming the AI in a single run
const issuesToProcess = conflictingLabelIssues.slice(0, 50);
fs.writeFileSync(
'conflicting_labels_issues.json',
JSON.stringify(issuesToProcess, null, 2),
);
core.info(
`Found ${conflictingLabelIssues.length} issues with conflicting labels. Wrote ${issuesToProcess.length} to conflicting_labels_issues.json`,
);
};
+142 -30
View File
@@ -16,6 +16,8 @@ module.exports = async ({ github, context, core }) => {
const owner = context.repo.owner;
const repo = context.repo.repo;
core.info(`Running in ${dryRun ? 'DRY RUN' : 'PRODUCTION'} mode.`);
const STALE_LABEL = 'stale';
const NEED_INFO_LABEL = 'status/need-information';
const EXEMPT_LABELS = [
@@ -79,14 +81,16 @@ module.exports = async ({ github, context, core }) => {
async function processItems(query, callback) {
core.info(`Searching: ${query}`);
try {
const response = await github.rest.search.issuesAndPullRequests({
q: query,
per_page: 100,
sort: 'updated',
order: 'asc',
});
const items = response.data.items;
core.info(`Found ${items.length} items (batch limited).`);
let items = await github.paginate(
github.rest.search.issuesAndPullRequests,
{
q: query,
per_page: 100,
sort: 'updated',
order: 'asc',
},
);
core.info(`Found ${items.length} items.`);
for (const item of items) {
try {
await callback(item);
@@ -114,16 +118,21 @@ module.exports = async ({ github, context, core }) => {
per_page: 5,
});
// Check if the last comment is from a non-maintainer
// Check if the last comment is from a non-maintainer and not a bot
const lastComment = comments[0];
if (
lastComment &&
lastComment.user?.type !== 'Bot' &&
!(await isMaintainer(lastComment.user, lastComment.author_association))
) {
core.info(
`Removing ${NEED_INFO_LABEL} from #${item.number} due to contributor response.`,
);
if (!dryRun) {
if (dryRun) {
core.info(
`[DRY RUN] Would remove ${NEED_INFO_LABEL} from #${item.number} due to contributor response.`,
);
} else {
core.info(
`Removing ${NEED_INFO_LABEL} from #${item.number} due to contributor response.`,
);
await github.rest.issues
.removeLabel({
owner,
@@ -141,10 +150,14 @@ module.exports = async ({ github, context, core }) => {
await processItems(
`repo:${owner}/${repo} is:open label:"${NEED_INFO_LABEL}" updated:<${noResponseThreshold.toISOString()}`,
async (item) => {
core.info(
`Closing #${item.number} due to no response for ${NO_RESPONSE_DAYS} days.`,
);
if (!dryRun) {
if (dryRun) {
core.info(
`[DRY RUN] Would close #${item.number} due to no response for ${NO_RESPONSE_DAYS} days.`,
);
} else {
core.info(
`Closing #${item.number} due to no response for ${NO_RESPONSE_DAYS} days.`,
);
await github.rest.issues.createComment({
owner,
repo,
@@ -156,6 +169,7 @@ module.exports = async ({ github, context, core }) => {
repo,
issue_number: item.number,
state: 'closed',
state_reason: 'not_planned',
});
}
},
@@ -163,11 +177,21 @@ module.exports = async ({ github, context, core }) => {
// 2. Handle Stale Mark (60 days inactivity, no stale label)
const exemptQuery = EXEMPT_LABELS.map((l) => `-label:"${l}"`).join(' ');
await processItems(
`repo:${owner}/${repo} is:open -label:"${STALE_LABEL}" ${exemptQuery} updated:<${staleThreshold.toISOString()}`,
async (item) => {
core.info(`Marking #${item.number} as stale.`);
if (!dryRun) {
const isBug = item.labels.some((l) =>
(typeof l === 'string' ? l : l.name).toLowerCase().includes('bug'),
);
const bodyText = isBug
? `This bug report has been automatically marked as stale due to ${STALE_DAYS} days of inactivity. Many issues are resolved in newer releases. Please verify if the issue persists in the latest Gemini CLI version. If it does, please leave a comment to keep this open. It will be closed in ${CLOSE_DAYS} days if no further activity occurs. Thank you!`
: `This item has been automatically marked as stale due to ${STALE_DAYS} days of inactivity. It will be closed in ${CLOSE_DAYS} days if no further activity occurs. Thank you!`;
if (dryRun) {
core.info(`[DRY RUN] Would mark #${item.number} as stale.`);
} else {
core.info(`Marking #${item.number} as stale.`);
await github.rest.issues.addLabels({
owner,
repo,
@@ -178,18 +202,97 @@ module.exports = async ({ github, context, core }) => {
owner,
repo,
issue_number: item.number,
body: `This item has been automatically marked as stale due to ${STALE_DAYS} days of inactivity. It will be closed in ${CLOSE_DAYS} days if no further activity occurs. Thank you!`,
body: bodyText,
});
}
},
);
// 3. Handle Stale Close (14 days with stale label)
// 3. Handle Stale Removal & Close
await processItems(
`repo:${owner}/${repo} is:open label:"${STALE_LABEL}" ${exemptQuery} updated:<${closeThreshold.toISOString()}`,
`repo:${owner}/${repo} is:open label:"${STALE_LABEL}" ${exemptQuery}`,
async (item) => {
core.info(`Closing stale item #${item.number}.`);
if (!dryRun) {
// Fetch full timeline to see events and comments
const timeline = await github.paginate(
github.rest.issues.listEventsForTimeline,
{
owner,
repo,
issue_number: item.number,
per_page: 100,
},
);
// Find exactly when the Stale label was added
// We look for the last 'labeled' event for STALE_LABEL
const staleEventIndex = timeline.findLastIndex(
(e) =>
e.event === 'labeled' &&
e.label?.name?.toLowerCase() === STALE_LABEL.toLowerCase(),
);
if (staleEventIndex === -1) return; // Fallback if no event found
const staleEvent = timeline[staleEventIndex];
const eventsAfterStale = timeline.slice(staleEventIndex + 1);
// Check for meaningful activity after the Stale label was applied
const meaningfulEvents = eventsAfterStale.filter((e) => {
const actor = e.actor?.login || '';
const isBot =
actor.includes('[bot]') || actor.includes('github-actions');
if (isBot) return false;
// Explicit whitelist of meaningful events for humans
if (
[
'commented',
'cross-referenced',
'connected',
'reopened',
'assigned',
].includes(e.event)
) {
return true;
}
return false;
});
if (meaningfulEvents.length > 0) {
// Activity detected, remove Stale label
if (dryRun) {
core.info(
`[DRY RUN] Would remove ${STALE_LABEL} from #${item.number} due to meaningful activity (e.g., comment or PR).`,
);
} else {
core.info(
`Removing ${STALE_LABEL} from #${item.number} due to meaningful activity (e.g., comment or PR).`,
);
await github.rest.issues
.removeLabel({
owner,
repo,
issue_number: item.number,
name: STALE_LABEL,
})
.catch(() => {});
}
return;
}
// No meaningful activity. Check if 14 days have passed.
const labeledDate = new Date(staleEvent.created_at);
if (labeledDate > closeThreshold) {
// Has not been 14 days since it was ACTUALLY marked stale
return;
}
if (dryRun) {
core.info(`[DRY RUN] Would close stale item #${item.number}.`);
} else {
core.info(`Closing stale item #${item.number}.`);
await github.rest.issues.createComment({
owner,
repo,
@@ -201,6 +304,7 @@ module.exports = async ({ github, context, core }) => {
repo,
issue_number: item.number,
state: 'closed',
state_reason: 'not_planned',
});
}
},
@@ -222,8 +326,12 @@ module.exports = async ({ github, context, core }) => {
async (pr) => {
if (await isMaintainer(pr.user, pr.author_association)) return;
core.info(`Nudging PR #${pr.number} for contribution policy.`);
if (!dryRun) {
if (dryRun) {
core.info(
`[DRY RUN] Would nudge PR #${pr.number} for contribution policy.`,
);
} else {
core.info(`Nudging PR #${pr.number} for contribution policy.`);
await github.rest.issues.addLabels({
owner,
repo,
@@ -246,10 +354,14 @@ module.exports = async ({ github, context, core }) => {
async (pr) => {
if (await isMaintainer(pr.user, pr.author_association)) return;
core.info(
`Closing PR #${pr.number} per contribution policy (no 'help wanted').`,
);
if (!dryRun) {
if (dryRun) {
core.info(
`[DRY RUN] Would close PR #${pr.number} per contribution policy (no 'help wanted').`,
);
} else {
core.info(
`Closing PR #${pr.number} per contribution policy (no 'help wanted').`,
);
await github.rest.issues.createComment({
owner,
repo,
@@ -68,6 +68,7 @@ jobs:
ISSUE_NUMBER: '${{ github.event.issue.number }}'
REPOSITORY: '${{ github.repository }}'
FIRESTORE_PROJECT: '${{ vars.FIRESTORE_PROJECT }}'
GEMINI_CLI_TRUST_WORKSPACE: 'true'
with:
gcp_workload_identity_provider: '${{ vars.GCP_WIF_PROVIDER }}'
gcp_project_id: '${{ vars.GOOGLE_CLOUD_PROJECT }}'
@@ -335,14 +335,41 @@ jobs:
return;
}
const newAreaLabel = labelsToAdd[0];
// Get current labels to resolve conflicts
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
});
const currentLabelNames = currentLabels.map(l => l.name);
const currentAreaLabels = currentLabelNames.filter(name => name.startsWith('area/'));
const labelsToRemove = currentAreaLabels.filter(name => name !== newAreaLabel);
for (const label of labelsToRemove) {
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
name: label
});
core.info(`Removed conflicting area label: ${label}`);
} catch (e) {
core.warning(`Failed to remove label ${label}: ${e.message}`);
}
}
// Set labels based on triage result
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: labelsToAdd
labels: [newAreaLabel]
});
core.info(`Successfully added labels for #${issueNumber}: ${labelsToAdd.join(', ')}`);
core.info(`Successfully added labels for #${issueNumber}: ${newAreaLabel}`);
- name: 'Post Issue Analysis Failure Comment'
if: |-
@@ -1,10 +1,6 @@
name: '📋 Gemini Scheduled Issue Triage'
on:
issues:
types:
- 'opened'
- 'reopened'
schedule:
- cron: '0 * * * *' # Runs every hour
workflow_dispatch:
@@ -66,12 +62,20 @@ jobs:
- name: 'Find Issues with Conflicting Labels'
if: |-
${{ github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' }}
uses: 'actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea'
with:
github-token: '${{ steps.generate_token.outputs.token }}'
script: |-
const findConflictingLabels = require('./.github/scripts/find-conflicting-labels.cjs');
await findConflictingLabels({ github, context, core });
env:
GITHUB_TOKEN: '${{ steps.generate_token.outputs.token }}'
GITHUB_REPOSITORY: '${{ github.repository }}'
run: |-
set -euo pipefail
echo '🔍 Fetching open issues to find conflicts...'
# Fetch up to 2000 open issues in one quick GraphQL-backed query
gh issue list --repo "${GITHUB_REPOSITORY}" --search "is:issue is:open" --limit 2000 --json number,title,body,labels > all_open_issues.json
echo '🧹 Filtering issues with multiple area/ or priority/ labels...'
jq -c '[ .[] | select( (.labels | map(select(.name | startswith("area/"))) | length) > 1 or (.labels | map(select(.name | startswith("priority/"))) | length) > 1 ) ] | .[0:50]' all_open_issues.json > conflicting_labels_issues.json
CONFLICT_COUNT=$(jq 'length' conflicting_labels_issues.json)
echo "Found ${CONFLICT_COUNT} issues with conflicting labels (capped at 50 for processing)."
- name: 'Find untriaged issues'
if: |-
@@ -85,19 +89,19 @@ jobs:
echo '🔍 Finding issues missing area labels...'
gh issue list --repo "${GITHUB_REPOSITORY}" \
--search 'is:open is:issue -label:status/bot-triaged -label:area/core -label:area/agent -label:area/enterprise -label:area/non-interactive -label:area/security -label:area/platform -label:area/extensions -label:area/documentation -label:area/unknown' --limit 50 --json number,title,body > no_area_issues.json
--search 'is:open is:issue -label:area/core -label:area/agent -label:area/enterprise -label:area/non-interactive -label:area/security -label:area/platform -label:area/extensions -label:area/documentation -label:area/unknown' --limit 50 --json number,title,body,labels > no_area_issues.json
echo '🔍 Finding issues missing kind labels...'
gh issue list --repo "${GITHUB_REPOSITORY}" \
--search 'is:open is:issue -label:status/bot-triaged -label:kind/bug -label:kind/enhancement -label:kind/customer-issue -label:kind/question' --limit 50 --json number,title,body > no_kind_issues.json
--search 'is:open is:issue -label:kind/bug -label:kind/enhancement -label:kind/customer-issue -label:kind/question' --limit 50 --json number,title,body,labels > no_kind_issues.json
echo '🏷️ Finding issues missing priority labels...'
gh issue list --repo "${GITHUB_REPOSITORY}" \
--search 'is:open is:issue -label:priority/p0 -label:priority/p1 -label:priority/p2 -label:priority/p3 -label:priority/unknown' --limit 50 --json number,title,body > no_priority_issues.json
--search 'is:open is:issue -label:priority/p0 -label:priority/p1 -label:priority/p2 -label:priority/p3 -label:priority/unknown' --limit 50 --json number,title,body,labels > no_priority_issues.json
echo '📏 Finding issues missing effort labels...'
gh issue list --repo "${GITHUB_REPOSITORY}" \
--search 'is:open is:issue -label:effort/small -label:effort/medium -label:effort/large label:area/core,area/extensions,area/site,area/non-interactive' --limit 5 --json number,title,body > no_effort_issues.json
--search 'is:open is:issue -label:effort/small -label:effort/medium -label:effort/large label:area/core,area/extensions,area/site,area/non-interactive' --limit 20 --json number,title,body,labels > no_effort_issues.json
echo '🔄 Merging and deduplicating standard triage issues...'
if [ ! -f conflicting_labels_issues.json ]; then echo "[]" > conflicting_labels_issues.json; fi
@@ -162,6 +166,7 @@ jobs:
GEMINI_CLI_TRUST_WORKSPACE: 'true'
GEMINI_EXP: 'gemini_exp.json'
GEMINI_STRICT_TELEMETRY_LIMITS: 'true'
GEMINI_MODEL: 'gemini-3-flash-preview'
with:
gcp_workload_identity_provider: '${{ vars.GCP_WIF_PROVIDER }}'
gcp_project_id: '${{ vars.GOOGLE_CLOUD_PROJECT }}'
@@ -178,7 +183,7 @@ jobs:
"read_file"
],
"telemetry": {
"enabled": true,
"enabled": false,
"target": "gcp"
}
}
@@ -192,12 +197,12 @@ jobs:
## Steps
1. You are only able to use the echo and read_file commands. Review the available labels in the environment variable: "${AVAILABLE_LABELS}".
2. Use the read_file tool to read the file "standard_issues_to_triage.json" which contains the JSON array of issues to triage.
3. Review the issue title, body and any comments provided in the JSON file.
2. Use the read_file tool to read the file "standard_issues_to_triage.json" which contains the JSON array of issues to triage (including their current labels).
3. Review the issue title, body, current labels, and any comments provided in the JSON file.
4. Identify the most relevant labels from the existing labels, specifically focusing on area/*, kind/*, and priority/*.
5. Label Policy:
- If the issue already has a kind/ label, do not change it.
- If the issue has exactly ONE priority/ label, do not change it.
- If the issue has exactly ONE priority/ label, do not change it (unless you are explicitly re-evaluating an ambiguous priority).
- If the issue is missing a priority/ label, OR if the issue currently has MULTIPLE priority/ labels, you must evaluate the issue's impact to determine exactly ONE priority level (priority/p0, priority/p1, priority/p2, priority/p3, or priority/unknown) based the guidelines. If you are fixing an issue with multiple priority/ labels, put the correct one in `labels_to_add` and put all the incorrect ones in `labels_to_remove`.
- If the issue has exactly ONE area/ label, do not change it.
- If the issue is missing an area/ label, OR if the issue currently has MULTIPLE area/ labels, select exactly ONE area/ label that best fits the issue. Issues MUST NOT have multiple area/ labels. If you are fixing an issue with multiple area/ labels, put the correct one in `labels_to_add` and put all the incorrect ones in `labels_to_remove`.
@@ -217,11 +222,12 @@ jobs:
]
```
If an issue cannot be classified, do not include it in the output array.
9. For each issue please check if CLI version is present, this is usually in the output of the /about command and will look like 0.1.5
- Anything more than 6 versions older than the most recent should add the status/need-retesting label
10. If you see that the issue doesn't look like it has sufficient information recommend the status/need-information label and leave a comment politely requesting the relevant information, eg.. if repro steps are missing request for repro steps. if version information is missing request for version information into the explanation section below.
11. If you think an issue might be a Priority/P0 do not apply the priority/p0 label. Instead apply a status/manual-triage label and include a note in your explanation.
12. If you are uncertain about a category, use the area/unknown, kind/question, or priority/unknown labels as appropriate. If you are extremely uncertain, apply the status/manual-triage label.
9. For each issue, carefully check if the CLI version is present. It is usually found under the "### Client information" header, as a bullet point (e.g., "• CLI Version: 0.33.1"), or in the output of the `/about` command.
- If the version is provided but is more than 6 minor versions older than the most recent release, apply the status/need-information label and leave a comment politely asking the user to verify if the issue persists in the latest version.
10. If the issue does not have sufficient information, recommend the status/need-information label and leave a comment politely requesting the missing details. For example, if repro steps are missing, ask for them; if the CLI version is completely missing, ask for the version information in the explanation section below. Do not ask for version info if it is already in the issue body.
11. If you think an issue is a Priority/P0, you MUST apply the priority/p1 label AND the status/manual-triage label, and include a note in your explanation that it likely requires P0 escalation.
12. If the issue is highly ambiguous, completely lacks a description, or you are torn between two lower priorities (like P2 vs P3), you MUST retain the existing priority label if one is already present. Do not toggle the priority if you do not have enough information to make a definitive change.
13. If you are uncertain about a category, use the area/unknown, kind/question, or priority/unknown labels as appropriate. If you are extremely uncertain, apply the status/manual-triage label.
## Guidelines
@@ -234,12 +240,14 @@ jobs:
- Identify exactly ONE area/ label. Do NOT assign multiple area/ labels to a single issue.
- Identify only one kind/ label (Do not apply kind/duplicate or kind/parent-issue)
- Identify exactly ONE priority/ label. Do NOT assign multiple priority/ labels to a single issue.
- Once you categorize the issue if it needs information bump down the priority by 1 eg.. a p0 would become a p1 a p1 would become a p2. P2 and P3 can stay as is in this scenario.
- **Do not manually downgrade the priority.** Always assign the true priority based on the guidelines. The system will handle downgrades programmatically if information is missing.
- **NEVER mention label names, label removals, or label additions in your `explanation`.** The explanation must be purely written for the user (e.g., "Please provide your CLI version.") without exposing internal triage mechanics (e.g., do NOT say "Removing area/unknown to leave only area/core").
Categorization Guidelines (Priority):
P0 - Urgent Blocking Issues:
- DO NOT APPLY THE priority/p0 LABEL AUTOMATICALLY. Instead apply priority/p1 and status/manual-triage.
- Definition: Critical failures breaking core functionality for a large portion of users. Examples: CLI fails to launch globally, core commands (gemini run) crash on valid input, unhandled promise rejections on boot, critical security vulnerability.
- Note: You must apply status/manual-triage instead of priority/p0.
- Note: You must apply priority/p1 and status/manual-triage instead of priority/p0.
P1 - Critical but Workable:
- Definition: Severe issues without a reasonable workaround, significantly degrading the developer experience but not globally blocking. Examples: Specific tools failing consistently (e.g., `web_search` returns 500s), persistent PTY streaming hangs, memory leaks leading to OOM after short use.
P2 - Significant Issues:
@@ -279,6 +287,7 @@ jobs:
GEMINI_CLI_TRUST_WORKSPACE: 'true'
GEMINI_EXP: 'gemini_exp.json'
GEMINI_STRICT_TELEMETRY_LIMITS: 'true'
GEMINI_MODEL: 'gemini-3-flash-preview'
with:
gcp_workload_identity_provider: '${{ vars.GCP_WIF_PROVIDER }}'
gcp_project_id: '${{ vars.GOOGLE_CLOUD_PROJECT }}'
@@ -297,7 +306,7 @@ jobs:
"read_file"
],
"telemetry": {
"enabled": true,
"enabled": false,
"target": "gcp"
}
}
@@ -383,29 +392,14 @@ jobs:
- This product is designed to use different models eg.. using pro, downgrading to flash etc.
- When users report that they dont expect the model to change those would be categorized as feature requests.
- name: 'Apply Standard Labels to Issues'
- name: 'Apply Triaged Labels'
if: |-
${{ steps.gemini_standard_issue_analysis.outcome == 'success' &&
steps.gemini_standard_issue_analysis.outputs.summary != '[]' &&
steps.gemini_standard_issue_analysis.outputs.summary != '' }}
always() &&
( (steps.gemini_standard_issue_analysis.outcome == 'success' && steps.gemini_standard_issue_analysis.outputs.summary != '[]' && steps.gemini_standard_issue_analysis.outputs.summary != '') ||
(steps.gemini_effort_issue_analysis.outcome == 'success' && steps.gemini_effort_issue_analysis.outputs.summary != '[]' && steps.gemini_effort_issue_analysis.outputs.summary != '') )
env:
REPOSITORY: '${{ github.repository }}'
LABELS_OUTPUT: '${{ steps.gemini_standard_issue_analysis.outputs.summary }}'
uses: 'actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea'
with:
github-token: '${{ steps.generate_token.outputs.token }}'
script: |-
const applyLabels = require('./.github/scripts/apply-issue-labels.cjs');
await applyLabels({ github, context, core });
- name: 'Apply Effort Labels to Issues'
if: |-
${{ steps.gemini_effort_issue_analysis.outcome == 'success' &&
steps.gemini_effort_issue_analysis.outputs.summary != '[]' &&
steps.gemini_effort_issue_analysis.outputs.summary != '' }}
env:
REPOSITORY: '${{ github.repository }}'
LABELS_OUTPUT: '${{ steps.gemini_effort_issue_analysis.outputs.summary }}'
LABELS_OUTPUT_STANDARD: '${{ steps.gemini_standard_issue_analysis.outputs.summary }}'
LABELS_OUTPUT_EFFORT: '${{ steps.gemini_effort_issue_analysis.outputs.summary }}'
uses: 'actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea'
with:
github-token: '${{ steps.generate_token.outputs.token }}'
@@ -431,9 +425,12 @@ jobs:
GITHUB_REPOSITORY: '${{ github.repository }}'
run: |-
set -euo pipefail
echo '🧹 Finding issues that have both bot-triaged and need-triage labels...'
echo '🧹 Finding issues that have conflicting status labels...'
gh issue list --repo "${GITHUB_REPOSITORY}" \
--search 'is:open is:issue label:status/bot-triaged label:status/need-triage' --limit 50 --json number > issues_to_cleanup.json
--search 'is:open is:issue label:status/bot-triaged label:status/need-triage' --limit 50 --json number > cleanup_1.json
gh issue list --repo "${GITHUB_REPOSITORY}" \
--search 'is:open is:issue label:status/bot-triaged label:status/manual-triage' --limit 50 --json number > cleanup_2.json
jq -c -s 'add | unique_by(.number)' cleanup_1.json cleanup_2.json > issues_to_cleanup.json
- name: 'Clean Up Triage Labels'
if: |-
+16
View File
@@ -18,6 +18,22 @@ on GitHub.
| [Preview](preview.md) | Experimental features ready for early feedback. |
| [Stable](latest.md) | Stable, recommended for general use. |
## Announcements: v0.42.0 - 2026-05-12
- **Auto Memory Inbox:** Introduced a new inbox flow for Auto Memory with a
canonical-patch contract for seamless skill management
([#26338](https://github.com/google-gemini/gemini-cli/pull/26338) by
@SandyTao520).
- **Gemma 4 by Default:** Enabled Gemma 4 models by default via the Gemini API
for all users
([#26307](https://github.com/google-gemini/gemini-cli/pull/26307) by
@Abhijit-2592).
- **Voice Mode Enhancements:** Added wave animations and privacy/compliance UX
warnings for the Gemini Live backend
([#26284](https://github.com/google-gemini/gemini-cli/pull/26284) by
@devr0306, [#26454](https://github.com/google-gemini/gemini-cli/pull/26454) by
@cocosheng-g).
## Announcements: v0.41.0 - 2026-05-05
- **Real-time Voice Mode:** Implemented real-time voice mode with cloud and
+261 -108
View File
@@ -1,6 +1,6 @@
# Latest stable release: v0.41.0
# Latest stable release: v0.42.0
Released: May 05, 2026
Released: May 12, 2026
For most users, our latest stable release is the recommended release. Install
the latest stable version with:
@@ -11,119 +11,272 @@ npm install -g @google/gemini-cli
## Highlights
- **Real-time Voice Mode:** Introduced support for real-time voice interaction
with both cloud-based and local processing backends.
- **Enhanced Security:** Implemented mandatory workspace trust for headless
environments and secured the loading of `.env` configuration files.
- **Advanced Shell Validation:** Added a robust shell command validation layer
and a core tools allowlist to prevent unauthorized execution.
- **Improved Context Management:** Integrated a new `ContextManager` and
`AgentChatHistory` to provide more reliable and efficient session handling.
- **Auto-Memory Persistence:** Enabled the persistence of the auto-memory
scratchpad, allowing for seamless skill extraction across turns.
- **Auto Memory Inbox:** Introduced a new inbox flow for Auto Memory using a
canonical-patch contract, enabling more robust and manageable skill
extraction.
- **Gemma 4 Default:** Gemma 4 models are now enabled by default via the Gemini
API, providing improved performance and capabilities out of the box.
- **Voice Mode Polish:** Added wave animations for visual feedback and
privacy/compliance UX warnings specifically for the Gemini Live backend.
- **Session Management:** Added a `--delete` flag to the `/exit` command for
instant session deletion and introduced `/bug-memory` for easier heap
diagnostics.
- **Improved Reliability:** Reduced default API timeouts to 60s and implemented
retries for undici and premature stream closure errors.
## What's Changed
- chore(release): bump version to 0.41.0-nightly.20260423.gaa05b4583 by
- fix(cli): prevent automatic updates from switching to less stable channels by
@Adib234 in [#26132](https://github.com/google-gemini/gemini-cli/pull/26132)
- chore(release): bump version to 0.42.0-nightly.20260428.g59b2dea0e by
@gemini-cli-robot in
[#25847](https://github.com/google-gemini/gemini-cli/pull/25847)
- fix(core): only show `list` suggestion if the partial input is empty by
@cynthialong0-0 in
[#25821](https://github.com/google-gemini/gemini-cli/pull/25821)
- feat(cli): secure .env loading and enforce workspace trust in headless mode by
@ehedlund in [#25814](https://github.com/google-gemini/gemini-cli/pull/25814)
- fix: fatal hard-crash on loop detection via unhandled AbortError by @hsm207 in
[#20108](https://github.com/google-gemini/gemini-cli/pull/20108)
- update package-lock.json by @ehedlund in
[#25876](https://github.com/google-gemini/gemini-cli/pull/25876)
- feat(core): enhance shell command validation and add core tools allowlist by
@galz10 in [#25720](https://github.com/google-gemini/gemini-cli/pull/25720)
- fix(ui): corrected background color check in user message components by
@devr0306 in [#25880](https://github.com/google-gemini/gemini-cli/pull/25880)
- perf(core): fix slow boot by fetching experiments and quota asynchronously by
@spencer426 in
[#25758](https://github.com/google-gemini/gemini-cli/pull/25758)
- feat(core,cli): add support for Gemma 4 models (experimental) by @Abhijit-2592
in [#25604](https://github.com/google-gemini/gemini-cli/pull/25604)
- update FatalUntrustedWorkspaceError message to include doc link by @ehedlund
in [#25874](https://github.com/google-gemini/gemini-cli/pull/25874)
- docs: add Gemini CLI course link to README by @JayadityaGit in
[#25925](https://github.com/google-gemini/gemini-cli/pull/25925)
- feat(repo): add gemini-cli-bot metrics and workflows by @gundermanc in
[#25888](https://github.com/google-gemini/gemini-cli/pull/25888)
- fix(cli): allow output redirection for cli commands by @spencer426 in
[#25894](https://github.com/google-gemini/gemini-cli/pull/25894)
- fix(core): fail closed in YOLO mode when shell parsing fails for restricted
rules by @ehedlund in
[#25935](https://github.com/google-gemini/gemini-cli/pull/25935)
- fix(cli-ui): revert backspace handling to fix Windows regression by @scidomino
in [#25941](https://github.com/google-gemini/gemini-cli/pull/25941)
- feat(voice): implement real-time voice mode with cloud and local backends by
[#26142](https://github.com/google-gemini/gemini-cli/pull/26142)
- fix(cli): pass node arguments via NODE_OPTIONS during relaunch to support SEA
by @cocosheng-g in
[#26130](https://github.com/google-gemini/gemini-cli/pull/26130)
- fix(cli): handle DECKPAM keypad Enter sequences in terminal by @Gitanaskhan26
in [#26092](https://github.com/google-gemini/gemini-cli/pull/26092)
- docs(cli): point plan-mode session retention to actual /settings labels by
@ifitisit in [#25978](https://github.com/google-gemini/gemini-cli/pull/25978)
- fix(core): add missing oauth fields support in subagent parsing by
@abhipatel12 in
[#26141](https://github.com/google-gemini/gemini-cli/pull/26141)
- fix(core): disconnect extension-backed MCP clients in stopExtension by
@cocosheng-g in
[#26136](https://github.com/google-gemini/gemini-cli/pull/26136)
- Update documentation workflows with workspace trust by @g-samroberts in
[#26150](https://github.com/google-gemini/gemini-cli/pull/26150)
- refactor(acp): modularize monolithic acpClient into specialized files by
@sripasg in [#26143](https://github.com/google-gemini/gemini-cli/pull/26143)
- test: fix failures due to antigravity environment leakage by @adamfweidman in
[#26162](https://github.com/google-gemini/gemini-cli/pull/26162)
- fix(core): add explicit empty log guard in A2A pushMessage by @adamfweidman in
[#26198](https://github.com/google-gemini/gemini-cli/pull/26198)
- feat(cli): add --delete flag to /exit command for session deletion by
@AbdulTawabJuly in
[#19332](https://github.com/google-gemini/gemini-cli/pull/19332)
- test(core): add regression test for issue for ToolConfirmationResponse by
@Adib234 in [#26194](https://github.com/google-gemini/gemini-cli/pull/26194)
- Add the ability to @ mention the gemini robot. by @gundermanc in
[#26207](https://github.com/google-gemini/gemini-cli/pull/26207)
- test(evals): add EvalMetadata JSDoc annotations to older tests by @akh64bit in
[#26147](https://github.com/google-gemini/gemini-cli/pull/26147)
- fix(core): reduce default API timeout to 60s and enable retries for undici
timeouts by @Adib234 in
[#26191](https://github.com/google-gemini/gemini-cli/pull/26191)
- fix(core): distinguish fallback chains and fix maxAttempts for auto vs
explicit model selection by @adamfweidman in
[#26163](https://github.com/google-gemini/gemini-cli/pull/26163)
- fix(cli): handle InvalidStream event gracefully without throwing by
@adamfweidman in
[#26218](https://github.com/google-gemini/gemini-cli/pull/26218)
- ci(github-actions): switch to github app token and fix bot self-trigger by
@gundermanc in
[#26223](https://github.com/google-gemini/gemini-cli/pull/26223)
- Respect logPrompts flag for logging sensitive fields by @lp-peg in
[#26153](https://github.com/google-gemini/gemini-cli/pull/26153)
- fix: correct API key validation logic in handleApiKeySubmit by
@martin-hsu-test in
[#25453](https://github.com/google-gemini/gemini-cli/pull/25453)
- fix(agent): prevent exit_plan_mode from being called via shell by
@Abhijit-2592 in
[#24174](https://github.com/google-gemini/gemini-cli/pull/24174)
- Changelog for v0.39.0 by @gemini-cli-robot in
[#25848](https://github.com/google-gemini/gemini-cli/pull/25848)
- feat(memory): persist auto-memory scratchpad for skill extraction by
[#26230](https://github.com/google-gemini/gemini-cli/pull/26230)
- # Fix: Inconsistent Case-Sensitivity in GrepTool by @.github/workflows/gemini-cli-bot-pulse.yml[bot] in [#26235](https://github.com/google-gemini/gemini-cli/pull/26235)
- docs(core): add automated gemma setup guide by @Samee24 in
[#26233](https://github.com/google-gemini/gemini-cli/pull/26233)
- Allow non-https proxy urls to support container environments by @stevemk14ebr
in [#26234](https://github.com/google-gemini/gemini-cli/pull/26234)
- fix(bot): productivity and backlog optimizations by @gundermanc in
[#26236](https://github.com/google-gemini/gemini-cli/pull/26236)
- refactor(acp): delegate prompt turn processing logic to GeminiClient by
@sripasg in [#26222](https://github.com/google-gemini/gemini-cli/pull/26222)
- fix(cli): refine platform-specific undo/redo and smart bubbling for WSL by
@cocosheng-g in
[#26202](https://github.com/google-gemini/gemini-cli/pull/26202)
- fix: suppress duplicate extension warnings during startup by @cocosheng-g in
[#26208](https://github.com/google-gemini/gemini-cli/pull/26208)
- fix(cli): use byte length instead of string length for readStdin size limits
by @Adib234 in
[#26224](https://github.com/google-gemini/gemini-cli/pull/26224)
- fix(ui): made shell tool header wrap on Ctrl+O by @devr0306 in
[#26229](https://github.com/google-gemini/gemini-cli/pull/26229)
- Changelog for v0.41.0-preview.0 by @gemini-cli-robot in
[#26244](https://github.com/google-gemini/gemini-cli/pull/26244)
- Skip binary CLI relaunch by @ruomengz in
[#26261](https://github.com/google-gemini/gemini-cli/pull/26261)
- fix(cli): do not override GOOGLE_CLOUD_PROJECT in Cloud Shell when using
Vertex AI by @jackwotherspoon in
[#24455](https://github.com/google-gemini/gemini-cli/pull/24455)
- docs(cli): add skill discovery troubleshooting checklist to tutorial by
@pmenic in [#26018](https://github.com/google-gemini/gemini-cli/pull/26018)
- docs(policy-engine): link to tools reference for tool names and args by
@Aaxhirrr in [#22081](https://github.com/google-gemini/gemini-cli/pull/22081)
- Fix posting invalid response to a comment by @gundermanc in
[#26266](https://github.com/google-gemini/gemini-cli/pull/26266)
- fix(cli): prevent informational logs from polluting json output by
@cocosheng-g in
[#26264](https://github.com/google-gemini/gemini-cli/pull/26264)
- feat(ui): added microphone and updated placeholder for voice mode by @devr0306
in [#26270](https://github.com/google-gemini/gemini-cli/pull/26270)
- feat(cli): Add 'list' subcommand to '/commands' by @Jwhyee in
[#22324](https://github.com/google-gemini/gemini-cli/pull/22324)
- fix(core): ensure tool output cleanup on session deletion for legacy files by
@cocosheng-g in
[#26263](https://github.com/google-gemini/gemini-cli/pull/26263)
- Docs: Update Agent Skills documentation by @jkcinouye in
[#22388](https://github.com/google-gemini/gemini-cli/pull/22388)
- test(acp): add missing coverage for extensions command error paths by
@sahilkirad in
[#25313](https://github.com/google-gemini/gemini-cli/pull/25313)
- Changelog for v0.40.0 by @gemini-cli-robot in
[#26245](https://github.com/google-gemini/gemini-cli/pull/26245)
- fix: report AgentExecutionBlocked in non-interactive programmatic modes by
@cocosheng-g in
[#26262](https://github.com/google-gemini/gemini-cli/pull/26262)
- feat(extensions): add 'delete' as an alias for /extensions uninstall by
@martin-hsu-test in
[#25660](https://github.com/google-gemini/gemini-cli/pull/25660)
- fix(core): silently skip GEMINI.md paths that are directories (EISDIR) by
@martin-hsu-test in
[#25662](https://github.com/google-gemini/gemini-cli/pull/25662)
- fix(ci): checkout PR branch instead of main in bot workflow by @gundermanc in
[#26289](https://github.com/google-gemini/gemini-cli/pull/26289)
- fix(cli): use resolved sandbox state for auto-update check by @Adib234 in
[#26285](https://github.com/google-gemini/gemini-cli/pull/26285)
- # Metrics Integrity & Standardized Reporting (BT-01) by @.github/workflows/gemini-cli-bot-pulse.yml[bot] in [#26240](https://github.com/google-gemini/gemini-cli/pull/26240)
- Add Star History section to README by @bdmorgan in
[#26290](https://github.com/google-gemini/gemini-cli/pull/26290)
- Add Star History section to README by @bdmorgan in
[#26308](https://github.com/google-gemini/gemini-cli/pull/26308)
- Remove Star History section from README by @bdmorgan in
[#26309](https://github.com/google-gemini/gemini-cli/pull/26309)
- test(evals): add behavioral eval for file creation and write_file tool
selection by @akh64bit in
[#26292](https://github.com/google-gemini/gemini-cli/pull/26292)
- feat(config): enable Gemma 4 models by default via Gemini API by @Abhijit-2592
in [#26307](https://github.com/google-gemini/gemini-cli/pull/26307)
- fix(cli): insert voice transcription at cursor position instead of ap… by
@Zheyuan-Lin in
[#26287](https://github.com/google-gemini/gemini-cli/pull/26287)
- fix(ui): fix issue with box edges by @gundermanc in
[#26148](https://github.com/google-gemini/gemini-cli/pull/26148)
- fix(cli): respect .env override for GOOGLE_CLOUD_PROJECT by @DavidAPierce in
[#26288](https://github.com/google-gemini/gemini-cli/pull/26288)
- fix(ci): robust version checking in release verification by @scidomino in
[#26337](https://github.com/google-gemini/gemini-cli/pull/26337)
- fix(cli): enable daemon relaunch in binary and bundle keytar by @ruomengz in
[#26333](https://github.com/google-gemini/gemini-cli/pull/26333)
- fix(core): discourage unprompted git add . in prompt snippets by @akh64bit in
[#26220](https://github.com/google-gemini/gemini-cli/pull/26220)
- feat(ui): added wave animation for voice mode by @devr0306 in
[#26284](https://github.com/google-gemini/gemini-cli/pull/26284)
- fix(cli): prevent Escape from clearing input buffer (#17083) by @cocosheng-g
in [#26339](https://github.com/google-gemini/gemini-cli/pull/26339)
- fix(cli): undeprecate --prompt and correct positional query docs by @Adib234
in [#26329](https://github.com/google-gemini/gemini-cli/pull/26329)
- Metrics updates by @.github/workflows/gemini-cli-bot-pulse.yml[bot] in
[#26348](https://github.com/google-gemini/gemini-cli/pull/26348)
- fix(core): remove "System: Please continue." injection on InvalidStream events
by @SandyTao520 in
[#26340](https://github.com/google-gemini/gemini-cli/pull/26340)
- docs(policy-engine): add tool argument keys reference and shell policy
cross-links by @harshpujari in
[#25292](https://github.com/google-gemini/gemini-cli/pull/25292)
- fix(cli): resolve Ghostty/raw-mode False Cancellation in oauth flow by
@Aarchi-07 in [#25026](https://github.com/google-gemini/gemini-cli/pull/25026)
- fix(core): reset session-scoped state on resumption by @cocosheng-g in
[#26342](https://github.com/google-gemini/gemini-cli/pull/26342)
- Fix bulk of remaining issues with generalist profile by @joshualitt in
[#26073](https://github.com/google-gemini/gemini-cli/pull/26073)
- fix(core): make subagents aware of active approval modes by @akh64bit in
[#23608](https://github.com/google-gemini/gemini-cli/pull/23608)
- fix(acp): resolve agent mode disconnect and improve mode awareness by @sripasg
in [#26332](https://github.com/google-gemini/gemini-cli/pull/26332)
- docs(sdk): add JSDoc to exported interfaces in packages/sdk/src/types.ts by
@cocosheng-g in
[#26441](https://github.com/google-gemini/gemini-cli/pull/26441)
- perf: skip redundant GEMINI.md loading in partialConfig by @cocosheng-g in
[#26443](https://github.com/google-gemini/gemini-cli/pull/26443)
- Enhance React guidelines by @psinha40898 in
[#22667](https://github.com/google-gemini/gemini-cli/pull/22667)
- feat(core): reinforce Inquiry constraints to prevent unauthorized changes by
@akh64bit in [#26310](https://github.com/google-gemini/gemini-cli/pull/26310)
- revert: fix(ci): robust version checking in release verification (#26337) by
@scidomino in [#26450](https://github.com/google-gemini/gemini-cli/pull/26450)
- refactor(UI): created constants file for ThemeDialog by @devr0306 in
[#26446](https://github.com/google-gemini/gemini-cli/pull/26446)
- docs: fix GitHub capitalization in releases guide by @haosenwang1018 in
[#26379](https://github.com/google-gemini/gemini-cli/pull/26379)
- fix(cli): ensure branch indicator updates in sub-directories and worktrees by
@Adib234 in [#26330](https://github.com/google-gemini/gemini-cli/pull/26330)
- feat: add minimal V8 heap snapshot utility for memory diagnostics by
@cocosheng-g in
[#26440](https://github.com/google-gemini/gemini-cli/pull/26440)
- fix(hooks): preserve non-text parts in fromHookLLMRequest by @SandyTao520 in
[#26275](https://github.com/google-gemini/gemini-cli/pull/26275)
- fix(cli): allow early stdout when config is undefined by @cocosheng-g in
[#26453](https://github.com/google-gemini/gemini-cli/pull/26453)
- fix(cli)#21297: clear skills consent dialog before reload by @manavmax in
[#26431](https://github.com/google-gemini/gemini-cli/pull/26431)
- fix(cli): render LaTeX-style output as Unicode in the TUI by @dimssu in
[#25802](https://github.com/google-gemini/gemini-cli/pull/25802)
- fix(core): use close event instead of exit in child_process fallback by
@tusaryan in [#25695](https://github.com/google-gemini/gemini-cli/pull/25695)
- feat(voice): add privacy and compliance UX warning for Gemini Live backend by
@cocosheng-g in
[#26454](https://github.com/google-gemini/gemini-cli/pull/26454)
- feat(memory): add Auto Memory inbox flow with canonical-patch contract by
@SandyTao520 in
[#25873](https://github.com/google-gemini/gemini-cli/pull/25873)
- fix(cli): add missing response key to custom theme text schema by @gaurav0107
in [#25822](https://github.com/google-gemini/gemini-cli/pull/25822)
- fix(cli): provide manual update command when automatic update fails by
@cocosheng-g in
[#26052](https://github.com/google-gemini/gemini-cli/pull/26052)
- test(cli): add unit tests for restore ACP command (#23402) by @cocosheng-g in
[#26053](https://github.com/google-gemini/gemini-cli/pull/26053)
- fix(ui): better error messages for ECONNRESET and ETIMEDOUT by @devr0306 in
[#26059](https://github.com/google-gemini/gemini-cli/pull/26059)
- feat(core): wire up the new ContextManager and AgentChatHistory by @joshualitt
in [#25409](https://github.com/google-gemini/gemini-cli/pull/25409)
- fix(cli): ensure sandbox proxy cleanup and remove handler leaks by @ehedlund
in [#26065](https://github.com/google-gemini/gemini-cli/pull/26065)
- fix(cli): correct alternate buffer warning logic for JetBrains by @Adib234 in
[#26067](https://github.com/google-gemini/gemini-cli/pull/26067)
- fix(cli): make MCP ping optional in list command and use configured timeout by
@cocosheng-g in
[#26068](https://github.com/google-gemini/gemini-cli/pull/26068)
- fix(core): better error message for failed cloudshell-gca auth by @devr0306 in
[#26079](https://github.com/google-gemini/gemini-cli/pull/26079)
- feat(cli): provide manual session UUID via command line arg by @cocosheng-g in
[#26060](https://github.com/google-gemini/gemini-cli/pull/26060)
- Changelog for v0.40.0-preview.2 by @gemini-cli-robot in
[#25846](https://github.com/google-gemini/gemini-cli/pull/25846)
- (docs) update sandboxing documentation by @g-samroberts in
[#25930](https://github.com/google-gemini/gemini-cli/pull/25930)
- fix(core): enforce parallel task tracker updates by @anj-s in
[#24477](https://github.com/google-gemini/gemini-cli/pull/24477)
- Update policy so transient errors are not marked terminal by @DavidAPierce in
[#26066](https://github.com/google-gemini/gemini-cli/pull/26066)
- Implement bot that performs time-series metric analysis and suggests repo
management improvements by @gundermanc in
[#25945](https://github.com/google-gemini/gemini-cli/pull/25945)
- fix(core): handle non-string model flags in resolution by @Adib234 in
[#26069](https://github.com/google-gemini/gemini-cli/pull/26069)
- fix(ux): added error message for ENOTDIR by @devr0306 in
[#26128](https://github.com/google-gemini/gemini-cli/pull/26128)
- Changelog for v0.40.0-preview.3 by @gemini-cli-robot in
[#25904](https://github.com/google-gemini/gemini-cli/pull/25904)
- fix(cli): prevent ACP stdout pollution from SessionEnd hooks by @cocosheng-g
in [#26125](https://github.com/google-gemini/gemini-cli/pull/26125)
- feat(cli): support boolean and number casting for env vars in settings.json by
@cocosheng-g in
[#26118](https://github.com/google-gemini/gemini-cli/pull/26118)
- fix(cli): preserve Request headers in DevTools activity logger by @Adib234 in
[#26078](https://github.com/google-gemini/gemini-cli/pull/26078)
- fix(patch): cherry-pick 2194da2 to release/v0.41.0-preview.0-pr-26153 to patch
version v0.41.0-preview.0 and create version 0.41.0-preview.1 by
[#26338](https://github.com/google-gemini/gemini-cli/pull/26338)
- test(cleanup): fix temporary directory leaks in test suites by @Adib234 in
[#26217](https://github.com/google-gemini/gemini-cli/pull/26217)
- feat: add ignoreLocalEnv setting and --ignore-env flag (#2493) by @cocosheng-g
in [#26445](https://github.com/google-gemini/gemini-cli/pull/26445)
- docs(sdk): add JSDoc to all exported interfaces and types by @fauzan171 in
[#26277](https://github.com/google-gemini/gemini-cli/pull/26277)
- feat(cli): improve /agents refresh logging by @cocosheng-g in
[#26442](https://github.com/google-gemini/gemini-cli/pull/26442)
- Fix: make Dockerfile self-contained with multi-stage build by @Famous077 in
[#24277](https://github.com/google-gemini/gemini-cli/pull/24277)
- fix(core): filter unsupported multimodal types from tool responses by
@aishaneeshah in
[#26352](https://github.com/google-gemini/gemini-cli/pull/26352)
- fix(core): properly format markdown in AskUser tool by unescaping newlines by
@Adib234 in [#26349](https://github.com/google-gemini/gemini-cli/pull/26349)
- feat(bot): add actions spend metric script by @gundermanc in
[#26463](https://github.com/google-gemini/gemini-cli/pull/26463)
- feat(cli): add /bug-memory command and auto-capture heap snapshot in /bug by
@Anjaligarhwal in
[#25639](https://github.com/google-gemini/gemini-cli/pull/25639)
- fix(cli): make SkillInboxDialog fit and scroll in alternate buffer by
@SandyTao520 in
[#26455](https://github.com/google-gemini/gemini-cli/pull/26455)
- Robust Scale-Safe Lifecycle Consolidation by @gemini-cli-robot in
[#26355](https://github.com/google-gemini/gemini-cli/pull/26355)
- fix(ci): respect exempt labels when closing stale items by @gundermanc in
[#26475](https://github.com/google-gemini/gemini-cli/pull/26475)
- fix(cli): use os.homedir() for home directory warning check by @TirthNaik-99
in [#25890](https://github.com/google-gemini/gemini-cli/pull/25890)
- fix(a2a-server): resolve tool approval race condition and improve status
reporting by @kschaab in
[#26479](https://github.com/google-gemini/gemini-cli/pull/26479)
- fix(cli): prevent settings dialog border clipping using maxHeight by
@jackwotherspoon in
[#26507](https://github.com/google-gemini/gemini-cli/pull/26507)
- feat: allow queuing messages during compression (#24071) by @cocosheng-g in
[#26506](https://github.com/google-gemini/gemini-cli/pull/26506)
- fix(core): retry on ERR_STREAM_PREMATURE_CLOSE errors by @cocosheng-g in
[#26519](https://github.com/google-gemini/gemini-cli/pull/26519)
- fix(core): Minor fixes for generalist profile. by @joshualitt in
[#26357](https://github.com/google-gemini/gemini-cli/pull/26357)
- fix(patch): cherry-pick 3627f47 to release/v0.42.0-preview.0-pr-26542 to patch
version v0.42.0-preview.0 and create version 0.42.0-preview.1 by
@gemini-cli-robot in
[#26269](https://github.com/google-gemini/gemini-cli/pull/26269)
- fix(patch): cherry-pick 1d72a12 to release/v0.41.0-preview.1-pr-26479 to patch
version v0.41.0-preview.1 and create version 0.41.0-preview.2 by
[#26544](https://github.com/google-gemini/gemini-cli/pull/26544)
- fix(patch): cherry-pick 02995ba to release/v0.42.0-preview.1-pr-26568 to patch
version v0.42.0-preview.1 and create version 0.42.0-preview.2 by
@gemini-cli-robot in
[#26508](https://github.com/google-gemini/gemini-cli/pull/26508)
- fix(patch): cherry-pick 7cc19c2 to release/v0.41.0-preview.2-pr-26507 to patch
version v0.41.0-preview.2 and create version 0.41.0-preview.3 by
@gemini-cli-robot in
[#26530](https://github.com/google-gemini/gemini-cli/pull/26530)
[#26590](https://github.com/google-gemini/gemini-cli/pull/26590)
**Full Changelog**:
https://github.com/google-gemini/gemini-cli/compare/v0.40.1...v0.41.0
https://github.com/google-gemini/gemini-cli/compare/v0.41.2...v0.42.0
+178 -227
View File
@@ -1,6 +1,6 @@
# Preview release: v0.42.0-preview.2
# Preview release: v0.43.0-preview.0
Released: May 06, 2026
Released: May 12, 2026
Our preview release includes the latest, new, and experimental features. This
release may not be as stable as our [latest weekly release](latest.md).
@@ -13,233 +13,184 @@ npm install -g @google/gemini-cli@preview
## Highlights
- **Auto Memory Enhancements:** Introduced an Auto Memory inbox flow with a
canonical-patch contract for better memory management.
- **Improved Voice Mode:** Added a wave animation, microphone icon updates, and
privacy/compliance UX warnings for the Gemini Live backend.
- **New CLI Commands & Flags:** Added a `--delete` flag to the `/exit` command
for session deletion, a `list` subcommand to `/commands`, and a `/bug-memory`
command for heap snapshots.
- **Expanded Model Support:** Gemma 4 models are now enabled by default via the
Gemini API.
- **Enhanced Core Resilience:** Improved API resilience with reduced timeouts,
automatic retries for stream errors, and better handling of invalid stream
events.
- **Surgical Code Edits:** Steer models to use the `edit` tool for precise code
modifications, improving accuracy and reducing context usage.
- **Session Portability:** Added ability to export chat sessions to files and
import them via a new CLI flag, enabling session persistence and sharing.
- **Enhanced Security:** Introduced comprehensive shell command safety
evaluations and strengthened model steering to prevent unauthorized changes.
- **Context Management:** Implemented a new adaptive token calculator for more
accurate content size estimations and optimized context pipelines.
- **UX Improvements:** Enhanced tool call visibility with prefixed IDs and
improved the UI for session resumption and MCP list management.
## What's Changed
- fix(cli): prevent automatic updates from switching to less stable channels in
[#26132](https://github.com/google-gemini/gemini-cli/pull/26132)
- chore(release): bump version to 0.42.0-nightly.20260428.g59b2dea0e in
[#26142](https://github.com/google-gemini/gemini-cli/pull/26142)
- fix(cli): pass node arguments via NODE_OPTIONS during relaunch to support SEA
in [#26130](https://github.com/google-gemini/gemini-cli/pull/26130)
- fix(cli): handle DECKPAM keypad Enter sequences in terminal in
[#26092](https://github.com/google-gemini/gemini-cli/pull/26092)
- docs(cli): point plan-mode session retention to actual /settings labels in
[#25978](https://github.com/google-gemini/gemini-cli/pull/25978)
- fix(core): add missing oauth fields support in subagent parsing in
[#26141](https://github.com/google-gemini/gemini-cli/pull/26141)
- fix(core): disconnect extension-backed MCP clients in stopExtension in
[#26136](https://github.com/google-gemini/gemini-cli/pull/26136)
- Update documentation workflows with workspace trust in
[#26150](https://github.com/google-gemini/gemini-cli/pull/26150)
- refactor(acp): modularize monolithic acpClient into specialized files in
[#26143](https://github.com/google-gemini/gemini-cli/pull/26143)
- test: fix failures due to antigravity environment leakage in
[#26162](https://github.com/google-gemini/gemini-cli/pull/26162)
- fix(core): add explicit empty log guard in A2A pushMessage in
[#26198](https://github.com/google-gemini/gemini-cli/pull/26198)
- feat(cli): add --delete flag to /exit command for session deletion in
[#19332](https://github.com/google-gemini/gemini-cli/pull/19332)
- test(core): add regression test for issue for ToolConfirmationResponse in
[#26194](https://github.com/google-gemini/gemini-cli/pull/26194)
- Add the ability to @ mention the gemini robot. in
[#26207](https://github.com/google-gemini/gemini-cli/pull/26207)
- test(evals): add EvalMetadata JSDoc annotations to older tests in
[#26147](https://github.com/google-gemini/gemini-cli/pull/26147)
- fix(core): reduce default API timeout to 60s and enable retries for undici
timeouts in [#26191](https://github.com/google-gemini/gemini-cli/pull/26191)
- fix(core): distinguish fallback chains and fix maxAttempts for auto vs
explicit model selection in
[#26163](https://github.com/google-gemini/gemini-cli/pull/26163)
- fix(cli): handle InvalidStream event gracefully without throwing in
[#26218](https://github.com/google-gemini/gemini-cli/pull/26218)
- ci(github-actions): switch to github app token and fix bot self-trigger in
[#26223](https://github.com/google-gemini/gemini-cli/pull/26223)
- Respect logPrompts flag for logging sensitive fields in
[#26153](https://github.com/google-gemini/gemini-cli/pull/26153)
- fix: correct API key validation logic in handleApiKeySubmit in
[#25453](https://github.com/google-gemini/gemini-cli/pull/25453)
- fix(agent): prevent exit_plan_mode from being called via shell in
[#26230](https://github.com/google-gemini/gemini-cli/pull/26230)
- # Fix: Inconsistent Case-Sensitivity in GrepTool in [#26235](https://github.com/google-gemini/gemini-cli/pull/26235)
- docs(core): add automated gemma setup guide in
[#26233](https://github.com/google-gemini/gemini-cli/pull/26233)
- Allow non-https proxy urls to support container environments in
[#26234](https://github.com/google-gemini/gemini-cli/pull/26234)
- fix(bot): productivity and backlog optimizations in
[#26236](https://github.com/google-gemini/gemini-cli/pull/26236)
- refactor(acp): delegate prompt turn processing logic to GeminiClient in
[#26222](https://github.com/google-gemini/gemini-cli/pull/26222)
- fix(cli): refine platform-specific undo/redo and smart bubbling for WSL in
[#26202](https://github.com/google-gemini/gemini-cli/pull/26202)
- fix: suppress duplicate extension warnings during startup in
[#26208](https://github.com/google-gemini/gemini-cli/pull/26208)
- fix(cli): use byte length instead of string length for readStdin size limits
in [#26224](https://github.com/google-gemini/gemini-cli/pull/26224)
- fix(ui): made shell tool header wrap on Ctrl+O in
[#26229](https://github.com/google-gemini/gemini-cli/pull/26229)
- Changelog for v0.41.0-preview.0 in
[#26244](https://github.com/google-gemini/gemini-cli/pull/26244)
- Skip binary CLI relaunch in
[#26261](https://github.com/google-gemini/gemini-cli/pull/26261)
- fix(cli): do not override GOOGLE_CLOUD_PROJECT in Cloud Shell when using
Vertex AI in [#24455](https://github.com/google-gemini/gemini-cli/pull/24455)
- docs(cli): add skill discovery troubleshooting checklist to tutorial in
[#26018](https://github.com/google-gemini/gemini-cli/pull/26018)
- docs(policy-engine): link to tools reference for tool names and args in
[#22081](https://github.com/google-gemini/gemini-cli/pull/22081)
- Fix posting invalid response to a comment in
[#26266](https://github.com/google-gemini/gemini-cli/pull/26266)
- fix(cli): prevent informational logs from polluting json output in
[#26264](https://github.com/google-gemini/gemini-cli/pull/26264)
- feat(ui): added microphone and updated placeholder for voice mode in
[#26270](https://github.com/google-gemini/gemini-cli/pull/26270)
- feat(cli): Add 'list' subcommand to '/commands' in
[#22324](https://github.com/google-gemini/gemini-cli/pull/22324)
- fix(core): ensure tool output cleanup on session deletion for legacy files in
[#26263](https://github.com/google-gemini/gemini-cli/pull/26263)
- Docs: Update Agent Skills documentation in
[#22388](https://github.com/google-gemini/gemini-cli/pull/22388)
- test(acp): add missing coverage for extensions command error paths in
[#25313](https://github.com/google-gemini/gemini-cli/pull/25313)
- Changelog for v0.40.0 in
[#26245](https://github.com/google-gemini/gemini-cli/pull/26245)
- fix: report AgentExecutionBlocked in non-interactive programmatic modes in
[#26262](https://github.com/google-gemini/gemini-cli/pull/26262)
- feat(extensions): add 'delete' as an alias for /extensions uninstall in
[#25660](https://github.com/google-gemini/gemini-cli/pull/25660)
- fix(core): silently skip GEMINI.md paths that are directories (EISDIR) in
[#25662](https://github.com/google-gemini/gemini-cli/pull/25662)
- fix(ci): checkout PR branch instead of main in bot workflow in
[#26289](https://github.com/google-gemini/gemini-cli/pull/26289)
- fix(cli): use resolved sandbox state for auto-update check in
[#26285](https://github.com/google-gemini/gemini-cli/pull/26285)
- # Metrics Integrity & Standardized Reporting (BT-01) in [#26240](https://github.com/google-gemini/gemini-cli/pull/26240)
- Add Star History section to README in
[#26290](https://github.com/google-gemini/gemini-cli/pull/26290)
- Add Star History section to README in
[#26308](https://github.com/google-gemini/gemini-cli/pull/26308)
- Remove Star History section from README in
[#26309](https://github.com/google-gemini/gemini-cli/pull/26309)
- test(evals): add behavioral eval for file creation and write_file tool
selection in [#26292](https://github.com/google-gemini/gemini-cli/pull/26292)
- feat(config): enable Gemma 4 models by default via Gemini API in
[#26307](https://github.com/google-gemini/gemini-cli/pull/26307)
- fix(cli): insert voice transcription at cursor position instead of ap… in
[#26287](https://github.com/google-gemini/gemini-cli/pull/26287)
- fix(ui): fix issue with box edges in
[#26148](https://github.com/google-gemini/gemini-cli/pull/26148)
- fix(cli): respect .env override for GOOGLE_CLOUD_PROJECT in
[#26288](https://github.com/google-gemini/gemini-cli/pull/26288)
- fix(ci): robust version checking in release verification in
[#26337](https://github.com/google-gemini/gemini-cli/pull/26337)
- fix(cli): enable daemon relaunch in binary and bundle keytar in
[#26333](https://github.com/google-gemini/gemini-cli/pull/26333)
- fix(core): discourage unprompted git add . in prompt snippets in
[#26220](https://github.com/google-gemini/gemini-cli/pull/26220)
- feat(ui): added wave animation for voice mode in
[#26284](https://github.com/google-gemini/gemini-cli/pull/26284)
- fix(cli): prevent Escape from clearing input buffer (#17083) in
[#26339](https://github.com/google-gemini/gemini-cli/pull/26339)
- fix(cli): undeprecate --prompt and correct positional query docs in
[#26329](https://github.com/google-gemini/gemini-cli/pull/26329)
- Metrics updates in
[#26348](https://github.com/google-gemini/gemini-cli/pull/26348)
- fix(core): remove "System: Please continue." injection on InvalidStream events
in [#26340](https://github.com/google-gemini/gemini-cli/pull/26340)
- docs(policy-engine): add tool argument keys reference and shell policy
cross-links in
[#25292](https://github.com/google-gemini/gemini-cli/pull/25292)
- fix(cli): resolve Ghostty/raw-mode False Cancellation in oauth flow in
[#25026](https://github.com/google-gemini/gemini-cli/pull/25026)
- fix(core): reset session-scoped state on resumption in
[#26342](https://github.com/google-gemini/gemini-cli/pull/26342)
- Fix bulk of remaining issues with generalist profile in
[#26073](https://github.com/google-gemini/gemini-cli/pull/26073)
- fix(core): make subagents aware of active approval modes in
[#23608](https://github.com/google-gemini/gemini-cli/pull/23608)
- fix(acp): resolve agent mode disconnect and improve mode awareness in
[#26332](https://github.com/google-gemini/gemini-cli/pull/26332)
- docs(sdk): add JSDoc to exported interfaces in packages/sdk/src/types.ts in
[#26441](https://github.com/google-gemini/gemini-cli/pull/26441)
- perf: skip redundant GEMINI.md loading in partialConfig in
[#26443](https://github.com/google-gemini/gemini-cli/pull/26443)
- Enhance React guidelines in
[#22667](https://github.com/google-gemini/gemini-cli/pull/22667)
- feat(core): reinforce Inquiry constraints to prevent unauthorized changes in
[#26310](https://github.com/google-gemini/gemini-cli/pull/26310)
- revert: fix(ci): robust version checking in release verification (#26337) in
[#26450](https://github.com/google-gemini/gemini-cli/pull/26450)
- refactor(UI): created constants file for ThemeDialog in
[#26446](https://github.com/google-gemini/gemini-cli/pull/26446)
- docs: fix GitHub capitalization in releases guide in
[#26379](https://github.com/google-gemini/gemini-cli/pull/26379)
- fix(cli): ensure branch indicator updates in sub-directories and worktrees in
[#26330](https://github.com/google-gemini/gemini-cli/pull/26330)
- feat: add minimal V8 heap snapshot utility for memory diagnostics in
[#26440](https://github.com/google-gemini/gemini-cli/pull/26440)
- fix(hooks): preserve non-text parts in fromHookLLMRequest in
[#26275](https://github.com/google-gemini/gemini-cli/pull/26275)
- fix(cli): allow early stdout when config is undefined in
[#26453](https://github.com/google-gemini/gemini-cli/pull/26453)
- fix(cli)#21297: clear skills consent dialog before reload in
[#26431](https://github.com/google-gemini/gemini-cli/pull/26431)
- fix(cli): render LaTeX-style output as Unicode in the TUI in
[#25802](https://github.com/google-gemini/gemini-cli/pull/25802)
- fix(core): use close event instead of exit in child_process fallback in
[#25695](https://github.com/google-gemini/gemini-cli/pull/25695)
- feat(voice): add privacy and compliance UX warning for Gemini Live backend in
[#26454](https://github.com/google-gemini/gemini-cli/pull/26454)
- feat(memory): add Auto Memory inbox flow with canonical-patch contract in
[#26338](https://github.com/google-gemini/gemini-cli/pull/26338)
- test(cleanup): fix temporary directory leaks in test suites in
[#26217](https://github.com/google-gemini/gemini-cli/pull/26217)
- feat: add ignoreLocalEnv setting and --ignore-env flag (#2493) in
[#26445](https://github.com/google-gemini/gemini-cli/pull/26445)
- docs(sdk): add JSDoc to all exported interfaces and types in
[#26277](https://github.com/google-gemini/gemini-cli/pull/26277)
- feat(cli): improve /agents refresh logging in
[#26442](https://github.com/google-gemini/gemini-cli/pull/26442)
- Fix: make Dockerfile self-contained with multi-stage build in
[#24277](https://github.com/google-gemini/gemini-cli/pull/24277)
- fix(core): filter unsupported multimodal types from tool responses in
[#26352](https://github.com/google-gemini/gemini-cli/pull/26352)
- fix(core): properly format markdown in AskUser tool by unescaping newlines in
[#26349](https://github.com/google-gemini/gemini-cli/pull/26349)
- feat(bot): add actions spend metric script in
[#26463](https://github.com/google-gemini/gemini-cli/pull/26463)
- feat(cli): add /bug-memory command and auto-capture heap snapshot in /bug in
[#25639](https://github.com/google-gemini/gemini-cli/pull/25639)
- fix(cli): make SkillInboxDialog fit and scroll in alternate buffer in
[#26455](https://github.com/google-gemini/gemini-cli/pull/26455)
- Robust Scale-Safe Lifecycle Consolidation in
[#26355](https://github.com/google-gemini/gemini-cli/pull/26355)
- fix(ci): respect exempt labels when closing stale items in
[#26475](https://github.com/google-gemini/gemini-cli/pull/26475)
- fix(cli): use os.homedir() for home directory warning check in
[#25890](https://github.com/google-gemini/gemini-cli/pull/25890)
- fix(a2a-server): resolve tool approval race condition and improve status
reporting in [#26479](https://github.com/google-gemini/gemini-cli/pull/26479)
- fix(cli): prevent settings dialog border clipping using maxHeight in
[#26507](https://github.com/google-gemini/gemini-cli/pull/26507)
- feat: allow queuing messages during compression (#24071) in
[#26506](https://github.com/google-gemini/gemini-cli/pull/26506)
- fix(core): retry on ERR_STREAM_PREMATURE_CLOSE errors in
[#26519](https://github.com/google-gemini/gemini-cli/pull/26519)
- fix(core): Minor fixes for generalist profile. in
[#26357](https://github.com/google-gemini/gemini-cli/pull/26357)
- feat(core): steer model to use edit tool for surgical edits, fix a typo in
[#26480](https://github.com/google-gemini/gemini-cli/pull/26480)
- docs: clarify Auto Memory proposes memory updates and skills in
[#26527](https://github.com/google-gemini/gemini-cli/pull/26527)
- fix(core): reject numeric project IDs in GOOGLE_CLOUD_PROJECT (#24695) in
[#26532](https://github.com/google-gemini/gemini-cli/pull/26532)
- fix(core): remove unsafe type assertion suppressions in error utils in
[#19881](https://github.com/google-gemini/gemini-cli/pull/19881)
- fix(core): allow redirection in YOLO and AUTO_EDIT modes without sandboxing in
[#26542](https://github.com/google-gemini/gemini-cli/pull/26542)
- ci(release): build and attach unsigned macOS binaries to releases in
[#26462](https://github.com/google-gemini/gemini-cli/pull/26462)
- fix(core): Fix chat corruption bug in context manager. in
[#26534](https://github.com/google-gemini/gemini-cli/pull/26534)
- fix(cli): provide JSON output for AgentExecutionStopped in non-interactive
mode in [#26504](https://github.com/google-gemini/gemini-cli/pull/26504)
- feat(evals): add shell command safety evals in
[#26528](https://github.com/google-gemini/gemini-cli/pull/26528)
- fix(core): handle invalid custom plans directory gracefully in
[#26560](https://github.com/google-gemini/gemini-cli/pull/26560)
- fix(acp): move tool explanation from thought stream to tool call content in
[#26554](https://github.com/google-gemini/gemini-cli/pull/26554)
- fix(a2a-server): Resolve race condition in tool completion waiting in
[#26568](https://github.com/google-gemini/gemini-cli/pull/26568)
- fix(cli): randomize sandbox container names in
[#26014](https://github.com/google-gemini/gemini-cli/pull/26014)
- fix(core): Fix hysteresis in async context management pipelines. in
[#26452](https://github.com/google-gemini/gemini-cli/pull/26452)
- Tighten private Auto Memory patch allowlist in
[#26535](https://github.com/google-gemini/gemini-cli/pull/26535)
- fix(cli): hide read-only settings scopes in
[#26249](https://github.com/google-gemini/gemini-cli/pull/26249)
- fix(ci): preserve executable bit for mac binaries in
[#26600](https://github.com/google-gemini/gemini-cli/pull/26600)
- fix(cli): improve mcp list UX in untrusted folders in
[#26457](https://github.com/google-gemini/gemini-cli/pull/26457)
- fix(core): prevent silent hang during OAuth auth on headless Linux in
[#26571](https://github.com/google-gemini/gemini-cli/pull/26571)
- Changelog for v0.42.0-preview.0 in
[#26537](https://github.com/google-gemini/gemini-cli/pull/26537)
- ci: fix Argument list too long in triage workflows in
[#26603](https://github.com/google-gemini/gemini-cli/pull/26603)
- refactor(cli): migrate core tools to native ToolDisplay property and fix UI
rendering in [#25186](https://github.com/google-gemini/gemini-cli/pull/25186)
- don't wrap args unnecessarily in
[#26599](https://github.com/google-gemini/gemini-cli/pull/26599)
- fix(core): preserve system PATH in Git environment to fix ENOENT (#25034) in
[#26587](https://github.com/google-gemini/gemini-cli/pull/26587)
- fix(routing): fix resolveClassifierModel argument mismatch in
ApprovalModeStrategy in
[#26658](https://github.com/google-gemini/gemini-cli/pull/26658)
- docs: add vi mode shortcuts and clarify MCP/custom sandbox setup in
[#23853](https://github.com/google-gemini/gemini-cli/pull/23853)
- fix(ux): fixed issue with transcribed text not showing after releasing space
in [#26609](https://github.com/google-gemini/gemini-cli/pull/26609)
- ci: fix json parsing in scheduled triage workflow in
[#26656](https://github.com/google-gemini/gemini-cli/pull/26656)
- fix(cli): hide /memory add subcommand when memoryV2 is enabled in
[#26605](https://github.com/google-gemini/gemini-cli/pull/26605)
- fix: prevent false command conflicts when launching from home directory in
[#23069](https://github.com/google-gemini/gemini-cli/pull/23069)
- fix(core): cache model routing decision in LocalAgentExecutor in
[#26548](https://github.com/google-gemini/gemini-cli/pull/26548)
- Changelog for v0.42.0-preview.2 in
[#26597](https://github.com/google-gemini/gemini-cli/pull/26597)
- skip broken test in
[#26705](https://github.com/google-gemini/gemini-cli/pull/26705)
- feat: export session to file and import via flag in
[#26514](https://github.com/google-gemini/gemini-cli/pull/26514)
- Feat: Add Machine Hostname to CLI interface in
[#25637](https://github.com/google-gemini/gemini-cli/pull/25637)
- docs(extensions): refactor releasing guide and add update mechanisms in
[#26595](https://github.com/google-gemini/gemini-cli/pull/26595)
- fix(ci): fix maintainer identification in lifecycle manager in
[#26706](https://github.com/google-gemini/gemini-cli/pull/26706)
- fix(ui): added quotes around session id in resume tip in
[#26669](https://github.com/google-gemini/gemini-cli/pull/26669)
- Changelog for v0.41.0 in
[#26670](https://github.com/google-gemini/gemini-cli/pull/26670)
- refactor(core): agent session protocol changes in
[#26661](https://github.com/google-gemini/gemini-cli/pull/26661)
- fix(context): implement loose boundary policy for gc backstop. in
[#26594](https://github.com/google-gemini/gemini-cli/pull/26594)
- fix(core): throw explicit error on dropped tool responses in
[#26668](https://github.com/google-gemini/gemini-cli/pull/26668)
- fix: resolve "function response turn must come immediately after function
call" error in
[#26691](https://github.com/google-gemini/gemini-cli/pull/26691)
- fix(core): resolve parallel tool call streaming ID collision in
[#26646](https://github.com/google-gemini/gemini-cli/pull/26646)
- feat(core): add LocalSubagentProtocol behind AgentProtocol in
[#25302](https://github.com/google-gemini/gemini-cli/pull/25302)
- fix(cli): remove noisy theme registration logs from terminal in
[#25858](https://github.com/google-gemini/gemini-cli/pull/25858)
- ci: implement codebase-aware effort level triage in
[#26666](https://github.com/google-gemini/gemini-cli/pull/26666)
- feat(acp/core): prefix tool call IDs with tool names to support tool rendering
in ACP compliant IDEs. in
[#26676](https://github.com/google-gemini/gemini-cli/pull/26676)
- fix(mcp): treat GET 404 as 405 in StreamableHTTPClientTransport in
[#24847](https://github.com/google-gemini/gemini-cli/pull/24847)
- feat(core): add RemoteSubagentProtocol behind AgentProtocol in
[#25303](https://github.com/google-gemini/gemini-cli/pull/25303)
- feat(context): Improvements to the snapshotter. in
[#26655](https://github.com/google-gemini/gemini-cli/pull/26655)
- fix(context): Change snapshotter model config. in
[#26745](https://github.com/google-gemini/gemini-cli/pull/26745)
- fix(cli): allow installing extensions from ssh repo in
[#26274](https://github.com/google-gemini/gemini-cli/pull/26274)
- fix(cli): prevent duplicate SessionStart systemMessage render in
[#25827](https://github.com/google-gemini/gemini-cli/pull/25827)
- fix(cli/acp): prevent infinite thought loop in ACP mode by disablig
nextSpeakerCheck in
[#26874](https://github.com/google-gemini/gemini-cli/pull/26874)
- fix(cli): use static tool name in confirmation prompt to avoid parsing errors
in [#26866](https://github.com/google-gemini/gemini-cli/pull/26866)
- fix(routing): Refactor tool turn handling for the conversation history in
NumericalClassifierStrategy to prevent 400 Bad Request in
[#26761](https://github.com/google-gemini/gemini-cli/pull/26761)
- fix(core): handle malformed projects.json in ProjectRegistry in
[#26885](https://github.com/google-gemini/gemini-cli/pull/26885)
- fix(ui): added a gutter width to the input prompt width calculation in
[#26882](https://github.com/google-gemini/gemini-cli/pull/26882)
- fix: prevent EISDIR crash when customIgnoreFilePaths contains directories
(#19868) in [#19898](https://github.com/google-gemini/gemini-cli/pull/19898)
- revert 6b9b778d821728427eea07b1b97ba07378137d0b in
[#26893](https://github.com/google-gemini/gemini-cli/pull/26893)
- Fix/vscode run current file ts in
[#22894](https://github.com/google-gemini/gemini-cli/pull/22894)
- Allow Enter to select session while in search mode in /resume in
[#21523](https://github.com/google-gemini/gemini-cli/pull/21523)
- fix(core): ignore .pak and .rpa game archive formats by default in
[#26884](https://github.com/google-gemini/gemini-cli/pull/26884)
- fix(cli): enable adk non-interactive session in
[#26895](https://github.com/google-gemini/gemini-cli/pull/26895)
- fix(cli): restore resume for legacy sessions in
[#26577](https://github.com/google-gemini/gemini-cli/pull/26577)
- fix: respect explicit model selection after Flash quota exhaustion (#26759) in
[#26872](https://github.com/google-gemini/gemini-cli/pull/26872)
- feat(context): Introduce adaptive token calculator to more accurately
calculate content sizes. in
[#26888](https://github.com/google-gemini/gemini-cli/pull/26888)
- chore: update checkout action configuration in workflows in
[#26897](https://github.com/google-gemini/gemini-cli/pull/26897)
- fix (telemetry): inject quota_project_id to prevent fallback to default oauth
client in [#26698](https://github.com/google-gemini/gemini-cli/pull/26698)
- Exclude extension context from skill extraction agent in
[#26879](https://github.com/google-gemini/gemini-cli/pull/26879)
- Enable NumericalRouter when using dynamic model configs in
[#26929](https://github.com/google-gemini/gemini-cli/pull/26929)
- ci: actively triage missing priority labels and intelligently clean up
conflicting labels in
[#26865](https://github.com/google-gemini/gemini-cli/pull/26865)
- refactor(core): introduce SubagentState enum for progress in
[#26934](https://github.com/google-gemini/gemini-cli/pull/26934)
- fix(ci): replace brittle --no-tag with explicit staging-tmp tag in
[#26940](https://github.com/google-gemini/gemini-cli/pull/26940)
- Incremental refactor repo agent towards skills-based composition in
[#26717](https://github.com/google-gemini/gemini-cli/pull/26717)
- fix(ui): fixed line wrap padding for selection lists in
[#26944](https://github.com/google-gemini/gemini-cli/pull/26944)
- fix(core): update read_file schema for v1 compatibility (#22183) in
[#26922](https://github.com/google-gemini/gemini-cli/pull/26922)
- fix(ci): configure git remote with token for authentication in
[#26949](https://github.com/google-gemini/gemini-cli/pull/26949)
**Full Changelog**:
https://github.com/google-gemini/gemini-cli/compare/v0.41.0-preview.3...v0.42.0-preview.2
https://github.com/google-gemini/gemini-cli/compare/v0.42.0-preview.2...v0.43.0-preview.0
+56 -46
View File
@@ -882,9 +882,10 @@ their corresponding top-level category object in your `settings.json` file.
}
},
"auto": {
"displayName": "Auto",
"tier": "auto",
"isPreview": true,
"isVisible": false,
"isVisible": true,
"features": {
"thinking": true,
"multimodalToolUse": false
@@ -918,26 +919,16 @@ their corresponding top-level category object in your `settings.json` file.
}
},
"auto-gemini-3": {
"displayName": "Auto (Gemini 3)",
"tier": "auto",
"family": "gemini-3",
"isPreview": true,
"isVisible": true,
"dialogDescription": "Let Gemini CLI decide the best model for the task: gemini-3-pro, gemini-3-flash",
"features": {
"thinking": true,
"multimodalToolUse": false
}
"isVisible": false
},
"auto-gemini-2.5": {
"displayName": "Auto (Gemini 2.5)",
"tier": "auto",
"family": "gemini-2.5",
"isPreview": false,
"isVisible": true,
"dialogDescription": "Let Gemini CLI decide the best model for the task: gemini-2.5-pro, gemini-2.5-flash",
"features": {
"thinking": false,
"multimodalToolUse": false
}
"isVisible": false
}
}
```
@@ -1020,33 +1011,15 @@ their corresponding top-level category object in your `settings.json` file.
}
]
},
"auto-gemini-3": {
"default": "gemini-3-pro-preview",
"contexts": [
{
"condition": {
"hasAccessToPreview": false
},
"target": "gemini-2.5-pro"
},
{
"condition": {
"useGemini3_1": true,
"useCustomTools": true
},
"target": "gemini-3.1-pro-preview-customtools"
},
{
"condition": {
"useGemini3_1": true
},
"target": "gemini-3.1-pro-preview"
}
]
},
"auto": {
"default": "gemini-3-pro-preview",
"contexts": [
{
"condition": {
"releaseChannel": "stable"
},
"target": "gemini-2.5-pro"
},
{
"condition": {
"hasAccessToPreview": false
@@ -1092,9 +1065,6 @@ their corresponding top-level category object in your `settings.json` file.
}
]
},
"auto-gemini-2.5": {
"default": "gemini-2.5-pro"
},
"gemini-3.1-flash-lite-preview": {
"default": "gemini-3.1-flash-lite-preview",
"contexts": [
@@ -1127,6 +1097,33 @@ their corresponding top-level category object in your `settings.json` file.
"target": "gemini-3.1-flash-lite-preview"
}
]
},
"auto-gemini-3": {
"default": "gemini-3-pro-preview",
"contexts": [
{
"condition": {
"hasAccessToPreview": false
},
"target": "gemini-2.5-pro"
},
{
"condition": {
"useGemini3_1": true,
"useCustomTools": true
},
"target": "gemini-3.1-pro-preview-customtools"
},
{
"condition": {
"useGemini3_1": true
},
"target": "gemini-3.1-pro-preview"
}
]
},
"auto-gemini-2.5": {
"default": "gemini-2.5-pro"
}
}
```
@@ -1145,15 +1142,15 @@ their corresponding top-level category object in your `settings.json` file.
"contexts": [
{
"condition": {
"requestedModels": ["auto-gemini-2.5", "gemini-2.5-pro"]
"hasAccessToPreview": false
},
"target": "gemini-2.5-flash"
},
{
"condition": {
"requestedModels": ["auto-gemini-3", "gemini-3-pro-preview"]
"requestedModels": ["gemini-2.5-pro", "auto-gemini-2.5"]
},
"target": "gemini-3-flash-preview"
"target": "gemini-2.5-flash"
}
]
},
@@ -1162,7 +1159,20 @@ their corresponding top-level category object in your `settings.json` file.
"contexts": [
{
"condition": {
"requestedModels": ["auto-gemini-2.5", "gemini-2.5-pro"]
"hasAccessToPreview": false
},
"target": "gemini-2.5-pro"
},
{
"condition": {
"releaseChannel": "stable",
"requestedModels": ["auto"]
},
"target": "gemini-2.5-pro"
},
{
"condition": {
"requestedModels": ["gemini-2.5-pro", "auto-gemini-2.5"]
},
"target": "gemini-2.5-pro"
},
+1 -1
View File
@@ -172,7 +172,7 @@ describe('file-system', () => {
).toBeDefined();
const newFileContent = rig.readFile(fileName);
expect(newFileContent).toBe('1.0.1');
expect(newFileContent.trimEnd()).toBe('1.0.1');
});
it.skip('should replace multiple instances of a string', async () => {
+9 -9
View File
@@ -1,12 +1,12 @@
{
"name": "@google/gemini-cli",
"version": "0.42.0-nightly.20260428.g59b2dea0e",
"version": "0.44.0-nightly.20260512.g022e8baef",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@google/gemini-cli",
"version": "0.42.0-nightly.20260428.g59b2dea0e",
"version": "0.44.0-nightly.20260512.g022e8baef",
"workspaces": [
"packages/*"
],
@@ -18077,7 +18077,7 @@
},
"packages/a2a-server": {
"name": "@google/gemini-cli-a2a-server",
"version": "0.42.0-nightly.20260428.g59b2dea0e",
"version": "0.44.0-nightly.20260512.g022e8baef",
"dependencies": {
"@a2a-js/sdk": "0.3.11",
"@google-cloud/storage": "^7.16.0",
@@ -18206,7 +18206,7 @@
},
"packages/cli": {
"name": "@google/gemini-cli",
"version": "0.42.0-nightly.20260428.g59b2dea0e",
"version": "0.44.0-nightly.20260512.g022e8baef",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^0.16.1",
@@ -18354,7 +18354,7 @@
},
"packages/core": {
"name": "@google/gemini-cli-core",
"version": "0.42.0-nightly.20260428.g59b2dea0e",
"version": "0.44.0-nightly.20260512.g022e8baef",
"license": "Apache-2.0",
"dependencies": {
"@a2a-js/sdk": "0.3.11",
@@ -18665,7 +18665,7 @@
},
"packages/devtools": {
"name": "@google/gemini-cli-devtools",
"version": "0.42.0-nightly.20260428.g59b2dea0e",
"version": "0.44.0-nightly.20260512.g022e8baef",
"license": "Apache-2.0",
"dependencies": {
"ws": "^8.16.0"
@@ -18680,7 +18680,7 @@
},
"packages/sdk": {
"name": "@google/gemini-cli-sdk",
"version": "0.42.0-nightly.20260428.g59b2dea0e",
"version": "0.44.0-nightly.20260512.g022e8baef",
"license": "Apache-2.0",
"dependencies": {
"@google/gemini-cli-core": "file:../core",
@@ -18711,7 +18711,7 @@
},
"packages/test-utils": {
"name": "@google/gemini-cli-test-utils",
"version": "0.42.0-nightly.20260428.g59b2dea0e",
"version": "0.44.0-nightly.20260512.g022e8baef",
"license": "Apache-2.0",
"dependencies": {
"@google/gemini-cli-core": "file:../core",
@@ -18743,7 +18743,7 @@
},
"packages/vscode-ide-companion": {
"name": "gemini-cli-vscode-ide-companion",
"version": "0.42.0-nightly.20260428.g59b2dea0e",
"version": "0.44.0-nightly.20260512.g022e8baef",
"license": "LICENSE",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.23.0",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@google/gemini-cli",
"version": "0.42.0-nightly.20260428.g59b2dea0e",
"version": "0.44.0-nightly.20260512.g022e8baef",
"engines": {
"node": ">=20.0.0"
},
@@ -14,7 +14,7 @@
"url": "git+https://github.com/google-gemini/gemini-cli.git"
},
"config": {
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.42.0-nightly.20260428.g59b2dea0e"
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.44.0-nightly.20260512.g022e8baef"
},
"scripts": {
"start": "cross-env NODE_ENV=development node scripts/start.js",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@google/gemini-cli-a2a-server",
"version": "0.42.0-nightly.20260428.g59b2dea0e",
"version": "0.44.0-nightly.20260512.g022e8baef",
"description": "Gemini CLI A2A Server",
"repository": {
"type": "git",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@google/gemini-cli",
"version": "0.42.0-nightly.20260428.g59b2dea0e",
"version": "0.44.0-nightly.20260512.g022e8baef",
"description": "Gemini CLI",
"license": "Apache-2.0",
"repository": {
@@ -27,7 +27,7 @@
"dist"
],
"config": {
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.42.0-nightly.20260428.g59b2dea0e"
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.44.0-nightly.20260512.g022e8baef"
},
"dependencies": {
"@agentclientprotocol/sdk": "^0.16.1",
+5 -2
View File
@@ -60,8 +60,11 @@ export class AcpFileSystemService implements FileSystemService {
sessionId: this.sessionId,
});
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return response.content;
const content: unknown = response.content;
if (typeof content !== 'string') {
throw new Error('content must be a string'); // replace with other response type formats when modified in the future
}
return content;
} catch (err: unknown) {
this.normalizeFileSystemError(err);
}
@@ -19,6 +19,7 @@ import type * as acp from '@agentclientprotocol/sdk';
import {
AuthType,
type Config,
GEMINI_MODEL_ALIAS_AUTO,
type MessageBus,
type Storage,
} from '@google/gemini-cli-core';
@@ -208,7 +209,7 @@ describe('AcpSessionManager', () => {
expect(response.models?.availableModels).toEqual(
expect.arrayContaining([
expect.objectContaining({
modelId: 'auto-gemini-3',
modelId: GEMINI_MODEL_ALIAS_AUTO,
name: expect.stringContaining('Auto'),
}),
]),
+10 -17
View File
@@ -10,8 +10,7 @@ import {
type ToolCallConfirmationDetails,
Kind,
ApprovalMode,
DEFAULT_GEMINI_MODEL_AUTO,
PREVIEW_GEMINI_MODEL_AUTO,
GEMINI_MODEL_ALIAS_AUTO,
DEFAULT_GEMINI_MODEL,
DEFAULT_GEMINI_FLASH_MODEL,
DEFAULT_GEMINI_FLASH_LITE_MODEL,
@@ -23,6 +22,8 @@ import {
getDisplayString,
AuthType,
ToolConfirmationOutcome,
getChannelFromVersion,
getAutoModelDescription,
} from '@google/gemini-cli-core';
import type * as acp from '@agentclientprotocol/sdk';
import { z } from 'zod';
@@ -262,7 +263,7 @@ export function buildAvailableModels(
}>;
currentModelId: string;
} {
const preferredModel = config.getModel() || DEFAULT_GEMINI_MODEL_AUTO;
const preferredModel = config.getModel() || GEMINI_MODEL_ALIAS_AUTO;
const shouldShowPreviewModels = config.getHasAccessToPreviewModel();
const useGemini31 = config.getGemini31LaunchedSync?.() ?? false;
const useGemini31FlashLite =
@@ -271,6 +272,8 @@ export function buildAvailableModels(
const useCustomToolModel =
useGemini31 && selectedAuthType === AuthType.USE_GEMINI;
const releaseChannel = getChannelFromVersion(config.clientVersion);
// --- DYNAMIC PATH ---
if (
config.getExperimentalDynamicModelConfiguration?.() === true &&
@@ -281,6 +284,7 @@ export function buildAvailableModels(
useGemini3_1FlashLite: useGemini31FlashLite,
useCustomTools: useCustomToolModel,
hasAccessToPreview: shouldShowPreviewModels,
releaseChannel,
});
return {
@@ -292,23 +296,12 @@ export function buildAvailableModels(
// --- LEGACY PATH ---
const mainOptions = [
{
value: DEFAULT_GEMINI_MODEL_AUTO,
title: getDisplayString(DEFAULT_GEMINI_MODEL_AUTO),
description:
'Let Gemini CLI decide the best model for the task: gemini-2.5-pro, gemini-2.5-flash',
value: GEMINI_MODEL_ALIAS_AUTO,
title: getDisplayString(GEMINI_MODEL_ALIAS_AUTO),
description: getAutoModelDescription(releaseChannel, useGemini31),
},
];
if (shouldShowPreviewModels) {
mainOptions.unshift({
value: PREVIEW_GEMINI_MODEL_AUTO,
title: getDisplayString(PREVIEW_GEMINI_MODEL_AUTO),
description: useGemini31
? 'Let Gemini CLI decide the best model for the task: gemini-3.1-pro, gemini-3-flash'
: 'Let Gemini CLI decide the best model for the task: gemini-3-pro, gemini-3-flash',
});
}
const manualOptions = [
{
value: DEFAULT_GEMINI_MODEL,
@@ -27,7 +27,7 @@ export interface ConfigLogger {
export type RequestSettingCallback = (
setting: ExtensionSetting,
) => Promise<string>;
) => Promise<string | undefined>;
export type RequestConfirmationCallback = (message: string) => Promise<boolean>;
const defaultLogger: ConfigLogger = {
@@ -47,8 +47,7 @@ const defaultRequestConfirmation: RequestConfirmationCallback = async (
message,
initial: false,
});
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return response.confirm;
return typeof response.confirm === 'boolean' ? response.confirm : false;
};
export async function getExtensionManager() {
+11 -2
View File
@@ -8,6 +8,15 @@ import { AuthType } from '@google/gemini-cli-core';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { validateAuthMethod } from './auth.js';
vi.mock('@google/gemini-cli-core', async (importOriginal) => {
const actual =
await importOriginal<typeof import('@google/gemini-cli-core')>();
return {
...actual,
loadApiKey: vi.fn().mockResolvedValue(null),
};
});
vi.mock('./settings.js', () => ({
loadEnvironment: vi.fn(),
loadSettings: vi.fn().mockReturnValue({
@@ -90,10 +99,10 @@ describe('validateAuthMethod', () => {
envs: {},
expected: 'Invalid auth method selected.',
},
])('$description', ({ authType, envs, expected }) => {
])('$description', async ({ authType, envs, expected }) => {
for (const [key, value] of Object.entries(envs)) {
vi.stubEnv(key, value as string);
}
expect(validateAuthMethod(authType)).toBe(expected);
expect(await validateAuthMethod(authType)).toBe(expected);
});
});
+6 -3
View File
@@ -4,10 +4,12 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { AuthType } from '@google/gemini-cli-core';
import { AuthType, loadApiKey } from '@google/gemini-cli-core';
import { loadEnvironment, loadSettings } from './settings.js';
export function validateAuthMethod(authMethod: string): string | null {
export async function validateAuthMethod(
authMethod: string,
): Promise<string | null> {
loadEnvironment(loadSettings().merged, process.cwd());
if (
authMethod === AuthType.LOGIN_WITH_GOOGLE ||
@@ -17,7 +19,8 @@ export function validateAuthMethod(authMethod: string): string | null {
}
if (authMethod === AuthType.USE_GEMINI) {
if (!process.env['GEMINI_API_KEY']) {
const key = process.env['GEMINI_API_KEY'] || (await loadApiKey());
if (!key) {
return (
'When using Gemini API, you must specify the GEMINI_API_KEY environment variable.\n' +
'Update your environment and try again (no reload needed if using .env)!'
+2 -2
View File
@@ -2058,7 +2058,7 @@ describe('loadCliConfig model selection', () => {
argv,
);
expect(config.getModel()).toBe('auto-gemini-3');
expect(config.getModel()).toBe('auto');
});
it('always prefers model from argv', async () => {
@@ -2102,7 +2102,7 @@ describe('loadCliConfig model selection', () => {
argv,
);
expect(config.getModel()).toBe('auto-gemini-3');
expect(config.getModel()).toBe('auto');
});
});
+1 -2
View File
@@ -30,7 +30,6 @@ import {
loadServerHierarchicalMemory,
ASK_USER_TOOL_NAME,
getVersion,
PREVIEW_GEMINI_MODEL_AUTO,
type HierarchicalMemory,
coreEvents,
GEMINI_MODEL_ALIAS_AUTO,
@@ -866,7 +865,7 @@ export async function loadCliConfig(
interactive,
);
const defaultModel = PREVIEW_GEMINI_MODEL_AUTO;
const defaultModel = GEMINI_MODEL_ALIAS_AUTO;
const rawModel =
argv.model || process.env['GEMINI_MODEL'] || settings.model?.name;
+5 -3
View File
@@ -88,7 +88,9 @@ interface ExtensionManagerParams {
enabledExtensionOverrides?: string[];
settings: MergedSettings;
requestConsent: (consent: string) => Promise<boolean>;
requestSetting: ((setting: ExtensionSetting) => Promise<string>) | null;
requestSetting:
| ((setting: ExtensionSetting) => Promise<string | undefined>)
| null;
workspaceDir: string;
eventEmitter?: EventEmitter<ExtensionEvents>;
clientVersion?: string;
@@ -106,7 +108,7 @@ export class ExtensionManager extends ExtensionLoader {
private settings: MergedSettings;
private requestConsent: (consent: string) => Promise<boolean>;
private requestSetting:
| ((setting: ExtensionSetting) => Promise<string>)
| ((setting: ExtensionSetting) => Promise<string | undefined>)
| undefined;
private telemetryConfig: Config;
private workspaceDir: string;
@@ -161,7 +163,7 @@ export class ExtensionManager extends ExtensionLoader {
}
setRequestSetting(
requestSetting?: (setting: ExtensionSetting) => Promise<string>,
requestSetting?: (setting: ExtensionSetting) => Promise<string | undefined>,
): void {
this.requestSetting = requestSetting;
}
@@ -94,9 +94,8 @@ export class ExtensionRegistryClient {
fuzzy: true,
});
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const results = await fzf.find(query);
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return results.map((r: { item: RegistryExtension }) => r.item);
const results: Array<{ item: RegistryExtension }> = await fzf.find(query);
return results.map((r) => r.item);
}
async getExtension(id: string): Promise<RegistryExtension | undefined> {
@@ -8,6 +8,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { coreEvents, type GeminiCLIExtension } from '@google/gemini-cli-core';
import { ExtensionStorage } from './storage.js';
import { z } from 'zod';
export interface ExtensionEnablementConfig {
overrides: string[];
@@ -179,8 +180,12 @@ export class ExtensionEnablementManager {
readConfig(): AllExtensionsEnablementConfig {
try {
const content = fs.readFileSync(this.configFilePath, 'utf-8');
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return JSON.parse(content);
const parsed: unknown = JSON.parse(content);
const schema = z.record(
z.string(),
z.object({ overrides: z.array(z.string()) }),
);
return schema.parse(parsed);
} catch (error) {
if (
error instanceof Error &&
@@ -62,7 +62,7 @@ export const getEnvFilePath = (
export async function maybePromptForSettings(
extensionConfig: ExtensionConfig,
extensionId: string,
requestSetting: (setting: ExtensionSetting) => Promise<string>,
requestSetting: (setting: ExtensionSetting) => Promise<string | undefined>,
previousExtensionConfig?: ExtensionConfig,
previousSettings?: Record<string, string>,
): Promise<void> {
@@ -106,7 +106,9 @@ export async function maybePromptForSettings(
settingsChanges.promptForEnv,
)) {
const answer = await requestSetting(setting);
allSettings[setting.envVar] = answer;
if (answer !== undefined) {
allSettings[setting.envVar] = answer;
}
}
const nonSensitiveSettings: Record<string, string> = {};
@@ -159,14 +161,13 @@ function formatEnvContent(settings: Record<string, string>): string {
export async function promptForSetting(
setting: ExtensionSetting,
): Promise<string> {
): Promise<string | undefined> {
const response = await prompts({
type: setting.sensitive ? 'password' : 'text',
name: 'value',
message: `${setting.name}\n${setting.description}`,
});
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return response.value;
return typeof response.value === 'string' ? response.value : undefined;
}
export async function getScopedEnvContents(
@@ -230,7 +231,7 @@ export async function updateSetting(
extensionConfig: ExtensionConfig,
extensionId: string,
settingKey: string,
requestSetting: (setting: ExtensionSetting) => Promise<string>,
requestSetting: (setting: ExtensionSetting) => Promise<string | undefined>,
scope: ExtensionSettingScope,
workspaceDir: string,
): Promise<void> {
@@ -250,6 +251,10 @@ export async function updateSetting(
}
const newValue = await requestSetting(settingToUpdate);
if (newValue === undefined) {
return;
}
const keychain = new KeychainTokenStorage(
getKeychainStorageName(extensionName, extensionId, scope, workspaceDir),
);
@@ -67,8 +67,7 @@ export function recursivelyHydrateStrings<T>(
}
if (Array.isArray(obj)) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
return obj.map((item) =>
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return (obj as unknown[]).map((item) =>
recursivelyHydrateStrings(item, values),
) as unknown as T;
}
+5 -1
View File
@@ -3471,7 +3471,11 @@ export const SETTINGS_SCHEMA_DEFINITIONS: Record<
family: { type: 'string' },
isPreview: { type: 'boolean' },
isVisible: { type: 'boolean' },
dialogDescription: { type: 'string' },
dialogDescription: {
type: 'string',
description:
"A description of the model to display in the model selection dialog. For the 'auto' alias, this value is dynamically generated and any value provided here will be ignored.",
},
features: {
type: 'object',
properties: {
+42
View File
@@ -275,6 +275,10 @@ vi.mock('./validateNonInterActiveAuth.js', () => ({
validateNonInteractiveAuth: vi.fn().mockResolvedValue('google'),
}));
vi.mock('./config/auth.js', () => ({
validateAuthMethod: vi.fn().mockResolvedValue(null),
}));
describe('gemini.tsx main function', () => {
let originalIsTTY: boolean | undefined;
let initialUnhandledRejectionListeners: NodeJS.UnhandledRejectionListener[] =
@@ -1276,6 +1280,44 @@ describe('gemini.tsx main function exit codes', () => {
}
});
it('should exit with 41 for validateAuthMethod failure during sandbox setup', async () => {
vi.stubEnv('SANDBOX', '');
vi.mocked(loadSandboxConfig).mockResolvedValue(
createMockSandboxConfig({
command: 'docker',
image: 'test-image',
}),
);
vi.mocked(loadCliConfig).mockResolvedValue(
createMockConfig({
refreshAuth: vi.fn().mockResolvedValue(undefined),
getRemoteAdminSettings: vi.fn().mockReturnValue(undefined),
isInteractive: vi.fn().mockReturnValue(true),
}),
);
vi.mocked(loadSettings).mockReturnValue(
createMockSettings({
merged: {
security: { auth: { selectedType: 'google', useExternal: false } },
},
}),
);
vi.mocked(parseArguments).mockResolvedValue({} as CliArgs);
const authModule = await import('./config/auth.js');
vi.mocked(authModule.validateAuthMethod).mockResolvedValueOnce(
'Auth method invalid',
);
try {
await main();
expect.fail('Should have thrown MockProcessExitError');
} catch (e) {
expect(e).toBeInstanceOf(MockProcessExitError);
expect((e as MockProcessExitError).code).toBe(41);
}
});
it('should exit with 41 for auth failure during sandbox setup', async () => {
vi.stubEnv('SANDBOX', '');
vi.mocked(loadSandboxConfig).mockResolvedValue(
+1 -1
View File
@@ -514,7 +514,7 @@ export async function main() {
partialConfig.isInteractive() &&
settings.merged.security.auth.selectedType
) {
const err = validateAuthMethod(
const err = await validateAuthMethod(
settings.merged.security.auth.selectedType,
);
if (err) {
@@ -112,5 +112,11 @@ export const createMockCommandContext = (
return output;
};
return merge(defaultMocks, overrides);
const merged: unknown = merge(defaultMocks, overrides);
const isCommandContext = (val: unknown): val is CommandContext =>
typeof val === 'object' && val !== null;
if (isCommandContext(merged)) {
return merged;
}
throw new Error('Unreachable');
};
+34
View File
@@ -150,6 +150,9 @@ vi.mock('./hooks/useQuotaAndFallback.js');
vi.mock('./hooks/useHistoryManager.js');
vi.mock('./hooks/useThemeCommand.js');
vi.mock('./auth/useAuth.js');
vi.mock('../config/auth.js', () => ({
validateAuthMethod: vi.fn().mockResolvedValue(null),
}));
vi.mock('./hooks/useEditorSettings.js');
vi.mock('./hooks/useSettingsCommand.js');
vi.mock('./hooks/useModelCommand.js');
@@ -217,6 +220,7 @@ vi.mock('../utils/cleanup.js');
import { useHistory } from './hooks/useHistoryManager.js';
import { useThemeCommand } from './hooks/useThemeCommand.js';
import { useAuthCommand } from './auth/useAuth.js';
import { validateAuthMethod } from '../config/auth.js';
import { useEditorSettings } from './hooks/useEditorSettings.js';
import { useSettingsCommand } from './hooks/useSettingsCommand.js';
import { useModelCommand } from './hooks/useModelCommand.js';
@@ -576,6 +580,36 @@ describe('AppContainer State Management', () => {
});
describe('State Initialization', () => {
it('calls validateAuthMethod and onAuthError if validation fails', async () => {
const mockOnAuthError = vi.fn();
mockedUseAuthCommand.mockReturnValue({
authState: 'authenticated',
setAuthState: vi.fn(),
authError: null,
onAuthError: mockOnAuthError,
});
vi.mocked(validateAuthMethod).mockResolvedValueOnce('Validation Failed');
const { unmount } = await act(async () =>
renderAppContainer({
settings: createMockSettings({
merged: {
security: {
auth: { selectedType: 'oauth-personal', useExternal: false },
},
},
}),
}),
);
await waitFor(() => {
expect(validateAuthMethod).toHaveBeenCalledWith('oauth-personal');
expect(mockOnAuthError).toHaveBeenCalledWith('Validation Failed');
});
unmount();
});
it('sends a macOS notification when confirmation is pending and terminal is unfocused', async () => {
mockedUseFocusState.mockReturnValue({
isFocused: false,
+16 -6
View File
@@ -912,12 +912,22 @@ Logging in with Google... Restarting Gemini CLI to continue.
return;
}
const error = validateAuthMethod(
settings.merged.security.auth.selectedType,
);
if (error) {
onAuthError(error);
}
const authMethod = settings.merged.security.auth.selectedType;
void (async () => {
try {
const error = await validateAuthMethod(authMethod);
if (
error &&
authMethod === settings.merged.security.auth.selectedType
) {
onAuthError(error);
}
} catch (e) {
if (authMethod === settings.merged.security.auth.selectedType) {
onAuthError(getErrorMessage(e));
}
}
})();
}
}, [
settings.merged.security.auth.selectedType,
+11 -11
View File
@@ -215,11 +215,11 @@ describe('AuthDialog', () => {
describe('handleAuthSelect', () => {
it('calls onAuthError if validation fails', async () => {
mockedValidateAuthMethod.mockReturnValue('Invalid method');
mockedValidateAuthMethod.mockResolvedValue('Invalid method');
const { unmount } = await renderWithProviders(<AuthDialog {...props} />);
const { onSelect: handleAuthSelect } =
mockedRadioButtonSelect.mock.calls[0][0];
handleAuthSelect(AuthType.USE_GEMINI);
await handleAuthSelect(AuthType.USE_GEMINI);
expect(mockedValidateAuthMethod).toHaveBeenCalledWith(
AuthType.USE_GEMINI,
@@ -231,7 +231,7 @@ describe('AuthDialog', () => {
});
it('sets auth context with requiresRestart: true for LOGIN_WITH_GOOGLE', async () => {
mockedValidateAuthMethod.mockReturnValue(null);
mockedValidateAuthMethod.mockResolvedValue(null);
const { unmount } = await renderWithProviders(<AuthDialog {...props} />);
const { onSelect: handleAuthSelect } =
mockedRadioButtonSelect.mock.calls[0][0];
@@ -245,7 +245,7 @@ describe('AuthDialog', () => {
it('sets auth context with requiresRestart: true for USE_VERTEX_AI in Cloud Shell', async () => {
vi.stubEnv('CLOUD_SHELL', 'true');
mockedValidateAuthMethod.mockReturnValue(null);
mockedValidateAuthMethod.mockResolvedValue(null);
const { unmount } = await renderWithProviders(<AuthDialog {...props} />);
const { onSelect: handleAuthSelect } =
mockedRadioButtonSelect.mock.calls[0][0];
@@ -259,7 +259,7 @@ describe('AuthDialog', () => {
it('sets auth context with empty object for USE_VERTEX_AI outside Cloud Shell', async () => {
vi.stubEnv('CLOUD_SHELL', '');
mockedValidateAuthMethod.mockReturnValue(null);
mockedValidateAuthMethod.mockResolvedValue(null);
const { unmount } = await renderWithProviders(<AuthDialog {...props} />);
const { onSelect: handleAuthSelect } =
mockedRadioButtonSelect.mock.calls[0][0];
@@ -270,7 +270,7 @@ describe('AuthDialog', () => {
});
it('sets auth context with empty object for other auth types', async () => {
mockedValidateAuthMethod.mockReturnValue(null);
mockedValidateAuthMethod.mockResolvedValue(null);
const { unmount } = await renderWithProviders(<AuthDialog {...props} />);
const { onSelect: handleAuthSelect } =
mockedRadioButtonSelect.mock.calls[0][0];
@@ -281,7 +281,7 @@ describe('AuthDialog', () => {
});
it('always shows API key dialog even when env var is present', async () => {
mockedValidateAuthMethod.mockReturnValue(null);
mockedValidateAuthMethod.mockResolvedValue(null);
vi.stubEnv('GEMINI_API_KEY', 'test-key-from-env');
// props.settings.merged.security.auth.selectedType is undefined here, simulating initial setup
@@ -297,7 +297,7 @@ describe('AuthDialog', () => {
});
it('always shows API key dialog even when env var is empty string', async () => {
mockedValidateAuthMethod.mockReturnValue(null);
mockedValidateAuthMethod.mockResolvedValue(null);
vi.stubEnv('GEMINI_API_KEY', ''); // Empty string
// props.settings.merged.security.auth.selectedType is undefined here
@@ -313,7 +313,7 @@ describe('AuthDialog', () => {
});
it('shows API key dialog on initial setup if no env var is present', async () => {
mockedValidateAuthMethod.mockReturnValue(null);
mockedValidateAuthMethod.mockResolvedValue(null);
// process.env['GEMINI_API_KEY'] is not set
// props.settings.merged.security.auth.selectedType is undefined here, simulating initial setup
@@ -329,7 +329,7 @@ describe('AuthDialog', () => {
});
it('always shows API key dialog on re-auth even if env var is present', async () => {
mockedValidateAuthMethod.mockReturnValue(null);
mockedValidateAuthMethod.mockResolvedValue(null);
vi.stubEnv('GEMINI_API_KEY', 'test-key-from-env');
// Simulate switching from a different auth method (e.g., Google Login → API key)
props.settings.merged.security.auth.selectedType =
@@ -353,7 +353,7 @@ describe('AuthDialog', () => {
.mockImplementation(() => undefined as never);
const logSpy = vi.spyOn(debugLogger, 'log').mockImplementation(() => {});
vi.mocked(props.config.isBrowserLaunchSuppressed).mockReturnValue(true);
mockedValidateAuthMethod.mockReturnValue(null);
mockedValidateAuthMethod.mockResolvedValue(null);
const { unmount } = await renderWithProviders(<AuthDialog {...props} />);
const { onSelect: handleAuthSelect } =
+5 -2
View File
@@ -154,8 +154,11 @@ export function AuthDialog({
[settings, config, setAuthState, exiting, setAuthContext],
);
const handleAuthSelect = (authMethod: AuthType) => {
const error = validateAuthMethodWithSettings(authMethod, settings);
const handleAuthSelect = async (authMethod: AuthType) => {
const error = await validateAuthMethodWithSettings(
authMethod,
settings,
).catch((e) => (e instanceof Error ? e.message : String(e)));
if (error) {
onAuthError(error);
} else {
+10 -10
View File
@@ -45,7 +45,7 @@ describe('useAuth', () => {
});
describe('validateAuthMethodWithSettings', () => {
it('should return error if auth type is enforced and does not match', () => {
it('should return error if auth type is enforced and does not match', async () => {
const settings = {
merged: {
security: {
@@ -56,14 +56,14 @@ describe('useAuth', () => {
},
} as LoadedSettings;
const error = validateAuthMethodWithSettings(
const error = await validateAuthMethodWithSettings(
AuthType.USE_GEMINI,
settings,
);
expect(error).toContain('Authentication is enforced to be oauth');
});
it('should return null if useExternal is true', () => {
it('should return null if useExternal is true', async () => {
const settings = {
merged: {
security: {
@@ -74,14 +74,14 @@ describe('useAuth', () => {
},
} as LoadedSettings;
const error = validateAuthMethodWithSettings(
const error = await validateAuthMethodWithSettings(
AuthType.LOGIN_WITH_GOOGLE,
settings,
);
expect(error).toBeNull();
});
it('should return null if authType is USE_GEMINI', () => {
it('should return null if authType is USE_GEMINI', async () => {
const settings = {
merged: {
security: {
@@ -90,14 +90,14 @@ describe('useAuth', () => {
},
} as LoadedSettings;
const error = validateAuthMethodWithSettings(
const error = await validateAuthMethodWithSettings(
AuthType.USE_GEMINI,
settings,
);
expect(error).toBeNull();
});
it('should call validateAuthMethod for other auth types', () => {
it('should call validateAuthMethod for other auth types', async () => {
const settings = {
merged: {
security: {
@@ -106,8 +106,8 @@ describe('useAuth', () => {
},
} as LoadedSettings;
mockValidateAuthMethod.mockReturnValue('Validation Error');
const error = validateAuthMethodWithSettings(
mockValidateAuthMethod.mockResolvedValue('Validation Error');
const error = await validateAuthMethodWithSettings(
AuthType.LOGIN_WITH_GOOGLE,
settings,
);
@@ -265,7 +265,7 @@ describe('useAuth', () => {
});
it('should set error if validation fails', async () => {
mockValidateAuthMethod.mockReturnValue('Validation Failed');
mockValidateAuthMethod.mockResolvedValue('Validation Failed');
const { result } = await renderHook(() =>
useAuthCommand(createSettings(AuthType.LOGIN_WITH_GOOGLE), mockConfig),
);
+7 -3
View File
@@ -18,10 +18,10 @@ import { getErrorMessage } from '@google/gemini-cli-core';
import { AuthState } from '../types.js';
import { validateAuthMethod } from '../../config/auth.js';
export function validateAuthMethodWithSettings(
export async function validateAuthMethodWithSettings(
authType: AuthType,
settings: LoadedSettings,
): string | null {
): Promise<string | null> {
const enforcedType = settings.merged.security.auth.enforcedType;
if (enforcedType && enforcedType !== authType) {
return `Authentication is enforced to be ${enforcedType}, but you are currently using ${authType}.`;
@@ -111,7 +111,11 @@ export const useAuthCommand = (
}
}
const error = validateAuthMethodWithSettings(authType, settings);
const error = await validateAuthMethodWithSettings(
authType,
settings,
).catch((e: unknown) => getErrorMessage(e));
if (error) {
onAuthError(error);
return;
@@ -12,7 +12,7 @@ import { waitFor } from '../../test-utils/async.js';
import { createMockSettings } from '../../test-utils/settings.js';
import {
DEFAULT_GEMINI_MODEL,
DEFAULT_GEMINI_MODEL_AUTO,
GEMINI_MODEL_ALIAS_AUTO,
DEFAULT_GEMINI_FLASH_MODEL,
DEFAULT_GEMINI_FLASH_LITE_MODEL,
PREVIEW_GEMINI_MODEL,
@@ -93,7 +93,7 @@ describe('<ModelDialog />', () => {
beforeEach(() => {
vi.resetAllMocks();
mockGetModel.mockReturnValue(DEFAULT_GEMINI_MODEL_AUTO);
mockGetModel.mockReturnValue(GEMINI_MODEL_ALIAS_AUTO);
mockGetHasAccessToPreviewModel.mockReturnValue(false);
mockGetGemini31LaunchedSync.mockReturnValue(false);
mockGetGemini31FlashLiteLaunchedSync.mockReturnValue(false);
@@ -102,8 +102,7 @@ describe('<ModelDialog />', () => {
// Default implementation for getDisplayString
mockGetDisplayString.mockImplementation((val: string) => {
if (val === 'auto-gemini-2.5') return 'Auto (Gemini 2.5)';
if (val === 'auto-gemini-3') return 'Auto (Preview)';
if (val === 'auto') return 'Auto';
return val;
});
});
@@ -234,7 +233,7 @@ describe('<ModelDialog />', () => {
await waitFor(() => {
expect(mockSetModel).toHaveBeenCalledWith(
DEFAULT_GEMINI_MODEL_AUTO,
GEMINI_MODEL_ALIAS_AUTO,
true, // Session only by default
);
expect(mockOnClose).toHaveBeenCalled();
@@ -292,7 +291,7 @@ describe('<ModelDialog />', () => {
await waitFor(() => {
expect(mockSetModel).toHaveBeenCalledWith(
DEFAULT_GEMINI_MODEL_AUTO,
GEMINI_MODEL_ALIAS_AUTO,
false, // Persist enabled
);
expect(mockOnClose).toHaveBeenCalled();
@@ -355,7 +354,7 @@ describe('<ModelDialog />', () => {
mockGetModel.mockReturnValue(DEFAULT_GEMINI_MODEL);
mockGetDisplayString.mockImplementation((val: string) => {
if (val === DEFAULT_GEMINI_MODEL) return 'My Custom Model Display';
if (val === 'auto-gemini-2.5') return 'Auto (Gemini 2.5)';
if (val === 'auto') return 'Auto';
return val;
});
const { lastFrame, unmount } = await renderComponent();
@@ -369,9 +368,9 @@ describe('<ModelDialog />', () => {
mockGetHasAccessToPreviewModel.mockReturnValue(true);
});
it('shows Auto (Preview) in main view when access is granted', async () => {
it('shows Auto in main view when access is granted', async () => {
const { lastFrame, unmount } = await renderComponent();
expect(lastFrame()).toContain('Auto (Preview)');
expect(lastFrame()).toContain('Auto');
unmount();
});
+17 -18
View File
@@ -14,11 +14,10 @@ import {
PREVIEW_GEMINI_3_1_MODEL,
PREVIEW_GEMINI_FLASH_MODEL,
PREVIEW_GEMINI_3_1_FLASH_LITE_MODEL,
PREVIEW_GEMINI_MODEL_AUTO,
DEFAULT_GEMINI_MODEL,
DEFAULT_GEMINI_FLASH_MODEL,
DEFAULT_GEMINI_FLASH_LITE_MODEL,
DEFAULT_GEMINI_MODEL_AUTO,
GEMINI_MODEL_ALIAS_AUTO,
GEMMA_4_31B_IT_MODEL,
GEMMA_4_26B_A4B_IT_MODEL,
ModelSlashCommandEvent,
@@ -27,6 +26,8 @@ import {
AuthType,
PREVIEW_GEMINI_3_1_CUSTOM_TOOLS_MODEL,
isProModel,
getChannelFromVersion,
getAutoModelDescription,
} from '@google/gemini-cli-core';
import { useKeypress } from '../hooks/useKeypress.js';
import { theme } from '../semantic-colors.js';
@@ -63,7 +64,7 @@ export function ModelDialog({ onClose }: ModelDialogProps): React.JSX.Element {
}, [config]);
// Determine the Preferred Model (read once when the dialog opens).
const preferredModel = config?.getModel() || DEFAULT_GEMINI_MODEL_AUTO;
const preferredModel = config?.getModel() || GEMINI_MODEL_ALIAS_AUTO;
const shouldShowPreviewModels = config?.getHasAccessToPreviewModel();
const useGemini31 = config?.getGemini31LaunchedSync?.() ?? false;
@@ -122,6 +123,11 @@ export function ModelDialog({ onClose }: ModelDialogProps): React.JSX.Element {
{ isActive: true },
);
const releaseChannel = useMemo(
() => getChannelFromVersion(config?.clientVersion ?? ''),
[config?.clientVersion],
);
const mainOptions = useMemo(() => {
// --- DYNAMIC PATH ---
if (
@@ -136,6 +142,7 @@ export function ModelDialog({ onClose }: ModelDialogProps): React.JSX.Element {
useCustomTools: useCustomToolModel,
hasAccessToPreview: shouldShowPreviewModels,
hasAccessToProModel,
releaseChannel,
});
const list = allOptions
@@ -161,11 +168,10 @@ export function ModelDialog({ onClose }: ModelDialogProps): React.JSX.Element {
// --- LEGACY PATH ---
const list = [
{
value: DEFAULT_GEMINI_MODEL_AUTO,
title: getDisplayString(DEFAULT_GEMINI_MODEL_AUTO),
description:
'Let Gemini CLI decide the best model for the task: gemini-2.5-pro, gemini-2.5-flash',
key: DEFAULT_GEMINI_MODEL_AUTO,
value: GEMINI_MODEL_ALIAS_AUTO,
title: getDisplayString(GEMINI_MODEL_ALIAS_AUTO),
description: getAutoModelDescription(releaseChannel, useGemini31),
key: GEMINI_MODEL_ALIAS_AUTO,
},
{
value: 'Manual',
@@ -177,16 +183,6 @@ export function ModelDialog({ onClose }: ModelDialogProps): React.JSX.Element {
},
];
if (shouldShowPreviewModels) {
list.unshift({
value: PREVIEW_GEMINI_MODEL_AUTO,
title: getDisplayString(PREVIEW_GEMINI_MODEL_AUTO),
description: useGemini31
? 'Let Gemini CLI decide the best model for the task: gemini-3.1-pro, gemini-3-flash'
: 'Let Gemini CLI decide the best model for the task: gemini-3-pro, gemini-3-flash',
key: PREVIEW_GEMINI_MODEL_AUTO,
});
}
return list;
}, [
config,
@@ -196,6 +192,7 @@ export function ModelDialog({ onClose }: ModelDialogProps): React.JSX.Element {
useGemini31FlashLite,
useCustomToolModel,
hasAccessToProModel,
releaseChannel,
]);
const manualOptions = useMemo(() => {
@@ -212,6 +209,7 @@ export function ModelDialog({ onClose }: ModelDialogProps): React.JSX.Element {
useCustomTools: useCustomToolModel,
hasAccessToPreview: shouldShowPreviewModels,
hasAccessToProModel,
releaseChannel,
});
return allOptions
@@ -304,6 +302,7 @@ export function ModelDialog({ onClose }: ModelDialogProps): React.JSX.Element {
useGemini31FlashLite,
useCustomToolModel,
hasAccessToProModel,
releaseChannel,
config,
]);
+13 -11
View File
@@ -170,13 +170,13 @@ async function searchResourceCandidates(
selector: (candidate: ResourceSuggestionCandidate) => candidate.searchKey,
});
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const results = await fzf.find(normalizedPattern, {
limit: MAX_SUGGESTIONS_TO_SHOW * 3,
});
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return results.map(
(result: { item: ResourceSuggestionCandidate }) => result.item.suggestion,
const results: Array<{ item: ResourceSuggestionCandidate }> = await fzf.find(
normalizedPattern,
{
limit: MAX_SUGGESTIONS_TO_SHOW * 3,
},
);
return results.map((result) => result.item.suggestion);
}
async function searchAgentCandidates(
@@ -194,11 +194,13 @@ async function searchAgentCandidates(
selector: (s: Suggestion) => s.label,
});
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const results = await fzf.find(normalizedPattern, {
limit: MAX_SUGGESTIONS_TO_SHOW,
});
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return results.map((r: { item: Suggestion }) => r.item);
const results: Array<{ item: Suggestion }> = await fzf.find(
normalizedPattern,
{
limit: MAX_SUGGESTIONS_TO_SHOW,
},
);
return results.map((r) => r.item);
}
export function useAtCompletion(props: UseAtCompletionProps): void {
@@ -49,6 +49,7 @@ import {
debugLogger,
coreEvents,
CoreEvent,
SHELL_TOOL_NAME,
MCPDiscoveryState,
GeminiCliOperation,
getPlanModeExitMessage,
@@ -2449,6 +2450,44 @@ describe('useGeminiStream', () => {
);
});
it('should auto-approve shell commands with redirection when switching to AUTO_EDIT mode', async () => {
const shellCall = createMockToolCall(
SHELL_TOOL_NAME,
'call-shell',
'info',
);
shellCall.request.args = { command: 'ls > files.txt' };
const { result } = await renderTestHook([shellCall]);
await act(async () => {
await result.current.handleApprovalModeChange(ApprovalMode.AUTO_EDIT);
});
// Shell command with redirection should be auto-approved
expect(mockMessageBus.publish).toHaveBeenCalledWith(
expect.objectContaining({ correlationId: 'corr-call-shell' }),
);
});
it('should NOT auto-approve shell commands without redirection when switching to AUTO_EDIT mode', async () => {
const shellCall = createMockToolCall(
SHELL_TOOL_NAME,
'call-shell',
'info',
);
shellCall.request.args = { command: 'ls -la' };
const { result } = await renderTestHook([shellCall]);
await act(async () => {
await result.current.handleApprovalModeChange(ApprovalMode.AUTO_EDIT);
});
// Regular shell command should NOT be auto-approved
expect(mockMessageBus.publish).not.toHaveBeenCalled();
});
it('should not auto-approve any tools when switching to REQUIRE_CONFIRMATION mode', async () => {
const awaitingApprovalToolCalls: TrackedToolCall[] = [
createMockToolCall('replace', 'call1', 'edit'),
+16 -3
View File
@@ -26,6 +26,8 @@ import {
debugLogger,
runInDevTraceSpan,
EDIT_TOOL_NAMES,
SHELL_TOOL_NAME,
hasRedirection,
processRestorableToolCalls,
recordToolCallInteractions,
ToolErrorType,
@@ -1820,10 +1822,21 @@ export const useGeminiStream = (
);
// For AUTO_EDIT mode, only approve edit tools (replace, write_file)
// or shell commands with redirection (which act as edits).
if (newApprovalMode === ApprovalMode.AUTO_EDIT) {
awaitingApprovalCalls = awaitingApprovalCalls.filter((call) =>
EDIT_TOOL_NAMES.has(call.request.name),
);
awaitingApprovalCalls = awaitingApprovalCalls.filter((call) => {
if (EDIT_TOOL_NAMES.has(call.request.name)) {
return true;
}
if (call.request.name === SHELL_TOOL_NAME) {
const command = (call.request.args as { command?: string })
.command;
return command && hasRedirection(command);
}
return false;
});
}
// Process pending tool calls sequentially to reduce UI chaos
@@ -265,6 +265,24 @@ describe('TableRenderer', () => {
unmount();
});
it('handles extremely small terminal widths without crashing', async () => {
const headers = ['Col 1', 'Col 2'];
const rows = [['Data 1', 'Data 2']];
// This width is much smaller than the overhead, which could lead to negative column widths
const terminalWidth = 1;
const renderResult = await renderWithProviders(
<TableRenderer
headers={headers}
rows={rows}
terminalWidth={terminalWidth}
/>,
);
const { unmount } = renderResult;
// If it didn't throw RangeError: Invalid count value, the test passes
unmount();
});
it.each([
{
name: 'handles non-ASCII characters (emojis and Asian scripts) correctly',
+8 -8
View File
@@ -174,7 +174,10 @@ export const TableRenderer: React.FC<TableRendererProps> = ({
}
// --- Pre-wrap and Optimize Widths ---
const actualColumnWidths = new Array(numColumns).fill(0);
const actualColumnWidths: number[] = [];
for (let i = 0; i < numColumns; i++) {
actualColumnWidths.push(0);
}
const wrapAndProcessRow = (row: StyledLine[]) => {
const rowResult: ProcessedLine[][] = [];
@@ -208,11 +211,7 @@ export const TableRenderer: React.FC<TableRendererProps> = ({
const wrappedRows = styledRows.map((row) => wrapAndProcessRow(row));
// Use the TIGHTEST widths that fit the wrapped content + padding
const adjustedWidths = actualColumnWidths.map(
(w) =>
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
w + COLUMN_PADDING,
);
const adjustedWidths = actualColumnWidths.map((w) => w + COLUMN_PADDING);
return { wrappedHeaders, wrappedRows, adjustedWidths };
}, [styledHeaders, styledRows, terminalWidth]);
@@ -251,7 +250,9 @@ export const TableRenderer: React.FC<TableRendererProps> = ({
};
const char = chars[type];
const borderParts = adjustedWidths.map((w) => char.horizontal.repeat(w));
const borderParts = adjustedWidths.map((w) =>
char.horizontal.repeat(Math.max(0, w || 0)),
);
const border = char.left + borderParts.join(char.middle) + char.right;
return <Text color={theme.border.default}>{border}</Text>;
@@ -263,7 +264,6 @@ export const TableRenderer: React.FC<TableRendererProps> = ({
isHeader = false,
): React.ReactNode => {
const renderedCells = cells.map((cell, index) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const width = adjustedWidths[index] || 0;
return renderCell(cell, width, isHeader);
});
+9 -7
View File
@@ -111,18 +111,20 @@ function resolveEnvVarsInObjectInternal<T>(
// Check for circular reference
if (visited.has(obj)) {
// Return a shallow copy to break the cycle
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
return [...obj] as unknown as T;
const copy: unknown = [...obj];
const isTArray = (val: unknown): val is T => Array.isArray(val);
if (isTArray(copy)) return copy;
throw new Error('Unreachable');
}
visited.add(obj);
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const result = obj.map((item) =>
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
const mapped: unknown = obj.map((item: unknown) =>
resolveEnvVarsInObjectInternal(item, visited, customEnv),
) as unknown as T;
);
visited.delete(obj);
return result;
const isTArray = (val: unknown): val is T => Array.isArray(val);
if (isTArray(mapped)) return mapped;
throw new Error('Unreachable');
}
if (typeof obj === 'object') {
+1 -2
View File
@@ -83,8 +83,7 @@ export const getLatestGitHubRelease = async (
if (!releaseTag) {
throw new Error(`Response did not include tag_name field`);
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return releaseTag;
return typeof releaseTag === 'string' ? releaseTag : '';
} catch (error) {
debugLogger.debug(
`Failed to determine latest run-gemini-cli release:`,
+1 -3
View File
@@ -29,8 +29,7 @@ export function tryParseJSON(input: string): object | null {
if (!checkInput(input)) return null;
const trimmed = input.trim();
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const parsed = JSON.parse(trimmed);
const parsed: unknown = JSON.parse(trimmed);
if (parsed === null || typeof parsed !== 'object') {
return null;
}
@@ -40,7 +39,6 @@ export function tryParseJSON(input: string): object | null {
if (!Array.isArray(parsed) && Object.keys(parsed).length === 0) return null;
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return parsed;
} catch {
return null;
@@ -59,7 +59,7 @@ describe('validateNonInterActiveAuth', () => {
.mockImplementation((code?: string | number | null | undefined) => {
throw new Error(`process.exit(${code}) called`);
});
vi.spyOn(auth, 'validateAuthMethod').mockReturnValue(null);
vi.spyOn(auth, 'validateAuthMethod').mockResolvedValue(null);
mockSettings = {
system: { path: '', settings: {} },
systemDefaults: { path: '', settings: {} },
@@ -247,7 +247,7 @@ describe('validateNonInterActiveAuth', () => {
it('exits if validateAuthMethod returns error', async () => {
// Mock validateAuthMethod to return error
vi.spyOn(auth, 'validateAuthMethod').mockReturnValue('Auth error!');
vi.spyOn(auth, 'validateAuthMethod').mockResolvedValue('Auth error!');
const nonInteractiveConfig = createLocalMockConfig({
getOutputFormat: vi.fn().mockReturnValue(OutputFormat.TEXT),
getContentGeneratorConfig: vi
@@ -277,7 +277,7 @@ describe('validateNonInterActiveAuth', () => {
// Mock validateAuthMethod to return error to ensure it's not being called
const validateAuthMethodSpy = vi
.spyOn(auth, 'validateAuthMethod')
.mockReturnValue('Auth error!');
.mockResolvedValue('Auth error!');
const nonInteractiveConfig = createLocalMockConfig({});
// Even with an invalid auth type, it should not exit
// because validation is skipped.
@@ -432,7 +432,7 @@ describe('validateNonInterActiveAuth', () => {
});
it(`prints JSON error when validateAuthMethod fails and exits with code ${ExitCodes.FATAL_AUTHENTICATION_ERROR}`, async () => {
vi.spyOn(auth, 'validateAuthMethod').mockReturnValue('Auth error!');
vi.spyOn(auth, 'validateAuthMethod').mockResolvedValue('Auth error!');
process.env['GEMINI_API_KEY'] = 'fake-key';
const nonInteractiveConfig = createLocalMockConfig({
@@ -42,7 +42,7 @@ export async function validateNonInteractiveAuth(
const authType: AuthType = effectiveAuthType;
if (!useExternalAuth) {
const err = validateAuthMethod(String(authType));
const err = await validateAuthMethod(String(authType));
if (err != null) {
throw new Error(err);
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@google/gemini-cli-core",
"version": "0.42.0-nightly.20260428.g59b2dea0e",
"version": "0.44.0-nightly.20260512.g022e8baef",
"description": "Gemini CLI Core",
"license": "Apache-2.0",
"repository": {
+11 -12
View File
@@ -49,6 +49,7 @@ vi.mock('../tools/mcp-client-manager.js', () => ({
}));
import { debugLogger } from '../utils/debugLogger.js';
import { runWithToolCallContext } from '../utils/toolCallContext.js';
import { LocalAgentExecutor, type ActivityCallback } from './local-executor.js';
import { makeFakeConfig } from '../test-utils/config.js';
import { ToolRegistry } from '../tools/tool-registry.js';
@@ -708,21 +709,19 @@ describe('LocalAgentExecutor', () => {
expect(agentRegistry.getTool(MOCK_TOOL_NOT_ALLOWED.name)).toBeUndefined();
});
it('should use parentPromptId from context to create agentId', async () => {
const parentId = 'parent-id';
Object.defineProperty(mockConfig, 'promptId', {
get: () => parentId,
configurable: true,
});
it('should not include parentCallId in agentId even when available', async () => {
const definition = createTestDefinition();
const executor = await LocalAgentExecutor.create(
definition,
mockConfig,
onActivity,
const parentCallId = 'parent-call-123';
const executor = await runWithToolCallContext(
{ callId: parentCallId, schedulerId: 'test-scheduler' },
() => LocalAgentExecutor.create(definition, mockConfig, onActivity),
);
expect(executor['agentId']).toBeDefined();
expect(executor['agentId']).not.toContain(parentCallId);
expect(executor['agentId']).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
);
});
it('should correctly apply templates to initialMessages', async () => {
+2 -1
View File
@@ -6,6 +6,7 @@
import { type AgentLoopContext } from '../config/agent-loop-context.js';
import { reportError } from '../utils/errorReporting.js';
import { randomUUID } from 'node:crypto';
import { ApprovalMode } from '../policy/types.js';
import { GeminiChat, StreamEventType } from '../core/geminiChat.js';
import {
@@ -315,7 +316,7 @@ export class LocalAgentExecutor<TOutput extends z.ZodTypeAny> {
this.parentCallId = parentCallId;
this.cache = new LRUCache<string, string>(10);
this.agentId = Math.random().toString(36).slice(2, 8);
this.agentId = randomUUID();
}
/**
+10 -24
View File
@@ -250,11 +250,11 @@ describe('AgentRegistry', () => {
};
vi.mocked(tomlLoader.loadAgentsFromDirectory)
.mockResolvedValueOnce({ agents: [userAgent], errors: [] }) // User dir
.mockResolvedValueOnce({
agents: [projectAgent, uniqueProjectAgent],
errors: [],
}); // Project dir
}) // Project dir
.mockResolvedValueOnce({ agents: [userAgent], errors: [] }); // User dir
await registry.initialize();
@@ -1011,7 +1011,7 @@ describe('AgentRegistry', () => {
);
});
it('should overwrite an existing agent definition', async () => {
it('should NOT overwrite an existing agent definition', async () => {
await registry.testRegisterAgent(MOCK_AGENT_V1);
expect(registry.getDefinition('MockAgent')?.description).toBe(
'Mock Description V1',
@@ -1019,36 +1019,22 @@ describe('AgentRegistry', () => {
await registry.testRegisterAgent(MOCK_AGENT_V2);
expect(registry.getDefinition('MockAgent')?.description).toBe(
'Mock Description V2 (Updated)',
'Mock Description V1',
);
expect(registry.getAllDefinitions()).toHaveLength(1);
});
it('should log overwrites when in debug mode', async () => {
const debugConfig = makeMockedConfig({ debugMode: true });
const debugRegistry = new TestableAgentRegistry(debugConfig);
const debugLogSpy = vi
.spyOn(debugLogger, 'log')
.mockImplementation(() => {});
await debugRegistry.testRegisterAgent(MOCK_AGENT_V1);
await debugRegistry.testRegisterAgent(MOCK_AGENT_V2);
expect(debugLogSpy).toHaveBeenCalledWith(
`[AgentRegistry] Overriding agent 'MockAgent'`,
);
});
it('should not log overwrites when not in debug mode', async () => {
const debugLogSpy = vi
.spyOn(debugLogger, 'log')
it('should emit warning on duplicate agent definition', async () => {
const feedbackSpy = vi
.spyOn(coreEvents, 'emitFeedback')
.mockImplementation(() => {});
await registry.testRegisterAgent(MOCK_AGENT_V1);
await registry.testRegisterAgent(MOCK_AGENT_V2);
expect(debugLogSpy).not.toHaveBeenCalledWith(
`[AgentRegistry] Overriding agent 'MockAgent'`,
expect(feedbackSpy).toHaveBeenCalledWith(
'warning',
expect.stringContaining("Duplicate agent name 'MockAgent' detected"),
);
});
+36 -25
View File
@@ -169,31 +169,6 @@ export class AgentRegistry {
return;
}
// Load user-level agents: ~/.gemini/agents/
const userAgentsDir = Storage.getUserAgentsDir();
const userAgents = await loadAgentsFromDirectory(userAgentsDir);
for (const error of userAgents.errors) {
debugLogger.warn(
`[AgentRegistry] Error loading user agent: ${error.message}`,
);
const msg = `Agent loading error: ${error.message}`;
errors?.push(msg);
coreEvents.emitFeedback('error', msg);
}
await Promise.allSettled(
userAgents.agents.map(async (agent) => {
try {
this.ensureRemoteAgentHash(agent);
await this.registerAgent(agent, errors);
} catch (e) {
const msg = `Error registering user agent "${agent.name}": ${e instanceof Error ? e.message : String(e)}`;
debugLogger.warn(`[AgentRegistry] ${msg}`, e);
errors?.push(msg);
coreEvents.emitFeedback('error', msg);
}
}),
);
// Load project-level agents: .gemini/agents/ (relative to Project Root)
const folderTrustEnabled = this.config.getFolderTrust();
const isTrustedFolder = this.config.isTrustedFolder();
@@ -256,6 +231,31 @@ export class AgentRegistry {
);
}
// Load user-level agents: ~/.gemini/agents/
const userAgentsDir = Storage.getUserAgentsDir();
const userAgents = await loadAgentsFromDirectory(userAgentsDir);
for (const error of userAgents.errors) {
debugLogger.warn(
`[AgentRegistry] Error loading user agent: ${error.message}`,
);
const msg = `Agent loading error: ${error.message}`;
errors?.push(msg);
coreEvents.emitFeedback('error', msg);
}
await Promise.allSettled(
userAgents.agents.map(async (agent) => {
try {
this.ensureRemoteAgentHash(agent);
await this.registerAgent(agent, errors);
} catch (e) {
const msg = `Error registering user agent "${agent.name}": ${e instanceof Error ? e.message : String(e)}`;
debugLogger.warn(`[AgentRegistry] ${msg}`, e);
errors?.push(msg);
coreEvents.emitFeedback('error', msg);
}
}),
);
// Load agents from extensions
for (const extension of this.config.getExtensions()) {
if (extension.isActive && extension.agents) {
@@ -336,6 +336,17 @@ export class AgentRegistry {
definition: AgentDefinition<TOutput>,
errors?: string[],
): Promise<void> {
const existing = this.agents.get(definition.name);
if (existing && existing !== definition) {
coreEvents.emitFeedback(
'warning',
`Duplicate agent name '${definition.name}' detected. ` +
`The later definition will be ignored. ` +
`Rename one of the agents to avoid this conflict.`,
);
return;
}
if (definition.kind === 'local') {
this.registerLocalAgent(definition);
} else if (definition.kind === 'remote') {
@@ -37,7 +37,11 @@ const createMockConfig = (overrides: Partial<Config> = {}): Config => {
return useGemini31 && authType === AuthType.USE_GEMINI;
},
getContentGeneratorConfig: () => ({ authType: undefined }),
getHasAccessToPreviewModel: () => true,
getMaxAttemptsPerTurn: () => 3,
getExperimentalDynamicModelConfiguration: () => false,
getReleaseChannel: () => 'preview',
modelConfigService: new ModelConfigService(DEFAULT_MODEL_CONFIGS),
...overrides,
} as unknown as Config;
return config;
@@ -187,6 +191,7 @@ describe('policyHelpers', () => {
const testCases = [
{ name: 'Default Auto', model: DEFAULT_GEMINI_MODEL_AUTO },
{ name: 'Gemini 3 Auto', model: 'auto-gemini-3' },
{ name: 'Unified Auto', model: 'auto' },
{ name: 'Flash Lite', model: DEFAULT_GEMINI_FLASH_LITE_MODEL },
{
name: 'Gemini 3 Auto (3.1 Enabled)',
@@ -215,7 +220,18 @@ describe('policyHelpers', () => {
];
testCases.forEach(
({ name, model, useGemini31, hasAccess, authType, wrapsAround }) => {
({
name,
model,
useGemini31,
hasAccess,
authType,
wrapsAround,
...rest
}) => {
const releaseChannel = (rest as Record<string, unknown>)[
'releaseChannel'
] as string | undefined;
it(`achieves parity for: ${name}`, () => {
const createBaseConfig = (dynamic: boolean) =>
createMockConfig({
@@ -225,6 +241,7 @@ describe('policyHelpers', () => {
getGemini31FlashLiteLaunchedSync: () => false,
getHasAccessToPreviewModel: () => hasAccess ?? true,
getContentGeneratorConfig: () => ({ authType }),
getReleaseChannel: () => releaseChannel ?? 'preview',
modelConfigService: new ModelConfigService(DEFAULT_MODEL_CONFIGS),
});
@@ -86,6 +86,7 @@ export function resolvePolicyChain(
useGemini3_1: useGemini31,
useGemini3_1FlashLite: useGemini31FlashLite,
useCustomTools: useCustomToolModel,
releaseChannel: config.getReleaseChannel?.(),
};
if (resolvedModel === DEFAULT_GEMINI_FLASH_LITE_MODEL) {
@@ -242,6 +242,39 @@ describe('OAuthCredentialStorage', () => {
);
});
it('should merge existing refresh token when new payload lacks one', async () => {
const oldCredentials: OAuthCredentials = {
serverName: 'main-account',
token: {
accessToken: 'old-access-token',
refreshToken: 'persistent-refresh-token',
tokenType: 'Bearer',
expiresAt: Date.now() + 3600000,
scope: 'email',
},
updatedAt: Date.now(),
};
vi.spyOn(mockHybridTokenStorage, 'getCredentials').mockResolvedValue(
oldCredentials,
);
const newTokens: Credentials = {
access_token: 'new-access-token',
expiry_date: Date.now() + 3600000,
};
await OAuthCredentialStorage.saveCredentials(newTokens);
expect(mockHybridTokenStorage.setCredentials).toHaveBeenCalledWith(
expect.objectContaining({
token: expect.objectContaining({
accessToken: 'new-access-token',
refreshToken: 'persistent-refresh-token', // correctly merged
}),
}),
);
});
it('should throw an error if access_token is missing', async () => {
const invalidCredentials: Credentials = {
...mockCredentials,
@@ -66,12 +66,16 @@ export class OAuthCredentialStorage {
throw new Error('Attempted to save credentials without an access token.');
}
const existing = await this.storage.getCredentials(MAIN_ACCOUNT_KEY);
const mergedRefreshToken =
credentials.refresh_token || existing?.token.refreshToken;
// Convert Google Credentials to OAuthCredentials format
const mcpCredentials: OAuthCredentials = {
serverName: MAIN_ACCOUNT_KEY,
token: {
accessToken: credentials.access_token,
refreshToken: credentials.refresh_token || undefined,
refreshToken: mergedRefreshToken || undefined,
tokenType: credentials.token_type || 'Bearer',
scope: credentials.scope || undefined,
expiresAt: credentials.expiry_date || undefined,
+7 -2
View File
@@ -679,8 +679,13 @@ async function fetchCachedCredentials(): Promise<
for (const keyFile of pathsToTry) {
try {
const keyFileString = await fs.readFile(keyFile, 'utf-8');
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return JSON.parse(keyFileString);
const parsed: unknown = JSON.parse(keyFileString);
const isOAuthCreds = (val: unknown): val is Credentials | JWTInput =>
typeof val === 'object' && val !== null;
if (isOAuthCreds(parsed)) {
return parsed;
}
throw new Error('Invalid credentials format');
} catch (error) {
// Log specific error for debugging, but continue trying other paths
debugLogger.debug(
+28 -10
View File
@@ -81,14 +81,11 @@ import { tokenLimit } from '../core/tokenLimits.js';
import {
DEFAULT_GEMINI_EMBEDDING_MODEL,
DEFAULT_GEMINI_FLASH_MODEL,
DEFAULT_GEMINI_MODEL,
DEFAULT_GEMINI_MODEL_AUTO,
isAutoModel,
isPreviewModel,
isGemini2Model,
PREVIEW_GEMINI_FLASH_MODEL,
PREVIEW_GEMINI_MODEL,
PREVIEW_GEMINI_MODEL_AUTO,
resolveModel,
} from './models.js';
import { shouldAttemptBrowserLaunch } from '../utils/browser.js';
@@ -445,6 +442,7 @@ export interface ExtensionInstallMetadata {
allowPreRelease?: boolean;
}
import { getChannelFromVersion } from '../utils/channel.js';
import { DEFAULT_MAX_ATTEMPTS } from '../utils/retry.js';
import {
DEFAULT_FILE_FILTERING_OPTIONS,
@@ -762,7 +760,8 @@ export class Config implements McpContext, AgentLoopContext {
private skillManager!: SkillManager;
private _sessionId: string;
private readonly clientName: string | undefined;
private clientVersion: string;
private _clientVersion: string;
private fileSystemService: FileSystemService;
private trackerService?: TrackerService;
readonly topicState = new TopicState();
@@ -982,8 +981,9 @@ export class Config implements McpContext, AgentLoopContext {
constructor(params: ConfigParameters) {
this._sessionId = params.sessionId;
this.clientName = params.clientName;
this.clientVersion = params.clientVersion ?? 'unknown';
this._clientVersion = params.clientVersion ?? 'unknown';
this.approvedPlanPath = undefined;
this.embeddingModel =
params.embeddingModel ?? DEFAULT_GEMINI_EMBEDDING_MODEL;
this.sandbox = params.sandbox
@@ -2009,14 +2009,21 @@ export class Config implements McpContext, AgentLoopContext {
resetTime?: string;
} {
const model = this.getModel();
if (!isAutoModel(model)) {
if (!isAutoModel(model, this)) {
return {};
}
const isPreview =
model === PREVIEW_GEMINI_MODEL_AUTO ||
isPreviewModel(this.getActiveModel(), this);
const proModel = isPreview ? PREVIEW_GEMINI_MODEL : DEFAULT_GEMINI_MODEL;
const primaryModel = resolveModel(
model,
this.getGemini31LaunchedSync(),
this.getGemini31FlashLiteLaunchedSync(),
this.getUseCustomToolModelSync(),
this.getHasAccessToPreviewModel(),
this,
);
const isPreview = isPreviewModel(primaryModel, this);
const proModel = primaryModel;
const flashModel = isPreview
? PREVIEW_GEMINI_FLASH_MODEL
: DEFAULT_GEMINI_FLASH_MODEL;
@@ -2781,6 +2788,10 @@ export class Config implements McpContext, AgentLoopContext {
return this.dynamicModelConfiguration;
}
getReleaseChannel(): string {
return getChannelFromVersion(this._clientVersion);
}
getPendingIncludeDirectories(): string[] {
return this.pendingIncludeDirectories;
}
@@ -3529,6 +3540,13 @@ export class Config implements McpContext, AgentLoopContext {
);
}
/**
* Returns the client version.
*/
get clientVersion(): string {
return this._clientVersion;
}
private async ensureExperimentsLoaded(): Promise<void> {
if (!this.experimentsPromise) {
return;
+36 -34
View File
@@ -362,9 +362,10 @@ export const DEFAULT_MODEL_CONFIGS: ModelConfigServiceConfig = {
// Aliases
auto: {
displayName: 'Auto',
tier: 'auto',
isPreview: true,
isVisible: false,
isVisible: true,
features: { thinking: true, multimodalToolUse: false },
},
pro: {
@@ -386,22 +387,16 @@ export const DEFAULT_MODEL_CONFIGS: ModelConfigServiceConfig = {
features: { thinking: false, multimodalToolUse: false },
},
'auto-gemini-3': {
displayName: 'Auto (Gemini 3)',
tier: 'auto',
family: 'gemini-3',
isPreview: true,
isVisible: true,
dialogDescription:
'Let Gemini CLI decide the best model for the task: gemini-3-pro, gemini-3-flash',
features: { thinking: true, multimodalToolUse: false },
isVisible: false,
},
'auto-gemini-2.5': {
displayName: 'Auto (Gemini 2.5)',
tier: 'auto',
family: 'gemini-2.5',
isPreview: false,
isVisible: true,
dialogDescription:
'Let Gemini CLI decide the best model for the task: gemini-2.5-pro, gemini-2.5-flash',
features: { thinking: false, multimodalToolUse: false },
isVisible: false,
},
},
modelIdResolutions: {
@@ -451,23 +446,10 @@ export const DEFAULT_MODEL_CONFIGS: ModelConfigServiceConfig = {
},
],
},
'auto-gemini-3': {
default: 'gemini-3-pro-preview',
contexts: [
{ condition: { hasAccessToPreview: false }, target: 'gemini-2.5-pro' },
{
condition: { useGemini3_1: true, useCustomTools: true },
target: 'gemini-3.1-pro-preview-customtools',
},
{
condition: { useGemini3_1: true },
target: 'gemini-3.1-pro-preview',
},
],
},
auto: {
default: 'gemini-3-pro-preview',
contexts: [
{ condition: { releaseChannel: 'stable' }, target: 'gemini-2.5-pro' },
{ condition: { hasAccessToPreview: false }, target: 'gemini-2.5-pro' },
{
condition: { useGemini3_1: true, useCustomTools: true },
@@ -493,9 +475,6 @@ export const DEFAULT_MODEL_CONFIGS: ModelConfigServiceConfig = {
},
],
},
'auto-gemini-2.5': {
default: 'gemini-2.5-pro',
},
'gemini-3.1-flash-lite-preview': {
default: 'gemini-3.1-flash-lite-preview',
contexts: [
@@ -523,20 +502,35 @@ export const DEFAULT_MODEL_CONFIGS: ModelConfigServiceConfig = {
},
],
},
'auto-gemini-3': {
default: 'gemini-3-pro-preview',
contexts: [
{ condition: { hasAccessToPreview: false }, target: 'gemini-2.5-pro' },
{
condition: { useGemini3_1: true, useCustomTools: true },
target: 'gemini-3.1-pro-preview-customtools',
},
{
condition: { useGemini3_1: true },
target: 'gemini-3.1-pro-preview',
},
],
},
'auto-gemini-2.5': {
default: 'gemini-2.5-pro',
},
},
classifierIdResolutions: {
flash: {
default: 'gemini-3-flash-preview',
contexts: [
{
condition: { requestedModels: ['auto-gemini-2.5', 'gemini-2.5-pro'] },
condition: { hasAccessToPreview: false },
target: 'gemini-2.5-flash',
},
{
condition: {
requestedModels: ['auto-gemini-3', 'gemini-3-pro-preview'],
},
target: 'gemini-3-flash-preview',
condition: { requestedModels: ['gemini-2.5-pro', 'auto-gemini-2.5'] },
target: 'gemini-2.5-flash',
},
],
},
@@ -544,7 +538,15 @@ export const DEFAULT_MODEL_CONFIGS: ModelConfigServiceConfig = {
default: 'gemini-3-pro-preview',
contexts: [
{
condition: { requestedModels: ['auto-gemini-2.5', 'gemini-2.5-pro'] },
condition: { hasAccessToPreview: false },
target: 'gemini-2.5-pro',
},
{
condition: { releaseChannel: 'stable', requestedModels: ['auto'] },
target: 'gemini-2.5-pro',
},
{
condition: { requestedModels: ['gemini-2.5-pro', 'auto-gemini-2.5'] },
target: 'gemini-2.5-pro',
},
{
+47 -7
View File
@@ -10,6 +10,7 @@ export interface ModelResolutionContext {
useCustomTools?: boolean;
hasAccessToPreview?: boolean;
requestedModel?: string;
releaseChannel?: string;
}
/**
@@ -48,6 +49,7 @@ export interface IModelConfigService {
export interface ModelCapabilityContext {
readonly modelConfigService: IModelConfigService;
getExperimentalDynamicModelConfiguration(): boolean;
getReleaseChannel?(): string;
}
export const PREVIEW_GEMINI_MODEL = 'gemini-3-pro-preview';
@@ -78,7 +80,9 @@ export const VALID_GEMINI_MODELS = new Set([
GEMMA_4_26B_A4B_IT_MODEL,
]);
/** @deprecated Use GEMINI_MODEL_ALIAS_AUTO instead. */
export const PREVIEW_GEMINI_MODEL_AUTO = 'auto-gemini-3';
/** @deprecated Use GEMINI_MODEL_ALIAS_AUTO instead. */
export const DEFAULT_GEMINI_MODEL_AUTO = 'auto-gemini-2.5';
// Model aliases for user convenience.
@@ -92,8 +96,22 @@ export const DEFAULT_GEMINI_EMBEDDING_MODEL = 'gemini-embedding-001';
// Cap the thinking at 8192 to prevent run-away thinking loops.
export const DEFAULT_THINKING_MODE = 8192;
export function getAutoModelDescription(
releaseChannel: string = 'stable',
useGemini3_1: boolean = false,
) {
const isPreview = releaseChannel === 'preview';
const proModel = isPreview
? useGemini3_1
? 'gemini-3.1-pro'
: 'gemini-3-pro'
: 'gemini-2.5-pro';
const flashModel = isPreview ? 'gemini-3-flash' : 'gemini-2.5-flash';
return `Let Gemini CLI decide the best model for the task: ${proModel}, ${flashModel}`;
}
/**
* Resolves the requested model alias (e.g., 'auto-gemini-3', 'pro', 'flash', 'flash-lite')
* Resolves the requested model alias (e.g., 'auto', 'pro', 'flash', 'flash-lite')
* to a concrete model name.
*
* @param requestedModel The model alias or concrete model name requested by the user.
@@ -108,6 +126,7 @@ export function resolveModel(
useCustomToolModel: boolean = false,
hasAccessToPreview: boolean = true,
config?: ModelCapabilityContext,
releaseChannel?: string,
): string {
// Defensive check against non-string inputs at runtime
const normalizedModel = Array.isArray(requestedModel)
@@ -116,12 +135,15 @@ export function resolveModel(
? String(requestedModel ?? '').trim() || ''
: requestedModel.trim() || '';
const currentReleaseChannel = releaseChannel ?? config?.getReleaseChannel?.();
if (config?.getExperimentalDynamicModelConfiguration?.() === true) {
const resolved = config.modelConfigService.resolveModelId(normalizedModel, {
useGemini3_1,
useGemini3_1FlashLite,
useCustomTools: useCustomToolModel,
hasAccessToPreview,
releaseChannel: currentReleaseChannel,
});
if (!hasAccessToPreview && isPreviewModel(resolved, config)) {
@@ -140,10 +162,16 @@ export function resolveModel(
let resolved: string;
switch (normalizedModel) {
case PREVIEW_GEMINI_MODEL:
case PREVIEW_GEMINI_MODEL_AUTO:
case GEMINI_MODEL_ALIAS_AUTO:
case GEMINI_MODEL_ALIAS_PRO: {
if (currentReleaseChannel === 'stable') {
resolved = DEFAULT_GEMINI_MODEL;
break;
}
// fallthrough
}
case PREVIEW_GEMINI_MODEL:
case PREVIEW_GEMINI_MODEL_AUTO: {
if (useGemini3_1) {
resolved = useCustomToolModel
? PREVIEW_GEMINI_3_1_CUSTOM_TOOLS_MODEL
@@ -202,7 +230,7 @@ export function resolveModel(
/**
* Resolves the appropriate model based on the classifier's decision.
*
* @param requestedModel The current requested model (e.g. auto-gemini-2.5).
* @param requestedModel The current requested model (e.g. auto).
* @param modelAlias The alias selected by the classifier ('flash' or 'pro').
* @param useGemini3_1 Whether to use Gemini 3.1 Pro Preview.
* @param useCustomToolModel Whether to use the custom tool model.
@@ -240,17 +268,27 @@ export function resolveClassifierModel(
}
if (
requestedModel === PREVIEW_GEMINI_MODEL_AUTO ||
requestedModel === PREVIEW_GEMINI_MODEL
requestedModel === PREVIEW_GEMINI_MODEL ||
requestedModel === GEMINI_MODEL_ALIAS_AUTO
) {
return PREVIEW_GEMINI_FLASH_MODEL;
return hasAccessToPreview
? PREVIEW_GEMINI_FLASH_MODEL
: DEFAULT_GEMINI_FLASH_MODEL;
}
return resolveModel(GEMINI_MODEL_ALIAS_FLASH);
return resolveModel(
GEMINI_MODEL_ALIAS_FLASH,
false,
false,
false,
hasAccessToPreview,
);
}
return resolveModel(
requestedModel,
useGemini3_1,
useGemini3_1FlashLite,
useCustomToolModel,
hasAccessToPreview,
);
}
@@ -266,6 +304,8 @@ export function getDisplayString(
}
switch (model) {
case GEMINI_MODEL_ALIAS_AUTO:
return 'Auto';
case PREVIEW_GEMINI_MODEL_AUTO:
return 'Auto (Gemini 3)';
case DEFAULT_GEMINI_MODEL_AUTO:
+1 -1
View File
@@ -76,7 +76,7 @@ export class ProjectRegistry {
if (isNodeError(error) && error.code === 'ENOENT') {
return { projects: {} }; // Normal first run
}
if (error instanceof SyntaxError) {
if (error instanceof SyntaxError || error instanceof z.ZodError) {
debugLogger.warn(
'Failed to load registry (JSON corrupted), resetting to empty: ',
error,
+7 -2
View File
@@ -177,10 +177,15 @@ export class BaseLlmClient {
);
// If we are here, the content is valid (not empty and parsable).
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return JSON.parse(
const parsed: unknown = JSON.parse(
this.cleanJsonResponse(getResponseText(result)!.trim(), model),
);
const isRecord = (val: unknown): val is Record<string, unknown> =>
typeof val === 'object' && val !== null && !Array.isArray(val);
if (isRecord(parsed)) {
return parsed;
}
throw new Error('Invalid JSON response format from LLM');
}
async generateEmbedding(texts: string[]): Promise<number[][]> {
+12 -10
View File
@@ -84,11 +84,12 @@ export class FakeContentGenerator implements ContentGenerator {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
role: LlmRole,
): Promise<GenerateContentResponse> {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return Object.setPrototypeOf(
this.getNextResponse('generateContent', request),
GenerateContentResponse.prototype,
);
const response: unknown = this.getNextResponse('generateContent', request);
Object.setPrototypeOf(response, GenerateContentResponse.prototype);
if (response instanceof GenerateContentResponse) {
return response;
}
throw new Error('Failed to create GenerateContentResponse');
}
async generateContentStream(
@@ -118,10 +119,11 @@ export class FakeContentGenerator implements ContentGenerator {
async embedContent(
request: EmbedContentParameters,
): Promise<EmbedContentResponse> {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return Object.setPrototypeOf(
this.getNextResponse('embedContent', request),
EmbedContentResponse.prototype,
);
const response: unknown = this.getNextResponse('embedContent', request);
Object.setPrototypeOf(response, EmbedContentResponse.prototype);
if (response instanceof EmbedContentResponse) {
return response;
}
throw new Error('Failed to create EmbedContentResponse');
}
}
@@ -84,8 +84,13 @@ export class LocalLiteRtLmClient {
);
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return JSON.parse(result.text);
const parsed: unknown = JSON.parse(result.text);
const isRecord = (val: unknown): val is Record<string, unknown> =>
typeof val === 'object' && val !== null && !Array.isArray(val);
if (isRecord(parsed)) {
return parsed;
}
throw new Error('Invalid JSON response format from Local LLM');
} catch (error) {
debugLogger.error(
`[LocalLiteRtLmClient] Failed to generate content:`,
+5 -3
View File
@@ -348,9 +348,11 @@ export class IdeClient {
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const parsedJson = JSON.parse(textPart.text);
if (parsedJson && typeof parsedJson.content === 'string') {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return parsedJson.content;
if (parsedJson) {
const content: unknown = parsedJson.content;
if (typeof content === 'string') {
return content;
}
}
if (parsedJson && parsedJson.content === null) {
return undefined;
+52 -27
View File
@@ -123,8 +123,17 @@ export async function getConnectionConfigFromFile(
`gemini-ide-server-${pid}.json`,
);
const portFileContents = await fs.promises.readFile(portFile, 'utf8');
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return JSON.parse(portFileContents);
const parsed: unknown = JSON.parse(portFileContents);
type ConfigType = ConnectionConfig & {
workspacePath?: string;
ideInfo?: IdeInfo;
};
const isConfig = (val: unknown): val is ConfigType =>
typeof val === 'object' && val !== null;
if (isConfig(parsed)) {
return parsed;
}
throw new Error('Invalid connection config format');
} catch {
// For newer extension versions, the file name matches the pattern
// /^gemini-ide-server-${pid}-\d+\.json$/. If multiple IDE
@@ -166,39 +175,59 @@ export async function getConnectionConfigFromFile(
logger.debug('Failed to read IDE connection config file(s):', e);
return undefined;
}
const parsedContents = fileContents.map((content) => {
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return JSON.parse(content);
} catch (e) {
logger.debug('Failed to parse JSON from config file: ', e);
return undefined;
}
});
const parsedContents = fileContents.map(
(
content,
):
| (ConnectionConfig & { workspacePath?: string; ideInfo?: IdeInfo })
| undefined => {
try {
const parsed: unknown = JSON.parse(content);
type ConfigType = ConnectionConfig & {
workspacePath?: string;
ideInfo?: IdeInfo;
};
const isConfig = (val: unknown): val is ConfigType =>
typeof val === 'object' && val !== null;
if (isConfig(parsed)) {
return parsed;
}
return undefined;
} catch (e) {
logger.debug('Failed to parse JSON from config file: ', e);
return undefined;
}
},
);
const validWorkspaces = parsedContents.filter((content) => {
if (!content) {
return false;
}
const { isValid } = validateWorkspacePath(
content.workspacePath,
process.cwd(),
);
return isValid;
});
const validWorkspaces = parsedContents.filter(
(
content,
): content is ConnectionConfig & {
workspacePath?: string;
ideInfo?: IdeInfo;
} => {
if (!content) {
return false;
}
const { isValid } = validateWorkspacePath(
content.workspacePath,
process.cwd(),
);
return isValid;
},
);
if (validWorkspaces.length === 0) {
return undefined;
}
if (validWorkspaces.length === 1) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const selected = validWorkspaces[0];
const fileIndex = parsedContents.indexOf(selected);
if (fileIndex !== -1) {
logger.debug(`Selected IDE connection file: ${matchingFiles[fileIndex]}`);
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return selected;
}
@@ -208,7 +237,6 @@ export async function getConnectionConfigFromFile(
(content) => String(content.port) === portFromEnv,
);
if (matchingPortIndex !== -1) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const selected = validWorkspaces[matchingPortIndex];
const fileIndex = parsedContents.indexOf(selected);
if (fileIndex !== -1) {
@@ -216,12 +244,10 @@ export async function getConnectionConfigFromFile(
`Selected IDE connection file (matched port from env): ${matchingFiles[fileIndex]}`,
);
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return selected;
}
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const selected = validWorkspaces[0];
const fileIndex = parsedContents.indexOf(selected);
if (fileIndex !== -1) {
@@ -229,7 +255,6 @@ export async function getConnectionConfigFromFile(
`Selected first valid IDE connection file: ${matchingFiles[fileIndex]}`,
);
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return selected;
}
+70
View File
@@ -616,4 +616,74 @@ ${authUrl}
return null;
}
async getValidTokenWithMetadata(
serverName: string,
config: MCPOAuthConfig,
): Promise<{
accessToken: string;
tokenType: string;
expiresAt?: number;
scope?: string;
refreshToken?: string;
} | null> {
const credentials = await this.tokenStorage.getCredentials(serverName);
if (!credentials) return null;
let current = credentials.token;
if (this.tokenStorage.isTokenExpired(current)) {
const clientId = config.clientId ?? credentials.clientId;
if (current.refreshToken && clientId && credentials.tokenUrl) {
try {
const newTokenResponse = await this.refreshAccessToken(
config,
current.refreshToken,
credentials.tokenUrl,
credentials.mcpServerUrl,
);
const refreshed: OAuthToken = {
accessToken: newTokenResponse.access_token,
tokenType: newTokenResponse.token_type,
refreshToken:
newTokenResponse.refresh_token || current.refreshToken,
scope: newTokenResponse.scope || current.scope,
};
if (newTokenResponse.expires_in) {
refreshed.expiresAt =
Date.now() + newTokenResponse.expires_in * 1000;
}
await this.tokenStorage.saveToken(
serverName,
refreshed,
clientId,
credentials.tokenUrl,
credentials.mcpServerUrl,
);
current = refreshed;
} catch (error) {
coreEvents.emitFeedback(
'error',
'Failed to refresh auth token.',
error,
);
await this.tokenStorage.deleteCredentials(serverName);
return null;
}
} else {
return null;
}
}
return {
accessToken: current.accessToken,
tokenType: current.tokenType || 'Bearer',
expiresAt: current.expiresAt,
scope: current.scope,
refreshToken: current.refreshToken,
};
}
}
@@ -192,6 +192,38 @@ describe('MCPOAuthTokenStorage', () => {
expect(savedData[0].serverName).toBe('existing-server');
});
it('should merge existing refresh token when new payload lacks one', async () => {
const existingCredentials: OAuthCredentials = {
...mockCredentials,
serverName: 'existing-server',
token: {
...mockToken,
refreshToken: 'old-refresh-token',
},
};
vi.mocked(fs.readFile).mockResolvedValue(
JSON.stringify([existingCredentials]),
);
vi.mocked(fs.writeFile).mockResolvedValue(undefined);
const newToken: OAuthToken = {
accessToken: 'new_access_token',
expiresAt: Date.now() + ONE_HR_MS,
tokenType: 'Bearer',
}; // missing refreshToken
await tokenStorage.saveToken('existing-server', newToken);
const writeCall = vi.mocked(fs.writeFile).mock.calls[0];
const savedData = JSON.parse(
writeCall[1] as string,
) as OAuthCredentials[];
expect(savedData).toHaveLength(1);
expect(savedData[0].token.accessToken).toBe('new_access_token');
expect(savedData[0].token.refreshToken).toBe('old-refresh-token'); // successfully merged
});
it('should handle write errors gracefully', async () => {
vi.mocked(fs.readFile).mockRejectedValue({ code: 'ENOENT' });
vi.mocked(fs.mkdir).mockResolvedValue(undefined);
@@ -447,6 +479,55 @@ describe('MCPOAuthTokenStorage', () => {
expect(fs.mkdir).toHaveBeenCalled();
});
it('should merge existing refresh token when new payload lacks one in encrypted storage', async () => {
const serverName = 'server1';
const now = Date.now();
vi.spyOn(Date, 'now').mockReturnValue(now);
const existingCredentials: OAuthCredentials = {
serverName,
token: {
...mockToken,
refreshToken: 'old-refresh-token',
},
updatedAt: now,
};
mockHybridTokenStorage.getCredentials.mockResolvedValue(
existingCredentials,
);
const newToken: OAuthToken = {
accessToken: 'new_access_token',
expiresAt: Date.now() + ONE_HR_MS,
tokenType: 'Bearer',
};
await tokenStorage.saveToken(
serverName,
newToken,
'clientId',
'tokenUrl',
'mcpUrl',
);
const expectedCredential: OAuthCredentials = {
serverName,
token: {
...newToken,
refreshToken: 'old-refresh-token',
},
clientId: 'clientId',
tokenUrl: 'tokenUrl',
mcpServerUrl: 'mcpUrl',
updatedAt: now,
};
expect(mockHybridTokenStorage.setCredentials).toHaveBeenCalledWith(
expectedCredential,
);
});
it('should use HybridTokenStorage to get credentials', async () => {
mockHybridTokenStorage.getCredentials.mockResolvedValue(mockCredentials);
const result = await tokenStorage.getCredentials('server1');
+10 -1
View File
@@ -143,9 +143,18 @@ export class MCPOAuthTokenStorage implements TokenStorage {
): Promise<void> {
await this.ensureConfigDir();
const existing = await this.getCredentials(serverName);
const mergedRefreshToken =
token.refreshToken || existing?.token.refreshToken;
const mergedToken = {
...token,
refreshToken: mergedRefreshToken,
};
const credential: OAuthCredentials = {
serverName,
token,
token: mergedToken,
clientId,
tokenUrl,
mcpServerUrl,
@@ -0,0 +1,101 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';
import type {
OAuthClientInformation,
OAuthClientMetadata,
OAuthTokens,
} from '@modelcontextprotocol/sdk/shared/auth.js';
import type { MCPServerConfig } from '../config/config.js';
import { MCPOAuthProvider } from './oauth-provider.js';
import { FIVE_MIN_BUFFER_MS } from './oauth-utils.js';
export class DynamicStoredOAuthProvider implements OAuthClientProvider {
readonly redirectUrl = '';
readonly clientMetadata: OAuthClientMetadata = {
client_name: 'Gemini CLI (Stored OAuth)',
redirect_uris: [],
grant_types: [],
response_types: [],
token_endpoint_auth_method: 'none',
};
private clientInfo?: OAuthClientInformation;
private readonly oauthProvider = new MCPOAuthProvider();
private cachedToken?: OAuthTokens;
private tokenExpiryTime?: number;
constructor(
private readonly serverName: string,
private readonly serverConfig: MCPServerConfig,
) {}
clientInformation(): OAuthClientInformation | undefined {
return this.clientInfo;
}
saveClientInformation(clientInformation: OAuthClientInformation): void {
this.clientInfo = clientInformation;
}
private isCachedTokenValid(): boolean {
return !!(
this.cachedToken?.access_token &&
this.tokenExpiryTime &&
Date.now() < this.tokenExpiryTime - FIVE_MIN_BUFFER_MS
);
}
async tokens(): Promise<OAuthTokens | undefined> {
if (this.isCachedTokenValid()) {
return this.cachedToken;
}
const oauthConfig =
this.serverConfig.oauth?.enabled && this.serverConfig.oauth
? this.serverConfig.oauth
: {};
const tokenMeta = await this.oauthProvider.getValidTokenWithMetadata(
this.serverName,
oauthConfig,
);
if (!tokenMeta?.accessToken) {
this.cachedToken = undefined;
this.tokenExpiryTime = undefined;
return undefined;
}
const freshTokens: OAuthTokens = {
access_token: tokenMeta.accessToken,
token_type: tokenMeta.tokenType || 'Bearer',
expires_in: tokenMeta.expiresAt
? Math.max(0, Math.floor((tokenMeta.expiresAt - Date.now()) / 1000))
: undefined,
scope: tokenMeta.scope,
refresh_token: tokenMeta.refreshToken,
};
if (freshTokens.expires_in !== undefined) {
this.cachedToken = freshTokens;
this.tokenExpiryTime = Date.now() + freshTokens.expires_in * 1000;
return this.cachedToken;
}
this.cachedToken = undefined;
this.tokenExpiryTime = undefined;
return freshTokens;
}
saveTokens(_tokens: OAuthTokens): void {}
redirectToAuthorization(_authorizationUrl: URL): void {}
saveCodeVerifier(_codeVerifier: string): void {}
codeVerifier(): string {
return '';
}
}
@@ -72,7 +72,7 @@ describe('KeychainTokenStorage', () => {
expect(retrieved?.serverName).toBe('test-server');
});
it('should return null if no credentials are found or they are expired', async () => {
it('should return null if no credentials are found or they are expired and unrefreshable', async () => {
expect(await storage.getCredentials('missing')).toBeNull();
const expiredCreds = {
@@ -81,6 +81,20 @@ describe('KeychainTokenStorage', () => {
};
await storage.setCredentials(expiredCreds);
expect(await storage.getCredentials('test-server')).toBeNull();
// Ensure that if it has a refresh token, it is NOT returned as null
const expiredWithRefresh = {
...validCredentials,
token: {
...validCredentials.token,
expiresAt: Date.now() - 1000,
refreshToken: 'some-refresh-token',
},
};
await storage.setCredentials(expiredWithRefresh);
const retrieved = await storage.getCredentials('test-server');
expect(retrieved).not.toBeNull();
expect(retrieved?.token.refreshToken).toBe('some-refresh-token');
});
it('should throw if stored data is corrupted JSON', async () => {
@@ -36,7 +36,7 @@ export class KeychainTokenStorage
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const credentials = JSON.parse(data) as OAuthCredentials;
if (this.isTokenExpired(credentials)) {
if (this.isTokenExpired(credentials) && !credentials.token.refreshToken) {
return null;
}
@@ -104,7 +104,7 @@ export class KeychainTokenStorage
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const data = JSON.parse(cred.password) as OAuthCredentials;
if (!this.isTokenExpired(data)) {
if (!this.isTokenExpired(data) || data.token.refreshToken) {
result.set(cred.account, data);
}
} catch (error) {
@@ -11,6 +11,7 @@ import {
PREVIEW_GEMINI_3_1_MODEL,
PREVIEW_GEMINI_3_1_FLASH_LITE_MODEL,
isProModel,
getAutoModelDescription,
} from '../config/models.js';
// The primary key for the ModelConfig is the model string. However, we also
@@ -101,6 +102,7 @@ export interface ResolutionContext {
hasAccessToPreview?: boolean;
hasAccessToProModel?: boolean;
requestedModel?: string;
releaseChannel?: string;
}
/** The requirements defined in the registry. */
@@ -111,6 +113,7 @@ export interface ResolutionCondition {
hasAccessToPreview?: boolean;
/** Matches if the current model is in this list. */
requestedModels?: string[];
releaseChannel?: string;
}
export interface ModelConfigServiceConfig {
@@ -156,6 +159,7 @@ export class ModelConfigService {
const shouldShowPreviewModels = context.hasAccessToPreview ?? false;
const useGemini31 = context.useGemini3_1 ?? false;
const useGemini31FlashLite = context.useGemini3_1FlashLite ?? false;
const releaseChannel = context.releaseChannel ?? 'stable';
const mainOptions = Object.entries(definitions)
.filter(([_, m]) => {
@@ -164,18 +168,21 @@ export class ModelConfigService {
if (m.tier !== 'auto') return false;
return true;
})
.map(([id, m]) => ({
modelId: id,
name: m.displayName ?? getDisplayString(id),
description:
id === 'auto-gemini-3' && useGemini31
? (m.dialogDescription ?? '').replace(
'gemini-3-pro',
'gemini-3.1-pro',
)
: (m.dialogDescription ?? ''),
tier: m.tier ?? 'auto',
}));
.map(([id, m]) => {
let description = m.dialogDescription ?? '';
if (id === 'auto') {
description = getAutoModelDescription(releaseChannel, useGemini31);
} else if (id === 'auto-gemini-3' && useGemini31) {
description = description.replace('gemini-3-pro', 'gemini-3.1-pro');
}
return {
modelId: id,
name: m.displayName ?? getDisplayString(id),
description,
tier: m.tier ?? 'auto',
};
});
const manualOptions = Object.entries(definitions)
.filter(([id, m]) => {
@@ -258,6 +265,8 @@ export class ModelConfigService {
!!context.requestedModel &&
value.includes(context.requestedModel)
);
case 'releaseChannel':
return value === context.releaseChannel;
default:
return false;
}
+223 -15
View File
@@ -1780,41 +1780,249 @@ describe('mcp-client', () => {
describe('createTransport', () => {
describe('should connect via httpUrl', () => {
it('without headers', async () => {
it('uses MCP SDK authProvider token() path for oauth-enabled servers', async () => {
const mockGetValidTokenWithMetadata = vi.fn().mockResolvedValue({
accessToken: 'fresh-token',
tokenType: 'Bearer',
expiresAt: Date.now() + 10 * 60 * 1000,
});
vi.mocked(MCPOAuthProvider).mockReturnValue({
getValidTokenWithMetadata: mockGetValidTokenWithMetadata,
} as unknown as MCPOAuthProvider);
vi.mocked(MCPOAuthTokenStorage).mockReturnValue({
getCredentials: vi.fn().mockResolvedValue({
clientId: 'cid',
token: {
accessToken: 'fresh-token',
tokenType: 'Bearer',
expiresAt: Date.now() + 10 * 60 * 1000,
},
}),
} as unknown as MCPOAuthTokenStorage);
const transport = await createTransport(
'test-server',
{
httpUrl: 'http://test-server',
url: 'http://test-server',
type: 'http',
oauth: { enabled: true },
},
false,
MOCK_CONTEXT,
);
expect(transport).toBeInstanceOf(StreamableHTTPClientTransport);
expect(transport).toMatchObject({
_url: new URL('http://test-server'),
_requestInit: { headers: {} },
});
const testableTransport = transport as unknown as {
_authProvider?: {
tokens: () => Promise<{ access_token: string } | undefined>;
};
};
expect(testableTransport._authProvider).toBeDefined();
const tokens = await testableTransport._authProvider!.tokens();
expect(tokens?.access_token).toBe('fresh-token');
});
it('uses storage-backed expiry instead of long fallback cache for dynamic authProvider', async () => {
const now = Date.now();
const soonExpiry = now + 10 * 60 * 1000; // 10 minutes
const mockGetValidTokenWithMetadata = vi.fn().mockResolvedValue({
accessToken: 'fresh-token',
tokenType: 'Bearer',
expiresAt: soonExpiry,
});
const mockGetCredentials = vi.fn().mockImplementation(async () => ({
clientId: 'cid',
token: {
accessToken: 'fresh-token',
tokenType: 'Bearer',
expiresAt: soonExpiry,
},
}));
vi.mocked(MCPOAuthProvider).mockReturnValue({
getValidTokenWithMetadata: mockGetValidTokenWithMetadata,
} as unknown as MCPOAuthProvider);
vi.mocked(MCPOAuthTokenStorage).mockReturnValue({
getCredentials: mockGetCredentials,
} as unknown as MCPOAuthTokenStorage);
it('with headers', async () => {
const transport = await createTransport(
'test-server',
{
httpUrl: 'http://test-server',
headers: { Authorization: 'derp' },
url: 'http://test-server',
type: 'http',
},
false,
MOCK_CONTEXT,
);
expect(transport).toBeInstanceOf(StreamableHTTPClientTransport);
expect(transport).toMatchObject({
_url: new URL('http://test-server'),
_requestInit: {
headers: { Authorization: 'derp' },
const testableTransport = transport as unknown as {
_authProvider?: {
tokens: () => Promise<
{ access_token: string; expires_in?: number } | undefined
>;
};
};
expect(testableTransport._authProvider).toBeDefined();
const tokens = await testableTransport._authProvider!.tokens();
expect(tokens?.access_token).toBe('fresh-token');
expect(tokens?.expires_in).toBeDefined();
expect((tokens?.expires_in ?? 0) <= 10 * 60).toBe(true);
expect(mockGetValidTokenWithMetadata).toHaveBeenCalledTimes(1);
expect(mockGetCredentials).toHaveBeenCalledTimes(1);
});
it('uses dynamic authProvider when stored OAuth token exists', async () => {
const mockGetValidTokenWithMetadata = vi.fn().mockResolvedValue({
accessToken: 'stored-fresh-token',
tokenType: 'Bearer',
expiresAt: Date.now() + 10 * 60 * 1000,
});
vi.mocked(MCPOAuthProvider).mockReturnValue({
getValidTokenWithMetadata: mockGetValidTokenWithMetadata,
} as unknown as MCPOAuthProvider);
vi.mocked(MCPOAuthTokenStorage).mockReturnValue({
getCredentials: vi.fn().mockResolvedValue({
clientId: 'cid',
token: {
accessToken: 'stored-fresh-token',
tokenType: 'Bearer',
expiresAt: Date.now() + 10 * 60 * 1000,
},
}),
} as unknown as MCPOAuthTokenStorage);
const transport = await createTransport(
'test-server',
{
url: 'http://test-server',
type: 'http',
},
false,
MOCK_CONTEXT,
);
const testableTransport = transport as unknown as {
_authProvider?: {
tokens: () => Promise<{ access_token: string } | undefined>;
};
};
expect(testableTransport._authProvider).toBeDefined();
const tokens = await testableTransport._authProvider!.tokens();
expect(tokens?.access_token).toBe('stored-fresh-token');
});
it('caches OAuth tokens in dynamic authProvider and avoids repeated lookups', async () => {
const mockGetValidTokenWithMetadata = vi.fn().mockResolvedValue({
accessToken: 'cached-token',
tokenType: 'Bearer',
expiresAt: Date.now() + 10 * 60 * 1000,
});
const mockGetCredentials = vi.fn().mockResolvedValue({
clientId: 'cid',
token: {
accessToken: 'cached-token',
tokenType: 'Bearer',
expiresAt: Date.now() + 10 * 60 * 1000,
},
});
vi.mocked(MCPOAuthProvider).mockReturnValue({
getValidTokenWithMetadata: mockGetValidTokenWithMetadata,
} as unknown as MCPOAuthProvider);
vi.mocked(MCPOAuthTokenStorage).mockReturnValue({
getCredentials: mockGetCredentials,
} as unknown as MCPOAuthTokenStorage);
const transport = await createTransport(
'test-server',
{
url: 'http://test-server',
type: 'http',
},
false,
MOCK_CONTEXT,
);
const testableTransport = transport as unknown as {
_authProvider?: {
tokens: () => Promise<{ access_token: string } | undefined>;
};
};
expect(testableTransport._authProvider).toBeDefined();
const t1 = await testableTransport._authProvider!.tokens();
const t2 = await testableTransport._authProvider!.tokens();
expect(t1?.access_token).toBe('cached-token');
expect(t2?.access_token).toBe('cached-token');
// one call from createTransport fallback detection + one call in first tokens();
// second tokens() should come from in-memory cache
expect(mockGetCredentials).toHaveBeenCalledTimes(1);
expect(mockGetValidTokenWithMetadata).toHaveBeenCalledTimes(1);
});
it('does not long-cache token when metadata has no expiresAt', async () => {
const mockGetValidTokenWithMetadata = vi.fn().mockResolvedValue({
accessToken: 'no-exp-token',
tokenType: 'Bearer',
// expiresAt intentionally omitted
});
const mockGetCredentials = vi.fn().mockResolvedValue({
clientId: 'cid',
token: {
accessToken: 'no-exp-token',
tokenType: 'Bearer',
// expiresAt intentionally omitted
},
});
vi.mocked(MCPOAuthProvider).mockReturnValue({
getValidTokenWithMetadata: mockGetValidTokenWithMetadata,
} as unknown as MCPOAuthProvider);
vi.mocked(MCPOAuthTokenStorage).mockReturnValue({
getCredentials: mockGetCredentials,
} as unknown as MCPOAuthTokenStorage);
const transport = await createTransport(
'test-server',
{
url: 'http://test-server',
type: 'http',
},
false,
MOCK_CONTEXT,
);
const testableTransport = transport as unknown as {
_authProvider?: {
tokens: () => Promise<
{ access_token: string; expires_in?: number } | undefined
>;
};
};
expect(testableTransport._authProvider).toBeDefined();
const t1 = await testableTransport._authProvider!.tokens();
const t2 = await testableTransport._authProvider!.tokens();
expect(t1?.access_token).toBe('no-exp-token');
expect(t2?.access_token).toBe('no-exp-token');
expect(t1?.expires_in).toBeUndefined();
expect(t2?.expires_in).toBeUndefined();
// no-expiry tokens should not be long-cached in memory
expect(mockGetValidTokenWithMetadata).toHaveBeenCalledTimes(2);
});
it('wraps fetch to convert GET 404 to 405 for POST-only servers (e.g. n8n)', async () => {
+35 -31
View File
@@ -5,6 +5,7 @@
*/
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
import type {
jsonSchemaValidator,
@@ -54,9 +55,11 @@ import { basename } from 'node:path';
import { pathToFileURL } from 'node:url';
import { randomUUID } from 'node:crypto';
import type { McpAuthProvider } from '../mcp/auth-provider.js';
import { MCPOAuthProvider } from '../mcp/oauth-provider.js';
import { MCPOAuthTokenStorage } from '../mcp/oauth-token-storage.js';
import { MCPOAuthProvider } from '../mcp/oauth-provider.js';
import { DynamicStoredOAuthProvider } from '../mcp/stored-token-provider.js';
import { OAuthUtils } from '../mcp/oauth-utils.js';
import type { PromptRegistry } from '../prompts/prompt-registry.js';
import {
getErrorMessage,
@@ -82,6 +85,7 @@ import {
type EnvironmentSanitizationConfig,
} from '../services/environmentSanitization.js';
import { expandEnvVars } from '../utils/envExpansion.js';
import {
GEMINI_CLI_IDENTIFICATION_ENV_VAR,
GEMINI_CLI_IDENTIFICATION_ENV_VAR_VALUE,
@@ -1025,6 +1029,16 @@ function createAuthProvider(
}
return undefined;
}
/**
* Creates an OAuth token provider for transports so token lookup/refresh happens
* at request/auth time instead of freezing a single token at transport creation.
*/
function createDynamicOAuthTokenProvider(
mcpServerName: string,
mcpServerConfig: MCPServerConfig,
): McpAuthProvider {
return new DynamicStoredOAuthProvider(mcpServerName, mcpServerConfig);
}
/**
* Create a transport with OAuth token for the given server configuration.
@@ -2205,41 +2219,32 @@ export async function createTransport(
}
}
if (mcpServerConfig.httpUrl || mcpServerConfig.url) {
const authProvider = createAuthProvider(mcpServerConfig);
let authProvider = createAuthProvider(mcpServerConfig);
const headers: Record<string, string> =
(await authProvider?.getRequestHeaders?.()) ?? {};
if (authProvider === undefined) {
// Check if we have OAuth configuration or stored tokens
let accessToken: string | null = null;
if (mcpServerConfig.oauth?.enabled && mcpServerConfig.oauth) {
const tokenStorage = new MCPOAuthTokenStorage();
const mcpAuthProvider = new MCPOAuthProvider(tokenStorage);
accessToken = await mcpAuthProvider.getValidToken(
mcpServerName,
mcpServerConfig.oauth,
);
const tokenStorage = new MCPOAuthTokenStorage();
const credentials = await tokenStorage.getCredentials(mcpServerName);
const shouldUseDynamicOAuthProvider = !!credentials;
if (!accessToken) {
// Emit info message (not error) since this is expected behavior
cliConfig.emitMcpDiagnostic(
'info',
`MCP server '${mcpServerName}' requires authentication using: /mcp auth ${mcpServerName}`,
undefined,
mcpServerName,
);
}
} else {
// Check if we have stored OAuth tokens for this server (from previous authentication)
accessToken = await getStoredOAuthToken(mcpServerName);
if (accessToken) {
debugLogger.log(
`Found stored OAuth token for server '${mcpServerName}'`,
);
}
if (!shouldUseDynamicOAuthProvider && mcpServerConfig.oauth?.enabled) {
cliConfig.emitMcpDiagnostic(
'info',
`MCP server '${mcpServerName}' requires authentication using: /mcp auth ${mcpServerName}`,
undefined,
mcpServerName,
);
}
if (accessToken) {
headers['Authorization'] = `Bearer ${accessToken}`;
if (shouldUseDynamicOAuthProvider) {
debugLogger.log(
`Found stored OAuth token for server '${mcpServerName}'`,
);
authProvider = createDynamicOAuthTokenProvider(
mcpServerName,
mcpServerConfig,
);
}
}
@@ -2339,7 +2344,6 @@ export async function createTransport(
`Invalid configuration: missing httpUrl (for Streamable HTTP), url (for SSE), and command (for stdio).`,
);
}
interface NamedTool {
name?: string;
}
@@ -9,7 +9,7 @@ import picomatch from 'picomatch';
import { loadIgnoreRules, type Ignore } from './ignore.js';
import { ResultCache } from './result-cache.js';
import { crawl } from './crawler.js';
import { AsyncFzf, type FzfResultItem } from 'fzf';
import { AsyncFzf } from 'fzf';
import { unescapePath } from '../paths.js';
import type { FileDiscoveryService } from '../../services/fileDiscoveryService.js';
import { FileWatcher, type FileWatcherEvent } from './fileWatcher.js';
@@ -270,7 +270,7 @@ class RecursiveFileSearch implements FileSearch {
pattern = unescapePath(pattern) || '*';
let filteredCandidates;
let filteredCandidates: string[];
const { files: candidates, isExactMatch } =
await this.resultCache.get(pattern);
@@ -282,17 +282,27 @@ class RecursiveFileSearch implements FileSearch {
if (pattern.includes('*') || !this.fzf) {
filteredCandidates = await filter(candidates, pattern, options.signal);
} else {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
filteredCandidates = await this.fzf
.find(pattern)
.then((results: Array<FzfResultItem<string>>) =>
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
results.map((entry: FzfResultItem<string>) => entry.item),
)
.catch(() => {
try {
const fzfResult: unknown = await this.fzf.find(pattern);
if (Array.isArray(fzfResult)) {
filteredCandidates = fzfResult.map((entry: unknown) => {
if (
typeof entry === 'object' &&
entry !== null &&
'item' in entry
) {
return String((entry as { item: unknown }).item);
}
return String(entry);
});
} else {
shouldCache = false;
return [];
});
filteredCandidates = [];
}
} catch {
shouldCache = false;
filteredCandidates = [];
}
}
if (shouldCache) {
@@ -46,6 +46,15 @@ import { Config, type GeminiCLIExtension } from '../config/config.js';
import { Storage } from '../config/storage.js';
import { SimpleExtensionLoader } from './extensionLoader.js';
import { CoreEvent, coreEvents } from './events.js';
import * as fs from 'node:fs';
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs')>();
return {
...actual,
realpathSync: vi.fn(actual.realpathSync),
};
});
vi.mock('os', async (importOriginal) => {
const actualOs = await importOriginal<typeof os>();
@@ -743,6 +752,40 @@ included directory memory
expect(result.filePaths).toContain(projectContextFile);
});
it('should not crash when fs.realpathSync throws EISDIR on virtual drive roots', async () => {
// Mock realpathSync to throw EISDIR for a specific path, simulating
// the Windows virtual drive issue (#25216).
vi.mocked(fs.realpathSync).mockImplementation((p: fs.PathLike) => {
const pathStr = p.toString();
if (pathStr.includes('virtual-drive')) {
const error = new Error(
"EISDIR: illegal operation on a directory, realpath 'A:\\a'",
);
(error as NodeJS.ErrnoException).code = 'EISDIR';
throw error;
}
// For other paths, we need to return something sensible.
// Since it's a mock, we can just return the path string itself.
return pathStr;
});
const virtualDriveCwd = path.join(testRootDir, 'virtual-drive');
await fsPromises.mkdir(virtualDriveCwd, { recursive: true });
// This should now succeed instead of throwing
const result = await loadServerHierarchicalMemory(
virtualDriveCwd,
[],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
DEFAULT_FOLDER_TRUST,
);
expect(result).toBeDefined();
expect(result.fileCount).toBe(0);
});
it('silently skips a GEMINI.md symlink that points to a directory', async () => {
// Create a real directory elsewhere and symlink GEMINI.md to it.
const realDir = await createEmptyDir(path.join(cwd, '.geminimd-target'));
+3 -4
View File
@@ -24,6 +24,7 @@ import {
isSubpath,
normalizePath,
toAbsolutePath,
resolveToRealPath,
} from './paths.js';
import type { ExtensionLoader } from './extensionLoader.js';
import { debugLogger } from './debugLogger.js';
@@ -702,10 +703,8 @@ export async function loadServerHierarchicalMemory(
boundaryMarkers: readonly string[] = ['.git'],
): Promise<LoadServerHierarchicalMemoryResponse> {
// FIX: Use real, canonical paths for a reliable comparison to handle symlinks.
const realCwd = normalizePath(
await fs.realpath(path.resolve(currentWorkingDirectory)),
);
const realHome = normalizePath(await fs.realpath(path.resolve(homedir())));
const realCwd = normalizePath(resolveToRealPath(currentWorkingDirectory));
const realHome = normalizePath(resolveToRealPath(homedir()));
const isHomeDirectory = realCwd === realHome;
// If it is the home directory, pass an empty string to the core memory
+2 -4
View File
@@ -27,8 +27,7 @@ export function safeJsonStringify(
}
seen.add(value);
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return value;
return value as unknown;
},
space,
);
@@ -61,8 +60,7 @@ export function safeJsonStringifyBooleanValuesOnly(obj: any): string {
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
if ((value as Config) !== null && !configSeen) {
configSeen = true;
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return value;
return value as unknown;
}
if (typeof value === 'boolean') {
return value;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@google/gemini-cli-devtools",
"version": "0.42.0-nightly.20260428.g59b2dea0e",
"version": "0.44.0-nightly.20260512.g022e8baef",
"license": "Apache-2.0",
"type": "module",
"main": "dist/src/index.js",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@google/gemini-cli-sdk",
"version": "0.42.0-nightly.20260428.g59b2dea0e",
"version": "0.44.0-nightly.20260512.g022e8baef",
"description": "Gemini CLI SDK",
"license": "Apache-2.0",
"repository": {
+2 -2
View File
@@ -55,7 +55,7 @@ describe('GeminiCliAgent Skills Integration', () => {
// Expect pirate speak
expect(responseText.toLowerCase()).toContain('arrr');
}, 60000);
}, 120000);
it('loads and activates a skill from a root', async () => {
const goldenFile = getGoldenPath('skill-root-success');
@@ -88,5 +88,5 @@ describe('GeminiCliAgent Skills Integration', () => {
// Expect confirmation or pirate speak
expect(responseText.toLowerCase()).toContain('arrr');
}, 60000);
}, 120000);
});
+3 -3
View File
@@ -57,7 +57,7 @@ describe('GeminiCliAgent Tool Integration', () => {
.join('');
expect(responseText).toContain('8');
});
}, 20000);
it('handles ModelVisibleError correctly', async () => {
const goldenFile = getGoldenPath('tool-error-recovery');
@@ -103,7 +103,7 @@ describe('GeminiCliAgent Tool Integration', () => {
// The model should see the error "Tool failed visibly" and report it back.
expect(responseText).toContain('Tool failed visibly');
});
}, 20000);
it('handles sendErrorsToModel: true correctly', async () => {
const goldenFile = getGoldenPath('tool-catchall-error');
@@ -145,5 +145,5 @@ describe('GeminiCliAgent Tool Integration', () => {
// The model should report the caught standard error.
expect(responseText.toLowerCase()).toContain('error');
});
}, 20000);
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@google/gemini-cli-test-utils",
"version": "0.42.0-nightly.20260428.g59b2dea0e",
"version": "0.44.0-nightly.20260512.g022e8baef",
"private": true,
"main": "src/index.ts",
"license": "Apache-2.0",
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "gemini-cli-vscode-ide-companion",
"displayName": "Gemini CLI Companion",
"description": "Enable Gemini CLI with direct access to your IDE workspace.",
"version": "0.42.0-nightly.20260428.g59b2dea0e",
"version": "0.44.0-nightly.20260512.g022e8baef",
"publisher": "google",
"icon": "assets/icon.png",
"repository": {
File diff suppressed because one or more lines are too long