Compare commits

..

6 Commits

Author SHA1 Message Date
mkorwel a0f32ff7d6 chore: fix circular dependency and complete dynamic model configuration migration 2026-03-13 17:43:18 +00:00
Kevin Wang 1693afe027 pull and merge latest changes 2026-03-13 09:29:33 +00:00
kevinjwang1 d179e3673b Merge branch 'main' into splitModelConfigurability 2026-03-13 02:02:55 -07:00
Kevin Wang e4d6a5cc7c Make ensure default definitions are merged with user defined definitions 2026-03-13 08:53:20 +00:00
Kevin Wang fc4fdc3cbe regenerate docs 2026-03-13 08:38:05 +00:00
Kevin Wang bdbb996a2e Add ModelDefinitions to ModelConfigService 2026-03-13 08:25:03 +00:00
357 changed files with 3293 additions and 17192 deletions
-54
View File
@@ -1,54 +0,0 @@
# --- STAGE 1: Base Runtime ---
FROM docker.io/library/node:20-slim AS base
ARG CLI_VERSION_ARG
ENV CLI_VERSION=$CLI_VERSION_ARG
RUN apt-get update && apt-get install -y --no-install-recommends \
python3 \
curl \
dnsutils \
less \
jq \
ca-certificates \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
# --- STAGE 2: Maintainer ---
FROM base AS maintainer
# Install "Maintainer Bloat" - tools needed for development and offloading
RUN apt-get update && apt-get install -y --no-install-recommends \
make \
g++ \
gh \
git \
unzip \
rsync \
ripgrep \
procps \
psmisc \
lsof \
socat \
tmux \
docker.io \
build-essential \
libsecret-1-dev \
libkrb5-dev \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
# Install global dev tools
RUN npm install -g tsx vitest @google/gemini-cli@nightly prettier eslint typescript cross-env
# Set up npm global package folder
RUN mkdir -p /usr/local/share/npm-global \
&& chown -R node:node /usr/local/share/npm-global
ENV NPM_CONFIG_PREFIX=/usr/local/share/npm-global
ENV PATH=$PATH:/usr/local/share/npm-global/bin
# Switch to non-root user node
USER node
# Default entrypoint
CMD ["/bin/bash"]
-50
View File
@@ -1,50 +0,0 @@
steps:
# Step 1: Install root dependencies
- name: 'us-west1-docker.pkg.dev/gemini-code-dev/gemini-code-containers/gemini-code-builder'
id: 'Install Dependencies'
entrypoint: 'npm'
args: ['install']
# Step 2: Authenticate for Docker
- name: 'us-west1-docker.pkg.dev/gemini-code-dev/gemini-code-containers/gemini-code-builder'
id: 'Authenticate docker'
entrypoint: 'npm'
args: ['run', 'auth']
# Step 3: Build workspace packages
- name: 'us-west1-docker.pkg.dev/gemini-code-dev/gemini-code-containers/gemini-code-builder'
id: 'Build packages'
entrypoint: 'npm'
args: ['run', 'build:packages']
# Step 4: Build Maintainer Image
- name: 'us-west1-docker.pkg.dev/gemini-code-dev/gemini-code-containers/gemini-code-builder'
id: 'Build Maintainer Image'
entrypoint: 'bash'
args:
- '-c'
- |-
IMAGE_BASE="us-docker.pkg.dev/gemini-code-dev/gemini-cli/maintainer"
# Determine the primary tag (branch name or 'latest' for main)
RAW_BRANCH="${_HEAD_BRANCH:-${BRANCH_NAME}}"
if [ "$${RAW_BRANCH}" == "main" ]; then
TAG_PRIMARY="latest"
else
TAG_PRIMARY=$(echo "$${RAW_BRANCH}" | sed 's/[^a-zA-Z0-9]/-/g' | tr '[:upper:]' '[:lower:]')
fi
TAG_SHA="${SHORT_SHA}"
echo "📦 Building Maintainer Image for: $${RAW_BRANCH} -> $${TAG_PRIMARY}"
docker build -f .gcp/Dockerfile.maintainer \
-t "$${IMAGE_BASE}:$${TAG_SHA}" \
-t "$${IMAGE_BASE}:$${TAG_PRIMARY}" .
docker push "$${IMAGE_BASE}:$${TAG_SHA}"
docker push "$${IMAGE_BASE}:$${TAG_PRIMARY}"
options:
defaultLogsBucketBehavior: 'REGIONAL_USER_OWNED_BUCKET'
dynamicSubstitutions: true
-31
View File
@@ -1,31 +0,0 @@
# Fix PR Skill
The `fix-pr` skill enables the Gemini CLI agent to autonomously and iteratively
fix a pull request until it is mergeable and passes all quality checks.
## When to use fix-pr
- **Autonomous fixing**: Move a PR from failing to green without manual
intervention.
- **Iterative loops**: Automatically handle the "fix -> push -> wait for CI"
cycle.
- **Context preservation**: Maintain context across multiple fix attempts.
## Sync vs Offload
This skill is designed to be versatile:
- **Synchronous mode**: Activate the skill in your current terminal for
quick fixes or conflict resolution.
- **Offloaded mode**: Use `npm run offload <PR> fix` to launch an iterative
fix loop on a remote workstation, keeping your local machine free.
## Objective
The goal is to move a PR from its current state (failing tests, merge conflicts,
or unaddressed comments) to a "Ready to Merge" state.
## Technical details
The skill uses the `gh` CLI and a specialized `wait-for-ci` utility to monitor
remote status. It is governed by the project's standard security policies.
-60
View File
@@ -1,60 +0,0 @@
# Fix PR Skill
This skill enables the agent to autonomously and iteratively fix a Pull Request until it is mergeable and passes all quality checks. It is designed to be run in a dedicated, non-blocking environment (like an offloaded remote session).
## Objective
The goal is to move a PR from its current state (failing tests, merge conflicts, or unaddressed comments) to a "Ready to Merge" state.
## Iterative Fix Loop
The agent must follow this loop until the PR is green and mergeable:
### 1. Synchronization & Merge Conflicts
- Fetch latest main: `git fetch origin main`.
- Attempt to merge: `git merge origin/main`.
- **If conflicts occur**:
- Use `git status` to identify conflicted files.
- Resolve the conflict markers (`<<<<<<<`, `=======`, `>>>>>>>`) based on the project's architectural direction.
- `git add` and `git commit` the resolution.
### 2. CI Failure Analysis
- Check current status: `gh pr checks`.
- **If CI is failing**:
- Download failing logs: `gh run view --log-failed`.
- Analyze the specific error (lint, typecheck, or test failure).
- Reproduce the failure locally (e.g., `npm run lint`, `npm test -- <path>`).
- Apply a targeted fix.
### 3. Comment Resolution
- Fetch all comments: Use `scripts/fetch-pr-info.js` or `gh pr view --json reviews,comments`.
- Analyze:
- **Line-level comments**: Fix the specific logic requested.
- **Review rejections**: Address the high-level architectural concerns.
- **General comments**: Respond or implement requested changes.
- For each fixed item, summarize the change in a commit message.
### 4. Verification & Push
- Verify the fix locally: `npm run build` and relevant tests.
- **If local verification fails**: Re-analyze and apply a new fix.
- **If local verification passes**:
- `git add .`
- `git commit -m "fix: address <issue/comment>"`
- `git push origin HEAD`
### 5. Wait for CI
- Run the blocker tool: `npx tsx .gemini/skills/fix-pr/scripts/wait-for-ci.ts`.
- **If CI passes**: Move to final check.
- **If CI fails**: Repeat the loop from step 2.
## Final Check
The PR is considered "Fix Complete" when:
1. `gh pr checks` returns success for all required jobs.
2. There are no outstanding merge conflicts with `main`.
3. All critical review comments have been addressed via code changes.
## Best Practices
- **Reason about failures**: Don't just guess. Read the stack traces and log files.
- **Incremental commits**: Make small, focused commits for different fixes.
- **Verify before pushing**: Always run the build/test locally before pushing to CI to save time.
- **Be Autonomous**: In an offloaded session, you have full permission to iterate until successful.
@@ -1,41 +0,0 @@
/**
* CI Waiter Utility for Fix PR Skill
* Blocks until GitHub checks for the current branch are complete.
*/
import { spawnSync } from 'child_process';
async function wait(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function main() {
console.log('🔍 Waiting for GitHub Checks to complete...');
let attempts = 0;
const maxAttempts = 30; // 15 minutes total
while (attempts < maxAttempts) {
const checkStatus = spawnSync('gh', ['pr', 'checks'], { shell: true });
const output = checkStatus.stdout.toString();
if (output.includes('fail')) {
console.log('❌ CI Failed.');
process.exit(1);
} else if (output.includes('pending')) {
console.log(`⏳ CI still pending... (check ${attempts + 1}/${maxAttempts})`);
await wait(30000); // 30 seconds
} else if (output.trim() === '') {
console.log('⚠️ No checks found yet, waiting...');
await wait(10000);
} else {
console.log('✅ CI Passed!');
process.exit(0);
}
attempts++;
}
console.error('⏰ Timeout waiting for CI.');
process.exit(1);
}
main().catch(console.error);
-34
View File
@@ -1,34 +0,0 @@
# Review PR Skill
The `review-pr` skill enables the Gemini CLI agent to conduct high-fidelity,
behavioral code reviews that go beyond simple static analysis.
## When to use review-pr
- **Deep verification**: Verify that a feature actually works by executing
it in a live environment.
- **Infrastructure awareness**: Leverage build and CI results to focus on
empirical proof of functionality.
- **Interactive collaboration**: Discuss findings and explore edge cases
with the agent in real-time.
## Sync vs Offload
This skill supports two primary modes:
- **Synchronous mode**: Activate the skill locally for quick, high-level
analysis of a peer's PR.
- **Offloaded mode**: Use `npm run offload <PR> review` to conduct a
full-scale behavioral review on a remote workstation with parallelized
infrastructure validation.
## Objective
Conduct a thorough review that involves physically proving the feature works
through terminal scripts and command execution.
## Technical details
The skill assumes the infrastructure (build and CI) is already being validated
and focuses on empirical proofs. It uses the `extract-failures.ts` utility to
automatically identify regressions in CI logs.
-67
View File
@@ -1,67 +0,0 @@
# Review PR Skill
This skill enables the agent to conduct a high-fidelity, behavioral code review
for a Pull Request. It is designed to be run in a dedicated, workspace remote
session where parallel infrastructure validation (build, CI check) is already
underway.
## Objective
Conduct a thorough review that goes beyond static analysis. The agent must
**physically prove** the feature works and that all regressions are caught by
exercising the code in a live terminal.
## Workflow: Verify then Synthesize
The agent must follow these steps to conduct the review:
### 1. Context Acquisition
- Read the PR description: `gh pr view <PR_NUMBER>`.
- Read the intent from the description and map it against the diff.
- Run `/review-frontend <PR_NUMBER>` to get an initial static analysis report.
### 2. Infrastructure Validation
- Trust the parallel worker results in `.gemini/logs/workspace-<PR_NUMBER>/`.
- Read `build.log` to ensure the environment is stable for testing.
- Read `ci-status.exit`.
- **If CI is failing**: Use the extractor to identify failing tests:
`npx tsx .gemini/skills/review-pr/scripts/extract-failures.ts <PR_NUMBER>`
- Reproduce the failing tests locally and analyze the output.
### 3. Behavioral Verification (The "Proof")
- Do NOT just trust that tests pass.
- Physically exercise the new code in the terminal.
- Examples of "Proof":
- If it's a new CLI command, run it with various flags.
- If it's a new service, write a small `.ts` script to call the functions.
- If it's a UI component, verify the Ink layout renders correctly.
- Log these proof steps and results in your conversation.
### 4. Synthesis
- Combine all data points:
- **Static Analysis** (Code quality, style).
- **Infrastructure** (Build status, CI status).
- **Behavioral Proof** (Empirical verification).
- Check for merge conflicts with `main`.
## Final Assessment
Provide a final recommendation with four sections:
1. **Summary**: High-level verdict (Approve / Needs Work / Reject).
2. **Verified Behavior**: Describe the scripts/commands you ran to prove the
feature works.
3. **Findings**: List Critical issues, Improvements, and Nitpicks.
4. **Actionable URL**: Explicitly print the PR URL: `gh pr view --web`.
### Approval Protocol
After presenting the synthesis, the agent MUST determine the all-up recommendation and ask the user for confirmation:
* "Based on the verification, I recommend **[APPROVE / COMMENT / REJECT]**. Would you like me to post this review to GitHub?"
* If the user agrees, execute the appropriate `gh pr review` command (e.g., `gh pr review <PR_NUMBER> --approve --body "<Summary>"`).
## Best Practices
- **Be Skeptical**: Just because CI is green doesn't mean the feature is complete. Look for missing edge cases.
- **Collaborate**: If you find a bug during verification, tell the user immediately in the main window.
- **Don't Fix**: Your role is to **review**, not to fix. If the PR is failing, summarize the causes and request changes.
@@ -1,59 +0,0 @@
/**
* CI Failure Extraction Utility
*
* Analyzes remote CI logs to identify specific failing test files.
* Used by the review-pr and fix-pr skills to minimize local repro noise.
*/
import { spawnSync } from 'child_process';
async function main() {
const prNumber = process.argv[2];
if (!prNumber) {
console.error('Usage: npx tsx extract-failures.ts <PR_NUMBER>');
process.exit(1);
}
console.log(`🔍 Investigating CI failures for PR #${prNumber}...`);
// 1. Get branch name
const branchView = spawnSync('gh', ['pr', 'view', prNumber, '--json', 'headRefName', '-q', '.headRefName'], { shell: true });
const branchName = branchView.stdout.toString().trim();
// 2. Get latest CI run ID
const runList = spawnSync('gh', ['run', 'list', '--branch', branchName, '--workflow', 'ci.yml', '--json', 'databaseId', '-q', '.[0].databaseId'], { shell: true });
const runId = runList.stdout.toString().trim();
if (!runId) {
console.log('⚠️ No recent CI runs found for this branch.');
process.exit(0);
}
// 3. Extract failing files from logs
// Pattern matches common test locations in the monorepo
const logView = spawnSync('gh', ['run', 'view', runId, '--log-failed'], { shell: true });
const logOutput = logView.stdout.toString();
const testPattern = /(packages\/[a-zA-Z0-9_-]+|integration-tests|evals)\/[a-zA-Z0-9_\/-]+\.test\.ts(x)?/g;
const matches = logOutput.match(testPattern);
if (!matches || matches.length === 0) {
console.log('✅ No specific failing test files detected in logs.');
process.exit(0);
}
const uniqueFiles = Array.from(new Set(matches)).sort();
console.log('\n❌ Found failing test files:');
uniqueFiles.forEach(f => console.log(` - ${f}`));
console.log('\n👉 Recommendation: Run these tests locally using:');
uniqueFiles.forEach(file => {
let wsDir = file.split('/')[0];
if (wsDir === 'packages') {
wsDir = file.split('/').slice(0, 2).join('/');
}
const relFile = file.replace(`${wsDir}/`, '');
console.log(` npm run test:ci -w ${wsDir} -- ${relFile}`);
});
}
main().catch(console.error);
@@ -40,8 +40,6 @@ jobs:
github-token: '${{ steps.generate_token.outputs.token || secrets.GITHUB_TOKEN }}'
script: |
const dryRun = process.env.DRY_RUN === 'true';
const fourteenDaysAgo = new Date();
fourteenDaysAgo.setDate(fourteenDaysAgo.getDate() - 14);
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
@@ -58,38 +56,48 @@ jobs:
for (const m of members) maintainerLogins.add(m.login.toLowerCase());
core.info(`Successfully fetched ${members.length} team members from ${team_slug}`);
} catch (e) {
// Silently skip if permissions are insufficient; we will rely on author_association
core.debug(`Skipped team fetch for ${team_slug}: ${e.message}`);
core.warning(`Failed to fetch team members from ${team_slug}: ${e.message}`);
}
}
const isMaintainer = async (login, assoc) => {
// Reliably identify maintainers using authorAssociation (provided by GitHub)
// and organization membership (if available).
const isTeamMember = maintainerLogins.has(login.toLowerCase());
const isRepoMaintainer = ['OWNER', 'MEMBER', 'COLLABORATOR'].includes(assoc);
const isGooglerCache = new Map();
const isGoogler = async (login) => {
if (isGooglerCache.has(login)) return isGooglerCache.get(login);
if (isTeamMember || isRepoMaintainer) return true;
// Fallback: Check if user belongs to the 'google' or 'googlers' orgs (requires permission)
try {
// Check membership in 'googlers' or 'google' orgs
const orgs = ['googlers', 'google'];
for (const org of orgs) {
try {
await github.rest.orgs.checkMembershipForUser({ org: org, username: login });
await github.rest.orgs.checkMembershipForUser({
org: org,
username: login
});
core.info(`User ${login} is a member of ${org} organization.`);
isGooglerCache.set(login, true);
return true;
} catch (e) {
// 404 just means they aren't a member, which is fine
if (e.status !== 404) throw e;
}
}
} catch (e) {
// Gracefully ignore failures here
core.warning(`Failed to check org membership for ${login}: ${e.message}`);
}
isGooglerCache.set(login, false);
return false;
};
// 2. Fetch all open PRs
const isMaintainer = async (login, assoc) => {
const isTeamMember = maintainerLogins.has(login.toLowerCase());
const isRepoMaintainer = ['OWNER', 'MEMBER', 'COLLABORATOR'].includes(assoc);
if (isTeamMember || isRepoMaintainer) return true;
return await isGoogler(login);
};
// 2. Determine which PRs to check
let prs = [];
if (context.eventName === 'pull_request') {
const { data: pr } = await github.rest.pulls.get({
@@ -110,77 +118,64 @@ jobs:
for (const pr of prs) {
const maintainerPr = await isMaintainer(pr.user.login, pr.author_association);
const isBot = pr.user.type === 'Bot' || pr.user.login.endsWith('[bot]');
if (maintainerPr || isBot) continue;
// Helper: Fetch labels and linked issues via GraphQL
const prDetailsQuery = `query($owner:String!, $repo:String!, $number:Int!) {
// Detection Logic for Linked Issues
// Check 1: Official GitHub "Closing Issue" link (GraphQL)
const linkedIssueQuery = `query($owner:String!, $repo:String!, $number:Int!) {
repository(owner:$owner, name:$repo) {
pullRequest(number:$number) {
closingIssuesReferences(first: 10) {
nodes {
number
labels(first: 20) {
nodes { name }
}
}
}
closingIssuesReferences(first: 1) { totalCount }
}
}
}`;
let linkedIssues = [];
let hasClosingLink = false;
try {
const res = await github.graphql(prDetailsQuery, {
const res = await github.graphql(linkedIssueQuery, {
owner: context.repo.owner, repo: context.repo.repo, number: pr.number
});
linkedIssues = res.repository.pullRequest.closingIssuesReferences.nodes;
} catch (e) {
core.warning(`GraphQL fetch failed for PR #${pr.number}: ${e.message}`);
}
hasClosingLink = res.repository.pullRequest.closingIssuesReferences.totalCount > 0;
} catch (e) {}
// Check for mentions in body as fallback (regex)
// Check 2: Regex for mentions (e.g., "Related to #123", "Part of #123", "#123")
// We check for # followed by numbers or direct URLs to issues.
const body = pr.body || '';
const mentionRegex = /(?:#|https:\/\/github\.com\/[^\/]+\/[^\/]+\/issues\/)(\d+)/i;
const matches = body.match(mentionRegex);
if (matches && linkedIssues.length === 0) {
const issueNumber = parseInt(matches[1]);
try {
const { data: issue } = await github.rest.issues.get({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber
});
linkedIssues = [{ number: issueNumber, labels: { nodes: issue.labels.map(l => ({ name: l.name })) } }];
} catch (e) {}
const hasMentionLink = mentionRegex.test(body);
const hasLinkedIssue = hasClosingLink || hasMentionLink;
// Logic for Closed PRs (Auto-Reopen)
if (pr.state === 'closed' && context.eventName === 'pull_request' && context.payload.action === 'edited') {
if (hasLinkedIssue) {
core.info(`PR #${pr.number} now has a linked issue. Reopening.`);
if (!dryRun) {
await github.rest.pulls.update({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: pr.number,
state: 'open'
});
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
body: "Thank you for linking an issue! This pull request has been automatically reopened."
});
}
}
continue;
}
// 3. Enforcement Logic
const prLabels = pr.labels.map(l => l.name.toLowerCase());
const hasHelpWanted = prLabels.includes('help wanted') ||
linkedIssues.some(issue => issue.labels.nodes.some(l => l.name.toLowerCase() === 'help wanted'));
const hasMaintainerOnly = prLabels.includes('🔒 maintainer only') ||
linkedIssues.some(issue => issue.labels.nodes.some(l => l.name.toLowerCase() === '🔒 maintainer only'));
const hasLinkedIssue = linkedIssues.length > 0;
// Closure Policy: No help-wanted label = Close after 14 days
if (pr.state === 'open' && !hasHelpWanted && !hasMaintainerOnly) {
const prCreatedAt = new Date(pr.created_at);
// We give a 14-day grace period for non-help-wanted PRs to be manually reviewed/labeled by an EM
if (prCreatedAt > fourteenDaysAgo) {
core.info(`PR #${pr.number} is new and lacks 'help wanted'. Giving 14-day grace period for EM review.`);
continue;
}
core.info(`PR #${pr.number} is older than 14 days and lacks 'help wanted' association. Closing.`);
// Logic for Open PRs (Immediate Closure)
if (pr.state === 'open' && !maintainerPr && !hasLinkedIssue && !isBot) {
core.info(`PR #${pr.number} is missing a linked issue. Closing.`);
if (!dryRun) {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
body: "Hi there! Thank you for your interest in contributing to Gemini CLI. \n\nTo ensure we maintain high code quality and focus on our prioritized roadmap, we have updated our contribution policy (see [Discussion #17383](https://github.com/google-gemini/gemini-cli/discussions/17383)). \n\n**We only *guarantee* review and consideration of pull requests for issues that are explicitly labeled as 'help wanted'.** All other community pull requests are subject to closure after 14 days if they do not align with our current focus areas. For this reason, we strongly recommend that contributors only submit pull requests against issues explicitly labeled as **'help-wanted'**. \n\nThis pull request is being closed as it has been open for 14 days without a 'help wanted' designation. We encourage you to find and contribute to existing 'help wanted' issues in our backlog! Thank you for your understanding and for being part of our community!"
body: "Hi there! Thank you for your contribution to Gemini CLI. \n\nTo improve our contribution process and better track changes, we now require all pull requests to be associated with an existing issue, as announced in our [recent discussion](https://github.com/google-gemini/gemini-cli/discussions/16706) and as detailed in our [CONTRIBUTING.md](https://github.com/google-gemini/gemini-cli/blob/main/CONTRIBUTING.md#1-link-to-an-existing-issue).\n\nThis pull request is being closed because it is not currently linked to an issue. **Once you have updated the description of this PR to link an issue (e.g., by adding `Fixes #123` or `Related to #123`), it will be automatically reopened.**\n\n**How to link an issue:**\nAdd a keyword followed by the issue number (e.g., `Fixes #123`) in the description of your pull request. For more details on supported keywords and how linking works, please refer to the [GitHub Documentation on linking pull requests to issues](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue).\n\nThank you for your understanding and for being a part of our community!"
});
await github.rest.pulls.update({
owner: context.repo.owner,
@@ -192,22 +187,27 @@ jobs:
continue;
}
// Also check for linked issue even if it has help wanted (redundant but safe)
if (pr.state === 'open' && !hasLinkedIssue) {
// Already covered by hasHelpWanted check above, but good for future-proofing
continue;
}
// 4. Staleness Check (Scheduled only)
// Staleness check (Scheduled runs only)
if (pr.state === 'open' && context.eventName !== 'pull_request') {
const labels = pr.labels.map(l => l.name.toLowerCase());
if (labels.includes('help wanted') || labels.includes('🔒 maintainer only')) continue;
// Skip PRs that were created less than 30 days ago - they cannot be stale yet
const prCreatedAt = new Date(pr.created_at);
if (prCreatedAt > thirtyDaysAgo) continue;
if (prCreatedAt > thirtyDaysAgo) {
const daysOld = Math.floor((Date.now() - prCreatedAt.getTime()) / (1000 * 60 * 60 * 24));
core.info(`PR #${pr.number} was created ${daysOld} days ago. Skipping staleness check.`);
continue;
}
// Initialize lastActivity to PR creation date (not epoch) as a safety baseline.
// This ensures we never incorrectly mark a PR as stale due to failed activity lookups.
let lastActivity = new Date(pr.created_at);
try {
const reviews = await github.paginate(github.rest.pulls.listReviews, {
owner: context.repo.owner, repo: context.repo.repo, pull_number: pr.number
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: pr.number
});
for (const r of reviews) {
if (await isMaintainer(r.user.login, r.author_association)) {
@@ -216,7 +216,9 @@ jobs:
}
}
const comments = await github.paginate(github.rest.issues.listComments, {
owner: context.repo.owner, repo: context.repo.repo, issue_number: pr.number
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number
});
for (const c of comments) {
if (await isMaintainer(c.user.login, c.author_association)) {
@@ -224,23 +226,25 @@ jobs:
if (d > lastActivity) lastActivity = d;
}
}
} catch (e) {}
} catch (e) {
core.warning(`Failed to fetch reviews/comments for PR #${pr.number}: ${e.message}`);
}
// For maintainer PRs, the PR creation itself counts as maintainer activity.
// (Now redundant since we initialize to pr.created_at, but kept for clarity)
if (maintainerPr) {
const d = new Date(pr.created_at);
if (d > lastActivity) lastActivity = d;
}
if (lastActivity < thirtyDaysAgo) {
const labels = pr.labels.map(l => l.name.toLowerCase());
const isProtected = labels.includes('help wanted') || labels.includes('🔒 maintainer only');
if (isProtected) {
core.info(`PR #${pr.number} is stale but has a protected label. Skipping closure.`);
continue;
}
core.info(`PR #${pr.number} is stale (no maintainer activity for 30+ days). Closing.`);
core.info(`PR #${pr.number} is stale.`);
if (!dryRun) {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
body: "Hi there! Thank you for your contribution. To keep our backlog manageable, we are closing pull requests that haven't seen maintainer activity for 30 days. If you're still working on this, please let us know!"
body: "Hi there! Thank you for your contribution to Gemini CLI. We really appreciate the time and effort you've put into this pull request.\n\nTo keep our backlog manageable and ensure we're focusing on current priorities, we are closing pull requests that haven't seen maintainer activity for 30 days. Currently, the team is prioritizing work associated with **🔒 maintainer only** or **help wanted** issues.\n\nIf you believe this change is still critical, please feel free to comment with updated details. Otherwise, we encourage contributors to focus on open issues labeled as **help wanted**. Thank you for your understanding!"
});
await github.rest.pulls.update({
owner: context.repo.owner,
@@ -1,41 +0,0 @@
name: Offload Golden Image Update
on:
push:
branches:
- main
paths:
- '.gemini/skills/offload/scripts/provision-worker.sh'
- '.gemini/skills/offload/scripts/fleet.ts'
workflow_dispatch:
jobs:
update-image:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
- name: Install Dependencies
run: npm install
- name: Authenticate to Google Cloud
uses: google-github-actions/auth@v2
with:
workload_identity_provider: ${{ secrets.GCP_WIP }}
service_account: ${{ secrets.GCP_SA }}
- name: Setup GCloud SDK
uses: google-github-actions/setup-gcloud@v2
- name: Build New Golden Image
run: npm run offload:fleet create-image
+10 -8
View File
@@ -43,14 +43,16 @@ The process for contributing code is as follows:
1. **Find an issue** that you want to work on. If an issue is tagged as
`🔒Maintainers only`, this means it is reserved for project maintainers. We
will not accept pull requests related to these issues.
2. **Maintainer Setup**: If you are a team maintainer, please follow the
[Maintainer Onboarding Guide](./MAINTAINER_ONBOARDING.md) to set up your
high-performance remote offload environment.
3. **Fork the repository** and create a new branch.
4. **Make your changes** in the `packages/` directory.
5. **Ensure all checks pass** by running `npm run preflight`.
6. **Open a pull request** with your changes.
will not accept pull requests related to these issues. In the near future,
we will explicitly mark issues looking for contributions using the
`help-wanted` label. If you believe an issue is a good candidate for
community contribution, please leave a comment on the issue. A maintainer
will review it and apply the `help-wanted` label if appropriate. Only
maintainers should attempt to add the `help-wanted` label to an issue.
2. **Fork the repository** and create a new branch.
3. **Make your changes** in the `packages/` directory.
4. **Ensure all checks pass** by running `npm run preflight`.
5. **Open a pull request** with your changes.
### Code reviews
+8 -3
View File
@@ -22,10 +22,9 @@ powerful tool for developers.
rendering.
- `packages/core`: Backend logic, Gemini API orchestration, prompt
construction, and tool execution.
- `packages/core/src/tools/`: Built-in tools for file system, shell, and web
operations.
- `packages/a2a-server`: Experimental Agent-to-Agent server.
- `packages/sdk`: Programmatic SDK for embedding Gemini CLI capabilities.
- `packages/devtools`: Integrated developer tools (Network/Console inspector).
- `packages/test-utils`: Shared test utilities and test rig.
- `packages/vscode-ide-companion`: VS Code extension pairing with the CLI.
## Building and Running
@@ -59,6 +58,10 @@ powerful tool for developers.
## Development Conventions
- **Legacy Snippets:** `packages/core/src/prompts/snippets.legacy.ts` is a
snapshot of an older system prompt. Avoid changing the prompting verbiage to
preserve its historical behavior; however, structural changes to ensure
compilation or simplify the code are permitted.
- **Contributions:** Follow the process outlined in `CONTRIBUTING.md`. Requires
signing the Google CLA.
- **Pull Requests:** Keep PRs small, focused, and linked to an existing issue.
@@ -66,6 +69,8 @@ powerful tool for developers.
`gh` CLI.
- **Commit Messages:** Follow the
[Conventional Commits](https://www.conventionalcommits.org/) standard.
- **Coding Style:** Adhere to existing patterns in `packages/cli` (React/Ink)
and `packages/core` (Backend logic).
- **Imports:** Use specific imports and avoid restricted relative imports
between packages (enforced by ESLint).
- **License Headers:** For all new source code files (`.ts`, `.tsx`, `.js`),
-75
View File
@@ -1,75 +0,0 @@
# Gemini Workspaces: Maintainer Onboarding
Gemini Workspaces allow you to delegate heavy tasks (PR reviews, agentic fixes,
full builds) to a high-performance GCP worker. It uses a **Unified Data Disk**
architecture to ensure your work persists even if the VM is deleted or
recreated.
## 1. Local Prerequisites
Before starting, ensure you have:
- **GCloud CLI**: Authenticated (`gcloud auth login`).
- **GitHub CLI**: Authenticated (`gh auth login`).
- **Project Access**: A GCP Project ID where you have `Editor` or
`Compute Admin` roles.
## 2. Initialization
Run the setup script using the unified workspaces entry point:
```bash
npx tsx scripts/workspaces.ts setup
```
**What happens during setup:**
1. **Auth Discovery**: It will detect your `GEMINI_API_KEY` (from `~/.env`) and
`GH_TOKEN`.
2. **Project Choice**: You will be prompted for your GCP Project and Zone.
3. **Infrastructure Check**: It verifies if your worker
(`gcli-workspace-<user>`) exists.
4. **SSH Magic**: It generates a local `.gemini/workspaces/ssh_config` for
seamless access.
## 3. Provisioning
If the setup informs you that the worker was not found, provision it:
```bash
npx tsx scripts/workspaces.ts fleet provision
```
_This creates a VM with a 10GB Boot Disk and a 200GB Data Disk. Initialization
takes ~1 minute._
## 4. Finalizing Remote Setup
Run the setup script one last time to clone the repo and sync credentials:
```bash
npx tsx scripts/workspaces.ts setup
```
_When you see "ALL SYSTEMS GO!", your workspace is ready._
## 5. Daily Usage
Once initialized, you can launch tasks directly through `npm` or the entry
point:
- **Review a PR**: `workspace <PR_NUMBER> review`
- **Launch a Shell**: `workspace:shell <ID>`
- **Check Status**: `workspace:status`
- **Cleanup All**: `workspace:clean-all`
- **Kill Task**: `workspace:kill <PR> <action>`
- **Stop Worker**: `npx tsx scripts/workspaces.ts fleet stop` (Recommended when
finished to save cost).
## Troubleshooting
- **Permission Denied (Docker)**: The orchestrator handles this by using
`sudo docker` internally.
- **Dubious Ownership**: The system automatically adds `/mnt/disks/data/main` to
Git's safe directory list.
- **Missing tsx**: Always prefer `npx tsx` when running scripts manually.
+6 -2
View File
@@ -125,6 +125,10 @@ on GitHub.
## Announcements: v0.28.0 - 2026-02-10
- **Slash Command:** We've added a new `/prompt-suggest` slash command to help
you generate prompt suggestions
([#17264](https://github.com/google-gemini/gemini-cli/pull/17264) by
@NTaylorMullen).
- **IDE Support:** Gemini CLI now supports the Positron IDE
([#15047](https://github.com/google-gemini/gemini-cli/pull/15047) by
@kapsner).
@@ -164,8 +168,8 @@ on GitHub.
([#16638](https://github.com/google-gemini/gemini-cli/pull/16638) by
@joshualitt).
- **UI/UX Improvements:** You can now "Rewind" through your conversation history
([#15717](https://github.com/google-gemini/gemini-cli/pull/15717) by
@Adib234).
([#15717](https://github.com/google-gemini/gemini-cli/pull/15717) by @Adib234)
and use a new `/introspect` command for debugging.
- **Core and Scheduler Refactoring:** The core scheduler has been significantly
refactored to improve performance and reliability
([#16895](https://github.com/google-gemini/gemini-cli/pull/16895) by
+3 -6
View File
@@ -1,6 +1,6 @@
# Latest stable release: v0.33.2
# Latest stable release: v0.33.1
Released: March 16, 2026
Released: March 12, 2026
For most users, our latest stable release is the recommended release. Install
the latest stable version with:
@@ -29,9 +29,6 @@ npm install -g @google/gemini-cli
## What's Changed
- fix(patch): cherry-pick 48130eb to release/v0.33.1-pr-22665 [CONFLICTS] by
@gemini-cli-robot in
[#22720](https://github.com/google-gemini/gemini-cli/pull/22720)
- fix(patch): cherry-pick 8432bce to release/v0.33.0-pr-22069 to patch version
v0.33.0 and create version 0.33.1 by @gemini-cli-robot in
[#22206](https://github.com/google-gemini/gemini-cli/pull/22206)
@@ -234,4 +231,4 @@ npm install -g @google/gemini-cli
[#21952](https://github.com/google-gemini/gemini-cli/pull/21952)
**Full Changelog**:
https://github.com/google-gemini/gemini-cli/compare/v0.32.1...v0.33.2
https://github.com/google-gemini/gemini-cli/compare/v0.32.1...v0.33.1
+3 -15
View File
@@ -1,6 +1,6 @@
# Preview release: v0.34.0-preview.4
# Preview release: v0.34.0-preview.1
Released: March 16, 2026
Released: March 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).
@@ -28,18 +28,6 @@ npm install -g @google/gemini-cli@preview
## What's Changed
- fix(patch): cherry-pick 48130eb to release/v0.34.0-preview.3-pr-22665 to patch
version v0.34.0-preview.3 and create version 0.34.0-preview.4 by
@gemini-cli-robot in
[#22719](https://github.com/google-gemini/gemini-cli/pull/22719)
- fix(patch): cherry-pick 24adacd to release/v0.34.0-preview.2-pr-22332 to patch
version v0.34.0-preview.2 and create version 0.34.0-preview.3 by
@gemini-cli-robot in
[#22391](https://github.com/google-gemini/gemini-cli/pull/22391)
- fix(patch): cherry-pick 8432bce to release/v0.34.0-preview.1-pr-22069 to patch
version v0.34.0-preview.1 and create version 0.34.0-preview.2 by
@gemini-cli-robot in
[#22205](https://github.com/google-gemini/gemini-cli/pull/22205)
- fix(patch): cherry-pick 45faf4d to release/v0.34.0-preview.0-pr-22148
[CONFLICTS] by @gemini-cli-robot in
[#22174](https://github.com/google-gemini/gemini-cli/pull/22174)
@@ -480,4 +468,4 @@ npm install -g @google/gemini-cli@preview
[#21938](https://github.com/google-gemini/gemini-cli/pull/21938)
**Full Changelog**:
https://github.com/google-gemini/gemini-cli/compare/v0.33.0-preview.15...v0.34.0-preview.4
https://github.com/google-gemini/gemini-cli/compare/v0.33.0-preview.15...v0.34.0-preview.1
+1 -2
View File
@@ -120,8 +120,7 @@ These are the only allowed tools:
[`list_directory`](../tools/file-system.md#1-list_directory-readfolder),
[`glob`](../tools/file-system.md#4-glob-findfiles)
- **Search:** [`grep_search`](../tools/file-system.md#5-grep_search-searchtext),
[`google_web_search`](../tools/web-search.md),
[`get_internal_docs`](../tools/internal-docs.md)
[`google_web_search`](../tools/web-search.md)
- **Research Subagents:**
[`codebase_investigator`](../core/subagents.md#codebase-investigator),
[`cli_help`](../core/subagents.md#cli-help-agent)
-3
View File
@@ -125,9 +125,7 @@ they appear in the UI.
| UI Label | Setting | Description | Default |
| ------------------------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- |
| Tool Sandboxing | `security.toolSandboxing` | Experimental tool-level sandboxing (implementation in progress). | `false` |
| Disable YOLO Mode | `security.disableYoloMode` | Disable YOLO mode, even if enabled by a flag. | `false` |
| Disable Always Allow | `security.disableAlwaysAllow` | Disable "Always allow" options in tool confirmation dialogs. | `false` |
| Allow Permanent Tool Approval | `security.enablePermanentToolApproval` | Enable the "Allow for all future sessions" option in tool confirmation dialogs. | `false` |
| Auto-add to Policy by Default | `security.autoAddToPolicyByDefault` | When enabled, the "Allow for all future sessions" option becomes the default choice for low-risk tools in trusted workspaces. | `false` |
| Blocks extensions from Git | `security.blockGitExtensions` | Blocks installing and loading extensions from Git. | `false` |
@@ -152,7 +150,6 @@ they appear in the UI.
| Plan | `experimental.plan` | Enable Plan Mode. | `true` |
| Model Steering | `experimental.modelSteering` | Enable model steering (user hints) to guide the model during tool execution. | `false` |
| Direct Web Fetch | `experimental.directWebFetch` | Enable web fetch behavior that bypasses LLM summarization. | `false` |
| Topic & Update Narration | `experimental.topicUpdateNarration` | Enable the experimental Topic & Update communication model for reduced chattiness and structured progress reporting. | `false` |
### Skills
-282
View File
@@ -25,20 +25,6 @@ To use remote subagents, you must explicitly enable them in your
}
```
## Proxy support
Gemini CLI routes traffic to remote agents through an HTTP/HTTPS proxy if one is
configured. It uses the `general.proxy` setting in your `settings.json` file or
standard environment variables (`HTTP_PROXY`, `HTTPS_PROXY`).
```json
{
"general": {
"proxy": "http://my-proxy:8080"
}
}
```
## Defining remote subagents
Remote subagents are defined as Markdown files (`.md`) with YAML frontmatter.
@@ -54,7 +40,6 @@ You can place them in:
| `kind` | string | Yes | Must be `remote`. |
| `name` | string | Yes | A unique name for the agent. Must be a valid slug (lowercase letters, numbers, hyphens, and underscores only). |
| `agent_card_url` | string | Yes | The URL to the agent's A2A card endpoint. |
| `auth` | object | No | Authentication configuration. See [Authentication](#authentication). |
### Single-subagent example
@@ -85,273 +70,6 @@ Markdown file.
> **Note:** Mixed local and remote agents, or multiple local agents, are not
> supported in a single file; the list format is currently remote-only.
## Authentication
Many remote agents require authentication. Gemini CLI supports several
authentication methods aligned with the
[A2A security specification](https://a2a-protocol.org/latest/specification/#451-securityscheme).
Add an `auth` block to your agent's frontmatter to configure credentials.
### Supported auth types
Gemini CLI supports the following authentication types:
| Type | Description |
| :------------------- | :--------------------------------------------------------------------------------------------- |
| `apiKey` | Send a static API key as an HTTP header. |
| `http` | HTTP authentication (Bearer token, Basic credentials, or any IANA-registered scheme). |
| `google-credentials` | Google Application Default Credentials (ADC). Automatically selects access or identity tokens. |
| `oauth2` | OAuth 2.0 Authorization Code flow with PKCE. Opens a browser for interactive sign-in. |
### Dynamic values
For `apiKey` and `http` auth types, secret values (`key`, `token`, `username`,
`password`, `value`) support dynamic resolution:
| Format | Description | Example |
| :---------- | :-------------------------------------------------- | :------------------------- |
| `$ENV_VAR` | Read from an environment variable. | `$MY_API_KEY` |
| `!command` | Execute a shell command and use the trimmed output. | `!gcloud auth print-token` |
| literal | Use the string as-is. | `sk-abc123` |
| `$$` / `!!` | Escape prefix. `$$FOO` becomes the literal `$FOO`. | `$$NOT_AN_ENV_VAR` |
> **Security tip:** Prefer `$ENV_VAR` or `!command` over embedding secrets
> directly in agent files, especially for project-level agents checked into
> version control.
### API key (`apiKey`)
Sends an API key as an HTTP header on every request.
| Field | Type | Required | Description |
| :----- | :----- | :------- | :---------------------------------------------------- |
| `type` | string | Yes | Must be `apiKey`. |
| `key` | string | Yes | The API key value. Supports dynamic values. |
| `name` | string | No | Header name to send the key in. Default: `X-API-Key`. |
```yaml
---
kind: remote
name: my-agent
agent_card_url: https://example.com/agent-card
auth:
type: apiKey
key: $MY_API_KEY
---
```
### HTTP authentication (`http`)
Supports Bearer tokens, Basic auth, and arbitrary IANA-registered HTTP
authentication schemes.
#### Bearer token
Use the following fields to configure a Bearer token:
| Field | Type | Required | Description |
| :------- | :----- | :------- | :----------------------------------------- |
| `type` | string | Yes | Must be `http`. |
| `scheme` | string | Yes | Must be `Bearer`. |
| `token` | string | Yes | The bearer token. Supports dynamic values. |
```yaml
auth:
type: http
scheme: Bearer
token: $MY_BEARER_TOKEN
```
#### Basic authentication
Use the following fields to configure Basic authentication:
| Field | Type | Required | Description |
| :--------- | :----- | :------- | :------------------------------------- |
| `type` | string | Yes | Must be `http`. |
| `scheme` | string | Yes | Must be `Basic`. |
| `username` | string | Yes | The username. Supports dynamic values. |
| `password` | string | Yes | The password. Supports dynamic values. |
```yaml
auth:
type: http
scheme: Basic
username: $MY_USERNAME
password: $MY_PASSWORD
```
#### Raw scheme
For any other IANA-registered scheme (for example, Digest, HOBA), provide the
raw authorization value.
| Field | Type | Required | Description |
| :------- | :----- | :------- | :---------------------------------------------------------------------------- |
| `type` | string | Yes | Must be `http`. |
| `scheme` | string | Yes | The scheme name (for example, `Digest`). |
| `value` | string | Yes | Raw value sent as `Authorization: <scheme> <value>`. Supports dynamic values. |
```yaml
auth:
type: http
scheme: Digest
value: $MY_DIGEST_VALUE
```
### Google Application Default Credentials (`google-credentials`)
Uses
[Google Application Default Credentials (ADC)](https://cloud.google.com/docs/authentication/application-default-credentials)
to authenticate with Google Cloud services and Cloud Run endpoints. This is the
recommended auth method for agents hosted on Google Cloud infrastructure.
| Field | Type | Required | Description |
| :------- | :------- | :------- | :-------------------------------------------------------------------------- |
| `type` | string | Yes | Must be `google-credentials`. |
| `scopes` | string[] | No | OAuth scopes. Defaults to `https://www.googleapis.com/auth/cloud-platform`. |
```yaml
---
kind: remote
name: my-gcp-agent
agent_card_url: https://my-agent-xyz.run.app/.well-known/agent.json
auth:
type: google-credentials
---
```
#### How token selection works
The provider automatically selects the correct token type based on the agent's
host:
| Host pattern | Token type | Use case |
| :----------------- | :----------------- | :------------------------------------------ |
| `*.googleapis.com` | **Access token** | Google APIs (Agent Engine, Vertex AI, etc.) |
| `*.run.app` | **Identity token** | Cloud Run services |
- **Access tokens** authorize API calls to Google services. They are scoped
(default: `cloud-platform`) and fetched via `GoogleAuth.getClient()`.
- **Identity tokens** prove the caller's identity to a service that validates
the token's audience. The audience is set to the target host. These are
fetched via `GoogleAuth.getIdTokenClient()`.
Both token types are cached and automatically refreshed before expiry.
#### Setup
`google-credentials` relies on ADC, which means your environment must have
credentials configured. Common setups:
- **Local development:** Run `gcloud auth application-default login` to
authenticate with your Google account.
- **CI / Cloud environments:** Use a service account. Set the
`GOOGLE_APPLICATION_CREDENTIALS` environment variable to the path of your
service account key file, or use workload identity on GKE / Cloud Run.
#### Allowed hosts
For security, `google-credentials` only sends tokens to known Google-owned
hosts:
- `*.googleapis.com`
- `*.run.app`
Requests to any other host will be rejected with an error. If your agent is
hosted on a different domain, use one of the other auth types (`apiKey`, `http`,
or `oauth2`).
#### Examples
The following examples demonstrate how to configure Google Application Default
Credentials.
**Cloud Run agent:**
```yaml
---
kind: remote
name: cloud-run-agent
agent_card_url: https://my-agent-xyz.run.app/.well-known/agent.json
auth:
type: google-credentials
---
```
**Google API with custom scopes:**
```yaml
---
kind: remote
name: vertex-agent
agent_card_url: https://us-central1-aiplatform.googleapis.com/.well-known/agent.json
auth:
type: google-credentials
scopes:
- https://www.googleapis.com/auth/cloud-platform
- https://www.googleapis.com/auth/compute
---
```
### OAuth 2.0 (`oauth2`)
Performs an interactive OAuth 2.0 Authorization Code flow with PKCE. On first
use, Gemini CLI opens your browser for sign-in and persists the resulting tokens
for subsequent requests.
| Field | Type | Required | Description |
| :------------------ | :------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------- |
| `type` | string | Yes | Must be `oauth2`. |
| `client_id` | string | Yes\* | OAuth client ID. Required for interactive auth. |
| `client_secret` | string | No\* | OAuth client secret. Required by most authorization servers (confidential clients). Can be omitted for public clients that don't require a secret. |
| `scopes` | string[] | No | Requested scopes. Can also be discovered from the agent card. |
| `authorization_url` | string | No | Authorization endpoint. Discovered from the agent card if omitted. |
| `token_url` | string | No | Token endpoint. Discovered from the agent card if omitted. |
```yaml
---
kind: remote
name: oauth-agent
agent_card_url: https://example.com/.well-known/agent.json
auth:
type: oauth2
client_id: my-client-id.apps.example.com
---
```
If the agent card advertises an `oauth2` security scheme with
`authorizationCode` flow, the `authorization_url`, `token_url`, and `scopes` are
automatically discovered. You only need to provide `client_id` (and
`client_secret` if required).
Tokens are persisted to disk and refreshed automatically when they expire.
### Auth validation
When Gemini CLI loads a remote agent, it validates your auth configuration
against the agent card's declared `securitySchemes`. If the agent requires
authentication that you haven't configured, you'll see an error describing
what's needed.
`google-credentials` is treated as compatible with `http` Bearer security
schemes, since it produces Bearer tokens.
### Auth retry behavior
All auth providers automatically retry on `401` and `403` responses by
re-fetching credentials (up to 2 retries). This handles cases like expired
tokens or rotated credentials. For `apiKey` with `!command` values, the command
is re-executed on retry to fetch a fresh key.
### Agent card fetching and auth
When connecting to a remote agent, Gemini CLI first fetches the agent card
**without** authentication. If the card endpoint returns a `401` or `403`, it
retries the fetch **with** the configured auth headers. This lets agents have
publicly accessible cards while protecting their task endpoints, or to protect
both behind auth.
## Managing Subagents
Users can manage subagents using the following commands within the Gemini CLI:
+27 -137
View File
@@ -7,14 +7,20 @@ the main agent's context or toolset.
> **Note: Subagents are currently an experimental feature.**
>
> To use custom subagents, you must ensure they are enabled in your
> `settings.json` (enabled by default):
> To use custom subagents, you must explicitly enable them in your
> `settings.json`:
>
> ```json
> {
> "experimental": { "enableAgents": true }
> }
> ```
>
> **Warning:** Subagents currently operate in
> ["YOLO mode"](../reference/configuration.md#command-line-arguments), meaning
> they may execute tools without individual user confirmation for each step.
> Proceed with caution when defining agents with powerful tools like
> `run_shell_command` or `write_file`.
## What are subagents?
@@ -32,34 +38,6 @@ main agent calls the tool, it delegates the task to the subagent. Once the
subagent completes its task, it reports back to the main agent with its
findings.
## How to use subagents
You can use subagents through automatic delegation or by explicitly forcing them
in your prompt.
### Automatic delegation
Gemini CLI's main agent is instructed to use specialized subagents when a task
matches their expertise. For example, if you ask "How does the auth system
work?", the main agent may decide to call the `codebase_investigator` subagent
to perform the research.
### Forcing a subagent (@ syntax)
You can explicitly direct a task to a specific subagent by using the `@` symbol
followed by the subagent's name at the beginning of your prompt. This is useful
when you want to bypass the main agent's decision-making and go straight to a
specialist.
**Example:**
```bash
@codebase_investigator Map out the relationship between the AgentRegistry and the LocalAgentExecutor.
```
When you use the `@` syntax, the CLI injects a system note that nudges the
primary model to use that specific subagent tool immediately.
## Built-in subagents
Gemini CLI comes with the following built-in subagents:
@@ -71,17 +49,15 @@ Gemini CLI comes with the following built-in subagents:
dependencies.
- **When to use:** "How does the authentication system work?", "Map out the
dependencies of the `AgentRegistry` class."
- **Configuration:** Enabled by default. You can override its settings in
`settings.json` under `agents.overrides`. Example (forcing a specific model
and increasing turns):
- **Configuration:** Enabled by default. You can configure it in
`settings.json`. Example (forcing a specific model):
```json
{
"agents": {
"overrides": {
"codebase_investigator": {
"modelConfig": { "model": "gemini-3-flash-preview" },
"runConfig": { "maxTurns": 50 }
}
"experimental": {
"codebaseInvestigatorSettings": {
"enabled": true,
"maxNumTurns": 20,
"model": "gemini-2.5-pro"
}
}
}
@@ -257,7 +233,7 @@ kind: local
tools:
- read_file
- grep_search
model: gemini-3-flash-preview
model: gemini-2.5-pro
temperature: 0.2
max_turns: 10
---
@@ -278,102 +254,16 @@ it yourself; just report it.
### Configuration schema
| Field | Type | Required | Description |
| :------------- | :----- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `name` | string | Yes | Unique identifier (slug) used as the tool name for the agent. Only lowercase letters, numbers, hyphens, and underscores. |
| `description` | string | Yes | Short description of what the agent does. This is visible to the main agent to help it decide when to call this subagent. |
| `kind` | string | No | `local` (default) or `remote`. |
| `tools` | array | No | List of tool names this agent can use. Supports wildcards: `*` (all tools), `mcp_*` (all MCP tools), `mcp_server_*` (all tools from a server). **If omitted, it inherits all tools from the parent session.** |
| `model` | string | No | Specific model to use (e.g., `gemini-3-preview`). Defaults to `inherit` (uses the main session model). |
| `temperature` | number | No | Model temperature (0.0 - 2.0). Defaults to `1`. |
| `max_turns` | number | No | Maximum number of conversation turns allowed for this agent before it must return. Defaults to `30`. |
| `timeout_mins` | number | No | Maximum execution time in minutes. Defaults to `10`. |
### Tool wildcards
When defining `tools` for a subagent, you can use wildcards to quickly grant
access to groups of tools:
- `*`: Grant access to all available built-in and discovered tools.
- `mcp_*`: Grant access to all tools from all connected MCP servers.
- `mcp_my-server_*`: Grant access to all tools from a specific MCP server named
`my-server`.
### Isolation and recursion protection
Each subagent runs in its own isolated context loop. This means:
- **Independent history:** The subagent's conversation history does not bloat
the main agent's context.
- **Isolated tools:** The subagent only has access to the tools you explicitly
grant it.
- **Recursion protection:** To prevent infinite loops and excessive token usage,
subagents **cannot** call other subagents. If a subagent is granted the `*`
tool wildcard, it will still be unable to see or invoke other agents.
## Managing subagents
You can manage subagents interactively using the `/agents` command or
persistently via `settings.json`.
### Interactive management (/agents)
If you are in an interactive CLI session, you can use the `/agents` command to
manage subagents without editing configuration files manually. This is the
recommended way to quickly enable, disable, or re-configure agents on the fly.
For a full list of sub-commands and usage, see the
[`/agents` command reference](../reference/commands.md#agents).
### Persistent configuration (settings.json)
While the `/agents` command and agent definition files provide a starting point,
you can use `settings.json` for global, persistent overrides. This is useful for
enforcing specific models or execution limits across all sessions.
#### `agents.overrides`
Use this to enable or disable specific agents or override their run
configurations.
```json
{
"agents": {
"overrides": {
"security-auditor": {
"enabled": false,
"runConfig": {
"maxTurns": 20,
"maxTimeMinutes": 10
}
}
}
}
}
```
#### `modelConfigs.overrides`
You can target specific subagents with custom model settings (like system
instruction prefixes or specific safety settings) using the `overrideScope`
field.
```json
{
"modelConfigs": {
"overrides": [
{
"match": { "overrideScope": "security-auditor" },
"modelConfig": {
"generateContentConfig": {
"temperature": 0.1
}
}
}
]
}
}
```
| Field | Type | Required | Description |
| :------------- | :----- | :------- | :------------------------------------------------------------------------------------------------------------------------ |
| `name` | string | Yes | Unique identifier (slug) used as the tool name for the agent. Only lowercase letters, numbers, hyphens, and underscores. |
| `description` | string | Yes | Short description of what the agent does. This is visible to the main agent to help it decide when to call this subagent. |
| `kind` | string | No | `local` (default) or `remote`. |
| `tools` | array | No | List of tool names this agent can use. If omitted, it may have access to a default set. |
| `model` | string | No | Specific model to use (e.g., `gemini-2.5-pro`). Defaults to `inherit` (uses the main session model). |
| `temperature` | number | No | Model temperature (0.0 - 2.0). |
| `max_turns` | number | No | Maximum number of conversation turns allowed for this agent before it must return. Defaults to `15`. |
| `timeout_mins` | number | No | Maximum execution time in minutes. Defaults to `5`. |
### Optimizing your subagent
@@ -408,7 +298,7 @@ Gemini CLI can also delegate tasks to remote subagents using the Agent-to-Agent
> **Note: Remote subagents are currently an experimental feature.**
See the [Remote Subagents documentation](remote-agents) for detailed
configuration, authentication, and usage instructions.
configuration and usage instructions.
## Extension subagents
-25
View File
@@ -14,31 +14,6 @@ Slash commands provide meta-level control over the CLI itself.
- **Description:** Show version info. Share this information when filing issues.
### `/agents`
- **Description:** Manage local and remote subagents.
- **Note:** This command is experimental and requires
`experimental.enableAgents: true` in your `settings.json`.
- **Sub-commands:**
- **`list`**:
- **Description:** Lists all discovered agents, including built-in, local,
and remote agents.
- **Usage:** `/agents list`
- **`reload`** (alias: `refresh`):
- **Description:** Rescans agent directories (`~/.gemini/agents` and
`.gemini/agents`) and reloads the registry.
- **Usage:** `/agents reload`
- **`enable`**:
- **Description:** Enables a specific subagent.
- **Usage:** `/agents enable <agent-name>`
- **`disable`**:
- **Description:** Disables a specific subagent.
- **Usage:** `/agents disable <agent-name>`
- **`config`**:
- **Description:** Opens a configuration dialog for the specified agent to
adjust its model, temperature, or execution limits.
- **Usage:** `/agents config <agent-name>`
### `/auth`
- **Description:** Open a dialog that lets you change the authentication method.
+16 -227
View File
@@ -688,7 +688,7 @@ their corresponding top-level category object in your `settings.json` file.
"tier": "pro",
"family": "gemini-3",
"isPreview": true,
"isVisible": true,
"dialogLocation": "manual",
"features": {
"thinking": true,
"multimodalToolUse": true
@@ -698,7 +698,6 @@ their corresponding top-level category object in your `settings.json` file.
"tier": "pro",
"family": "gemini-3",
"isPreview": true,
"isVisible": false,
"features": {
"thinking": true,
"multimodalToolUse": true
@@ -708,7 +707,7 @@ their corresponding top-level category object in your `settings.json` file.
"tier": "pro",
"family": "gemini-3",
"isPreview": true,
"isVisible": true,
"dialogLocation": "manual",
"features": {
"thinking": true,
"multimodalToolUse": true
@@ -718,7 +717,7 @@ their corresponding top-level category object in your `settings.json` file.
"tier": "flash",
"family": "gemini-3",
"isPreview": true,
"isVisible": true,
"dialogLocation": "manual",
"features": {
"thinking": false,
"multimodalToolUse": true
@@ -728,7 +727,7 @@ their corresponding top-level category object in your `settings.json` file.
"tier": "pro",
"family": "gemini-2.5",
"isPreview": false,
"isVisible": true,
"dialogLocation": "manual",
"features": {
"thinking": false,
"multimodalToolUse": false
@@ -738,7 +737,7 @@ their corresponding top-level category object in your `settings.json` file.
"tier": "flash",
"family": "gemini-2.5",
"isPreview": false,
"isVisible": true,
"dialogLocation": "manual",
"features": {
"thinking": false,
"multimodalToolUse": false
@@ -748,7 +747,7 @@ their corresponding top-level category object in your `settings.json` file.
"tier": "flash-lite",
"family": "gemini-2.5",
"isPreview": false,
"isVisible": true,
"dialogLocation": "manual",
"features": {
"thinking": false,
"multimodalToolUse": false
@@ -757,7 +756,6 @@ their corresponding top-level category object in your `settings.json` file.
"auto": {
"tier": "auto",
"isPreview": true,
"isVisible": false,
"features": {
"thinking": true,
"multimodalToolUse": false
@@ -766,7 +764,6 @@ their corresponding top-level category object in your `settings.json` file.
"pro": {
"tier": "pro",
"isPreview": false,
"isVisible": false,
"features": {
"thinking": true,
"multimodalToolUse": false
@@ -775,7 +772,6 @@ their corresponding top-level category object in your `settings.json` file.
"flash": {
"tier": "flash",
"isPreview": false,
"isVisible": false,
"features": {
"thinking": false,
"multimodalToolUse": false
@@ -784,7 +780,6 @@ their corresponding top-level category object in your `settings.json` file.
"flash-lite": {
"tier": "flash-lite",
"isPreview": false,
"isVisible": false,
"features": {
"thinking": false,
"multimodalToolUse": false
@@ -794,7 +789,7 @@ their corresponding top-level category object in your `settings.json` file.
"displayName": "Auto (Gemini 3)",
"tier": "auto",
"isPreview": true,
"isVisible": true,
"dialogLocation": "main",
"dialogDescription": "Let Gemini CLI decide the best model for the task: gemini-3.1-pro, gemini-3-flash",
"features": {
"thinking": true,
@@ -805,7 +800,7 @@ their corresponding top-level category object in your `settings.json` file.
"displayName": "Auto (Gemini 2.5)",
"tier": "auto",
"isPreview": false,
"isVisible": true,
"dialogLocation": "main",
"dialogDescription": "Let Gemini CLI decide the best model for the task: gemini-2.5-pro, gemini-2.5-flash",
"features": {
"thinking": false,
@@ -817,184 +812,6 @@ their corresponding top-level category object in your `settings.json` file.
- **Requires restart:** Yes
- **`modelConfigs.modelIdResolutions`** (object):
- **Description:** Rules for resolving requested model names to concrete model
IDs based on context.
- **Default:**
```json
{
"gemini-3-pro-preview": {
"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-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": {
"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"
}
]
},
"pro": {
"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"
},
"flash": {
"default": "gemini-3-flash-preview",
"contexts": [
{
"condition": {
"hasAccessToPreview": false
},
"target": "gemini-2.5-flash"
}
]
},
"flash-lite": {
"default": "gemini-2.5-flash-lite"
}
}
```
- **Requires restart:** Yes
- **`modelConfigs.classifierIdResolutions`** (object):
- **Description:** Rules for resolving classifier tiers (flash, pro) to
concrete model IDs.
- **Default:**
```json
{
"flash": {
"default": "gemini-3-flash-preview",
"contexts": [
{
"condition": {
"requestedModels": ["auto-gemini-2.5", "gemini-2.5-pro"]
},
"target": "gemini-2.5-flash"
},
{
"condition": {
"requestedModels": ["auto-gemini-3", "gemini-3-pro-preview"]
},
"target": "gemini-3-flash-preview"
}
]
},
"pro": {
"default": "gemini-3-pro-preview",
"contexts": [
{
"condition": {
"requestedModels": ["auto-gemini-2.5", "gemini-2.5-pro"]
},
"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"
}
]
}
}
```
- **Requires restart:** Yes
#### `agents`
- **`agents.overrides`** (object):
@@ -1024,17 +841,6 @@ their corresponding top-level category object in your `settings.json` file.
- **Default:** `undefined`
- **Requires restart:** Yes
- **`agents.browser.allowedDomains`** (array):
- **Description:** A list of allowed domains for the browser agent (e.g.,
["github.com", "*.google.com"]).
- **Default:**
```json
["github.com", "*.google.com", "localhost"]
```
- **Requires restart:** Yes
- **`agents.browser.disableUserInput`** (boolean):
- **Description:** Disable user input on browser window during automation.
- **Default:** `true`
@@ -1102,10 +908,9 @@ their corresponding top-level category object in your `settings.json` file.
#### `tools`
- **`tools.sandbox`** (string):
- **Description:** Legacy full-process sandbox execution environment. Set to a
boolean to enable or disable the sandbox, provide a string path to a sandbox
profile, or specify an explicit sandbox command (e.g., "docker", "podman",
"lxc").
- **Description:** Sandbox execution environment. Set to a boolean to enable
or disable the sandbox, provide a string path to a sandbox profile, or
specify an explicit sandbox command (e.g., "docker", "podman", "lxc").
- **Default:** `undefined`
- **Requires restart:** Yes
@@ -1209,22 +1014,11 @@ their corresponding top-level category object in your `settings.json` file.
#### `security`
- **`security.toolSandboxing`** (boolean):
- **Description:** Experimental tool-level sandboxing (implementation in
progress).
- **Default:** `false`
- **`security.disableYoloMode`** (boolean):
- **Description:** Disable YOLO mode, even if enabled by a flag.
- **Default:** `false`
- **Requires restart:** Yes
- **`security.disableAlwaysAllow`** (boolean):
- **Description:** Disable "Always allow" options in tool confirmation
dialogs.
- **Default:** `false`
- **Requires restart:** Yes
- **`security.enablePermanentToolApproval`** (boolean):
- **Description:** Enable the "Allow for all future sessions" option in tool
confirmation dialogs.
@@ -1341,8 +1135,9 @@ their corresponding top-level category object in your `settings.json` file.
- **Requires restart:** Yes
- **`experimental.enableAgents`** (boolean):
- **Description:** Enable local and remote subagents.
- **Default:** `true`
- **Description:** Enable local and remote subagents. Warning: Experimental
feature, uses YOLO mode for subagents
- **Default:** `false`
- **Requires restart:** Yes
- **`experimental.extensionManagement`** (boolean):
@@ -1373,7 +1168,7 @@ their corresponding top-level category object in your `settings.json` file.
- **`experimental.jitContext`** (boolean):
- **Description:** Enable Just-In-Time (JIT) context loading.
- **Default:** `true`
- **Default:** `false`
- **Requires restart:** Yes
- **`experimental.useOSC52Paste`** (boolean):
@@ -1431,11 +1226,6 @@ their corresponding top-level category object in your `settings.json` file.
- **Default:** `"gemma3-1b-gpu-custom"`
- **Requires restart:** Yes
- **`experimental.topicUpdateNarration`** (boolean):
- **Description:** Enable the experimental Topic & Update communication model
for reduced chattiness and structured progress reporting.
- **Default:** `false`
#### `skills`
- **`skills.enabled`** (boolean):
@@ -1525,8 +1315,7 @@ their corresponding top-level category object in your `settings.json` file.
#### `admin`
- **`admin.secureModeEnabled`** (boolean):
- **Description:** If true, disallows YOLO mode and "Always allow" options
from being used.
- **Description:** If true, disallows yolo mode from being used.
- **Default:** `false`
- **`admin.extensions.enabled`** (boolean):
+3 -3
View File
@@ -60,7 +60,7 @@ command.
```toml
[[rule]]
toolName = "run_shell_command"
commandPrefix = "git"
commandPrefix = "git "
decision = "ask_user"
priority = 100
```
@@ -264,7 +264,7 @@ argsPattern = '"command":"(git|npm)'
# (Optional) A string or array of strings that a shell command must start with.
# This is syntactic sugar for `toolName = "run_shell_command"` and an `argsPattern`.
commandPrefix = "git"
commandPrefix = "git "
# (Optional) A regex to match against the entire shell command.
# This is also syntactic sugar for `toolName = "run_shell_command"`.
@@ -321,7 +321,7 @@ This rule will ask for user confirmation before executing any `git` command.
```toml
[[rule]]
toolName = "run_shell_command"
commandPrefix = "git"
commandPrefix = "git "
decision = "ask_user"
priority = 100
```
+1 -2
View File
@@ -25,8 +25,7 @@ confirmation.
- `label` (string, required): Display text (1-5 words).
- `description` (string, required): Brief explanation.
- `multiSelect` (boolean, optional): For `'choice'` type, allows selecting
multiple options. Automatically adds an "All the above" option if there
are multiple standard options.
multiple options.
- `placeholder` (string, optional): Hint text for input fields.
- **Behavior:**
-37
View File
@@ -729,43 +729,6 @@ tools. The model will automatically:
The MCP integration tracks several states:
#### Overriding extension configurations
If an MCP server is provided by an extension (for example, the
`google-workspace` extension), you can still override its settings in your local
`settings.json`. Gemini CLI merges your local configuration with the extension's
defaults:
- **Tool lists:** Tool lists are merged securely to ensure the most restrictive
policy wins:
- **Exclusions (`excludeTools`):** Arrays are combined (unioned). If either
source blocks a tool, it remains disabled.
- **Inclusions (`includeTools`):** Arrays are intersected. If both sources
provide an allowlist, only tools present in **both** lists are enabled. If
only one source provides an allowlist, that list is respected.
- **Precedence:** `excludeTools` always takes precedence over `includeTools`.
This ensures you always have veto power over tools provided by an extension
and that an extension cannot re-enable tools you have omitted from your
personal allowlist.
- **Environment variables:** The `env` objects are merged. If the same variable
is defined in both places, your local value takes precedence.
- **Scalar properties:** Properties like `command`, `url`, and `timeout` are
replaced by your local values if provided.
**Example override:**
```json
{
"mcpServers": {
"google-workspace": {
"excludeTools": ["gmail.send"]
}
}
}
```
#### Server status (`MCPServerStatus`)
- **`DISCONNECTED`:** Server is not connected or has errors
+1 -2
View File
@@ -13,8 +13,7 @@ updates to the CLI interface.
- `todos` (array of objects, required): The complete list of tasks. Each object
includes:
- `description` (string): Technical description of the task.
- `status` (enum): `pending`, `in_progress`, `completed`, `cancelled`, or
`blocked`.
- `status` (enum): `pending`, `in_progress`, `completed`, or `cancelled`.
## Technical behavior
+2 -18
View File
@@ -51,7 +51,6 @@ export default tseslint.config(
'evals/**',
'packages/test-utils/**',
'.gemini/skills/**',
'**/*.d.ts',
],
},
eslint.configs.recommended,
@@ -207,26 +206,11 @@ export default tseslint.config(
{
// Rules that only apply to product code
files: ['packages/*/src/**/*.{ts,tsx}'],
ignores: ['**/*.test.ts', '**/*.test.tsx', 'packages/*/src/test-utils/**'],
ignores: ['**/*.test.ts', '**/*.test.tsx'],
rules: {
'@typescript-eslint/no-unsafe-type-assertion': 'error',
'@typescript-eslint/no-unsafe-assignment': 'error',
'@typescript-eslint/no-unsafe-return': 'error',
'no-restricted-syntax': [
'error',
...commonRestrictedSyntaxRules,
{
selector:
'CallExpression[callee.object.name="Object"][callee.property.name="create"]',
message:
'Avoid using Object.create() in product code. Use object spread {...obj}, explicit class instantiation, structuredClone(), or copy constructors instead.',
},
{
selector: 'Identifier[name="Reflect"]',
message:
'Avoid using Reflect namespace in product code. Do not use reflection to make copies. Instead, use explicit object copying or cloning (structuredClone() for values, new instance/clone function for classes).',
},
],
},
},
{
@@ -319,7 +303,7 @@ export default tseslint.config(
},
},
{
files: ['./scripts/**/*.js', 'esbuild.config.js', 'packages/core/scripts/**/*.{js,mjs}'],
files: ['./scripts/**/*.js', 'esbuild.config.js'],
languageOptions: {
globals: {
...globals.node,
+1 -1
View File
@@ -111,7 +111,7 @@ describe('Answer vs. ask eval', () => {
* Ensures that when the user asks a question about style, the agent does NOT
* automatically modify the file.
*/
evalTest('ALWAYS_PASSES', {
evalTest('USUALLY_PASSES', {
name: 'should not edit files when asked about style',
prompt: 'Is app.ts following good style?',
files: FILES,
+33 -72
View File
@@ -5,62 +5,31 @@
*/
import { describe, expect } from 'vitest';
import { appEvalTest, AppEvalCase } from './app-test-helper.js';
import { EvalPolicy } from './test-helper.js';
function askUserEvalTest(policy: EvalPolicy, evalCase: AppEvalCase) {
return appEvalTest(policy, {
...evalCase,
configOverrides: {
...evalCase.configOverrides,
general: {
...evalCase.configOverrides?.general,
approvalMode: 'default',
enableAutoUpdate: false,
enableAutoUpdateNotification: false,
},
},
files: {
...evalCase.files,
},
});
}
import { evalTest } from './test-helper.js';
describe('ask_user', () => {
askUserEvalTest('USUALLY_PASSES', {
evalTest('USUALLY_PASSES', {
name: 'Agent uses AskUser tool to present multiple choice options',
prompt: `Use the ask_user tool to ask me what my favorite color is. Provide 3 options: red, green, or blue.`,
setup: async (rig) => {
rig.setBreakpoint(['ask_user']);
},
assert: async (rig) => {
const confirmation = await rig.waitForPendingConfirmation('ask_user');
expect(
confirmation,
'Expected a pending confirmation for ask_user tool',
).toBeDefined();
const wasToolCalled = await rig.waitForToolCall('ask_user');
expect(wasToolCalled, 'Expected ask_user tool to be called').toBe(true);
},
});
askUserEvalTest('USUALLY_PASSES', {
evalTest('USUALLY_PASSES', {
name: 'Agent uses AskUser tool to clarify ambiguous requirements',
files: {
'package.json': JSON.stringify({ name: 'my-app', version: '1.0.0' }),
},
prompt: `I want to build a new feature in this app. Ask me questions to clarify the requirements before proceeding.`,
setup: async (rig) => {
rig.setBreakpoint(['ask_user']);
},
assert: async (rig) => {
const confirmation = await rig.waitForPendingConfirmation('ask_user');
expect(
confirmation,
'Expected a pending confirmation for ask_user tool',
).toBeDefined();
const wasToolCalled = await rig.waitForToolCall('ask_user');
expect(wasToolCalled, 'Expected ask_user tool to be called').toBe(true);
},
});
askUserEvalTest('USUALLY_PASSES', {
evalTest('USUALLY_PASSES', {
name: 'Agent uses AskUser tool before performing significant ambiguous rework',
files: {
'packages/core/src/index.ts': '// index\nexport const version = "1.0.0";',
@@ -70,37 +39,28 @@ describe('ask_user', () => {
}),
'README.md': '# Gemini CLI',
},
prompt: `I want to completely rewrite the core package to support the upcoming V2 architecture, but I haven't decided what that looks like yet. We need to figure out the requirements first. Can you ask me some questions to help nail down the design?`,
setup: async (rig) => {
rig.setBreakpoint(['enter_plan_mode', 'ask_user']);
},
prompt: `Refactor the entire core package to be better.`,
assert: async (rig) => {
// It might call enter_plan_mode first.
let confirmation = await rig.waitForPendingConfirmation([
'enter_plan_mode',
'ask_user',
]);
expect(confirmation, 'Expected a tool call confirmation').toBeDefined();
if (confirmation?.name === 'enter_plan_mode') {
rig.acceptConfirmation('enter_plan_mode');
confirmation = await rig.waitForPendingConfirmation('ask_user');
}
const wasPlanModeCalled = await rig.waitForToolCall('enter_plan_mode');
expect(wasPlanModeCalled, 'Expected enter_plan_mode to be called').toBe(
true,
);
const wasAskUserCalled = await rig.waitForToolCall('ask_user');
expect(
confirmation?.toolName,
'Expected ask_user to be called to clarify the significant rework',
).toBe('ask_user');
wasAskUserCalled,
'Expected ask_user tool to be called to clarify the significant rework',
).toBe(true);
},
});
// --- Regression Tests for Recent Fixes ---
// Regression test for issue #20177: Ensure the agent does not use \`ask_user\` to
// Regression test for issue #20177: Ensure the agent does not use `ask_user` to
// confirm shell commands. Fixed via prompt refinements and tool definition
// updates to clarify that shell command confirmation is handled by the UI.
// See fix: https://github.com/google-gemini/gemini-cli/pull/20504
askUserEvalTest('USUALLY_PASSES', {
evalTest('USUALLY_PASSES', {
name: 'Agent does NOT use AskUser to confirm shell commands',
files: {
'package.json': JSON.stringify({
@@ -108,24 +68,25 @@ describe('ask_user', () => {
}),
},
prompt: `Run 'npm run build' in the current directory.`,
setup: async (rig) => {
rig.setBreakpoint(['run_shell_command', 'ask_user']);
},
assert: async (rig) => {
const confirmation = await rig.waitForPendingConfirmation([
'run_shell_command',
'ask_user',
]);
await rig.waitForTelemetryReady();
const toolLogs = rig.readToolLogs();
const wasShellCalled = toolLogs.some(
(log) => log.toolRequest.name === 'run_shell_command',
);
const wasAskUserCalled = toolLogs.some(
(log) => log.toolRequest.name === 'ask_user',
);
expect(
confirmation,
'Expected a pending confirmation for a tool',
).toBeDefined();
wasShellCalled,
'Expected run_shell_command tool to be called',
).toBe(true);
expect(
confirmation?.toolName,
wasAskUserCalled,
'ask_user should not be called to confirm shell commands',
).toBe('run_shell_command');
).toBe(false);
},
});
});
+1 -1
View File
@@ -11,7 +11,7 @@ import { assertModelHasOutput } from '../integration-tests/test-helper.js';
describe('Hierarchical Memory', () => {
const conflictResolutionTest =
'Agent follows hierarchy for contradictory instructions';
evalTest('ALWAYS_PASSES', {
evalTest('USUALLY_PASSES', {
name: conflictResolutionTest,
params: {
settings: {
+3 -3
View File
@@ -14,7 +14,7 @@ import {
describe('save_memory', () => {
const TEST_PREFIX = 'Save memory test: ';
const rememberingFavoriteColor = "Agent remembers user's favorite color";
evalTest('ALWAYS_PASSES', {
evalTest('USUALLY_PASSES', {
name: rememberingFavoriteColor,
params: {
settings: { tools: { core: ['save_memory'] } },
@@ -79,7 +79,7 @@ describe('save_memory', () => {
const ignoringTemporaryInformation =
'Agent ignores temporary conversation details';
evalTest('ALWAYS_PASSES', {
evalTest('USUALLY_PASSES', {
name: ignoringTemporaryInformation,
params: {
settings: { tools: { core: ['save_memory'] } },
@@ -104,7 +104,7 @@ describe('save_memory', () => {
});
const rememberingPetName = "Agent remembers user's pet's name";
evalTest('ALWAYS_PASSES', {
evalTest('USUALLY_PASSES', {
name: rememberingPetName,
params: {
settings: { tools: { core: ['save_memory'] } },
@@ -1,35 +0,0 @@
# Future State: Gemini Workspaces Platform
This document outlines the long-term architectural evolution of the Workspaces feature (formerly "Workspace").
## 🎯 Vision
Transform Workspaces into a first-class platform capability that allows developers to seamlessly move intensive workloads (AI reasoning, complex builds, parallel testing) to any compute environment (Cloud or Local).
## 🗺️ Evolutionary Roadmap
### Phase 1: Generalization & Renaming (Current)
- **Goal**: Make the feature useful for any repository, not just Gemini CLI.
- **Action**: Rename to "Workspaces."
- **Action**: Implement dynamic repository detection via Git.
- **Action**: Isolate all state into `.gemini/workspaces/`.
### Phase 2: Pluggable Compute Extensions
- **Goal**: Decouple the infrastructure logic from the core CLI.
- **Action**: Move `WorkerProviders` into a dedicated **Workspaces Extension**.
- **Action**: Support multiple providers (GCP, AWS, Local Docker).
- **Action**: Define a standard API for Workspace Providers.
### Phase 3: Core Integration
- **Goal**: Standardize the user experience.
- **Action**: Move the high-level `gemini workspace` command into the core `gemini` binary.
- **Action**: Implement automated "Environment Hand-off" where the local agent can automatically spin up a remote workspace when it detects a heavy task.
### Phase 4: Public Marketplace
- **Goal**: Community adoption.
- **Action**: Publish the official GCP Workspace Extension.
- **Action**: Provide a "Zero-Config" public base image for standard Node/TS development.
## 🏗️ Architectural Principles
1. **BYOC (Bring Your Own Cloud)**: Users connect their own infrastructure.
2. **Nested Persistence**: Keep the environment in the container, but manage the lifecycle with the host.
3. **Repo-Agnostic**: One set of tools should work for any project.
-28
View File
@@ -1,28 +0,0 @@
# Architectural Mandate: High-Performance Workspace System
## Infrastructure Strategy
- **Base OS**: Always use **Container-Optimized OS (COS)** (`cos-stable` family). It is security-hardened and has Docker pre-installed.
- **Provisioning**: Use the **Cloud-Init (`user-data`)** pattern.
- *Note*: Avoid `gcloud compute instances create-with-container` on standard Linux images as it uses a deprecated startup agent. On COS, use native `user-data` for cleanest execution.
- **Performance**: Provision with a minimum of **200GB PD-Balanced** disk to ensure high I/O throughput for Node.js builds and to satisfy GCP disk performance requirements.
## Container Isolation
- **Image**: `us-docker.pkg.dev/gemini-code-dev/gemini-cli/maintainer:latest`.
- **Identity**: The container must be named **`maintainer-worker`**.
- **Mounts**: Standardize on these host-to-container mappings:
- `~/dev` -> `/home/node/dev` (Persistence for worktrees)
- `~/.gemini` -> `/home/node/.gemini` (Shared credentials)
- `~/.workspace` -> `/home/node/.workspace` (Shared scripts/logs)
- **Runtime**: The container runs as a persistent service (`--restart always`) acting as a "Remote Workstation" rather than an ephemeral task.
## Orchestration Logic
- **Worker Provider Abstraction**: Infrastructure is managed via a `WorkerProvider` interface (e.g., `GceCosProvider`). This decouples the orchestration logic from the underlying platform.
- **Robust Connectivity**: The system uses a dual-path connectivity strategy:
1. **Fast-Path SSH**: Primary connection via a standard SSH alias (`gcli-worker`) for high-performance synchronization and interaction.
2. **IAP Fallback**: Automatic fallback to `gcloud compute ssh --tunnel-through-iap` for users off-VPC or when direct DNS resolution fails.
- **Context Execution**: Use `docker exec -it maintainer-worker ...` for interactive tasks and `tmux` sessions. This provides persistence against connection drops while keeping the host OS "invisible."
- **Path Resolution**: Both Host and Container must share identical tilde (`~`) paths to avoid mapping confusion in automation scripts.
## Maintenance
- **Rebuilds**: If the environment drifts or the image updates, delete the VM and re-run the `provision` action.
- **Status**: The Mission Control dashboard derives state by scanning host `tmux` sessions and container filesystem logs.
@@ -1,49 +0,0 @@
# Network Architecture & Troubleshooting Research
This document captures the empirical research and final configuration settled upon for the Gemini CLI Workspace system, specifically addressing the challenges of connecting from corporate environments to private GCP workers.
## 🔍 The Challenge
The goal was to achieve **Direct internal SSH** access to GCE workers that have **no public IP addresses**, allowing for high-performance file synchronization (`rsync`) and interactive sessions without the overhead of `gcloud` wrappers.
## 🧪 What Was Tested
### 1. Standard Internal DNS (`<instance>.<zone>.c.<project>.internal`)
- **Result**: ❌ FAILED
- **Observation**: Standard GCE internal DNS suffixes often fail to resolve or route correctly from local workstations in certain corporate environments, even when VPN/Peering is active.
### 2. IAP Tunneling (`gcloud compute ssh --tunnel-through-iap`)
- **Result**: ⚠️ INCONSISTENT
- **Observation**: While IAP is the standard fallback for private VMs, it failed with "failed to connect to backend" (4003) when the underlying VPC network lacked proper configuration or when firewall rules were misaligned with the specific network interface.
### 3. Custom "Auto" Networks
- **Result**: ❌ FAILED
- **Observation**: Creating a fresh VPC with default "auto" settings was insufficient. The "magic" corporate routing paths did not automatically extend to these new, isolated networks.
## ✅ The Final State (The "Magic" Configuration)
Through comparison with the working `gemini-cli-team-quota` project and empirical testing in a sandbox, we settled on the following requirements:
### 1. Hostname Construction
The system **MUST** use the following specific hostname pattern for direct internal reachability:
`nic0.<instance>.<zone>.c.<project>.internal.gcpnode.com`
### 2. VPC Configuration
The VPC (e.g., `iap-vpc`) must be a **Custom Mode** network with the following properties:
- **Private Google Access**: MUST be enabled on the subnetwork. This allows the private VM to communicate with Google services (like Artifact Registry) without a public IP.
- **Firewall Rule**: An ingress rule allowing `tcp:22` from `0.0.0.0/0`.
- *Note*: While `0.0.0.0/0` seems broad, in this context it is typically restricted by the corporate-level gateway/peering that provides the `internal.gcpnode.com` route.
### 3. Worker Provider Abstraction
To manage this complexity, we implemented a `WorkerProvider` architecture:
- **`BaseProvider`**: Defines a common interface for `exec`, `sync`, and `provision`.
- **`GceCosProvider`**: Encapsulates the GCE-specific "magic" (hostname construction, IAP fallbacks, COS startup scripts).
## 🛠️ Why This Works
This configuration aligns with the **Google Corporate Direct-Access** pattern. By using the `nic0` prefix and the `.gcpnode.com` suffix, the connection is routed through internal corporate proxies that recognize the authenticated developer identity and permit the direct SSH handshake to the private IP.
## 📜 Technical Metadata Summary
- **Network**: `iap-vpc` (Custom)
- **Subnet**: `iap-subnet` (Private Google Access: Enabled)
- **Identity**: OS Login (`enable-oslogin=TRUE`)
- **Image**: Container-Optimized OS (COS)
- **Connectivity**: Direct SSH via `nic0` -> Automatic Fallback to IAP.
@@ -1,60 +0,0 @@
# Mission: GCE Container-First Refactor 🚀
## Current State
- **Architecture**: Persistent GCE VM (`gcli-workspace-mattkorwel`) with Fast-Path SSH (`gcli-worker`).
- **Logic**: Decoupled scripts in `~/.workspace/scripts`, using Git Worktrees for concurrency.
- **Auth**: Scoped GitHub PATs mirrored via setup.
## The Goal (Container-OS Transition)
Shift from a "Manual VM" to an "Invisible VM" (Container-Optimized OS) that runs our Sandbox Docker image directly.
## Planned Changes
1. **Multi-Stage Dockerfile**: ✅ VERIFIED
- Optimize `.gcp/Dockerfile.maintainer` to include `tsx`, `vitest`, `gh`, and system dependencies (`libsecret`, `build-essential`).
- *Verified locally: Node v20, GH CLI, Git, TSX, and Vitest are functional with required headers.*
2. **Dedicated Pipeline**:
- Use `.gcp/maintainer-worker.yml` for isolated builds.
- **Tagging Strategy**:
- `latest`: Automatically updated on every merge to `main`.
- `branch-name`: Created on-demand for PRs via `/gcbrun` comment.
3. **Setup Script (`setup.ts`)**:
- Refactor `provision` to use `gcloud compute instances create-with-container`.
- Point to the new `maintainer` image in Artifact Registry.
4. **Orchestrator (`orchestrator.ts`)**:
- Update SSH logic to include the `--container` flag.
## GCP Console Setup (Two Triggers)
### Trigger 1: Production Maintainer Image (Automatic)
1. **Event**: Push to branch.
2. **Branch**: `^main$`.
3. **Configuration**: Point to `.gcp/maintainer-worker.yml`.
4. **Purpose**: Keeps the stable "Golden Image" up to date for daily use.
### Trigger 2: On-Demand Testing (Comment-Gated)
1. **Event**: Pull request.
2. **Base Branch**: `^main$`.
3. **Comment Control**: Set to **"Required"** (e.g. `/gcbrun`).
4. **Configuration**: Point to `.gcp/maintainer-worker.yml`.
5. **Purpose**: Allows developers to test infrastructure changes before merging.
## Phase 2: Refactoring setup.ts for Container-OS
This phase is currently **ARCHIVED** in favor of the Persistent Workstation model.
### Implementation Logic (Snapshot)
The orchestrator should launch isolated containers using this pattern:
```bash
docker run --rm -it \
--name workspace-job-id \
-v ~/dev/worktrees/job-id:/home/node/dev/worktree:rw \
-v ~/dev/main:/home/node/dev/main:ro \
-v ~/.gemini:/home/node/.gemini:ro \
-w /home/node/dev/worktree \
maintainer-image:latest \
sh -c "tsx ~/.workspace/scripts/entrypoint.ts ..."
```
## How to Resume
1. Review the archived container-launch logic above.
2. Update `setup.ts` to use `gcloud compute instances create-with-container`.
3. Update `orchestrator.ts` to use `docker run` instead of standard `ssh`.
-141
View File
@@ -1,141 +0,0 @@
# Workspace maintainer skill
The `workspace` skill provides a high-performance, parallelized workflow for
workspaceing intensive developer tasks to a remote workstation. It leverages a
Node.js orchestrator to run complex validation playbooks concurrently in a
dedicated terminal window.
## Why use workspace?
As a maintainer, you eventually reach the limits of how much work you can manage
at once on a single local machine. Heavy builds, concurrent test suites, and
multiple PRs in flight can quickly overload local resources, leading to
performance degradation and developer friction.
While manual remote management is a common workaround, it is often cumbersome
and context-heavy. The `workspace` skill addresses these challenges by
providing:
- **Elastic compute**: Workspace resource-intensive build and lint suites to a
beefy remote workstation, keeping your local machine responsive.
- **Context preservation**: The main Gemini session remains interactive and
focused on high-level reasoning while automated tasks provide real-time
feedback in a separate window.
- **Automated orchestration**: The skill handles worktree provisioning, script
synchronization, and environment isolation automatically.
- **True parallelism**: Infrastructure validation, CI checks, and behavioral
proofs run simultaneously, compressing a 15-minute process into 3 minutes.
## Agentic skills: Sync or Workspace
The `workspace` system is designed to work in synergy with specialized agentic
skills. These skills can be run **synchronously** in your current terminal for
quick tasks, or **workspaceed** to a remote session for complex, iterative
loops.
- **`review-pr`**: Conducts high-fidelity, behavioral code reviews. It assumes
the infrastructure is already validated and focuses on physical proof of
functionality.
- **`fix-pr`**: An autonomous "Fix-to-Green" loop. It iteratively addresses CI
failures, merge conflicts, and review comments until the PR is mergeable.
When you run `workspace <PR> fix`, the orchestrator provisions the remote
environment and then launches a Gemini CLI session specifically powered by the
`fix-pr` skill.
## Architecture: The Hybrid Powerhouse
The workspace system uses a **Hybrid VM + Docker** architecture designed for
maximum performance and reliability:
1. **The GCE VM (Raw Power)**: By running on high-performance Google Compute
Engine instances, we workspace heavy CPU and RAM tasks (like full project
builds and massive test suites) from your local machine, keeping your
primary workstation responsive.
2. **The Docker Container (Consistency & Resilience)**:
- **Source of Truth**: The `.gcp/Dockerfile.maintainer` defines the exact
environment. If a tool is added there, every maintainer gets it instantly.
- **Zero Drift**: Containers are immutable. Every job starts in a fresh
state, preventing the "OS rot" that typically affects persistent VMs.
- **Local-to-Remote Parity**: The same image can be run locally on your Mac
or remotely in GCP, ensuring that "it works on my machine" translates 100%
to the remote worker.
- **Safe Multi-tenancy**: Using Git Worktrees inside an isolated container
environment allows multiple jobs to run in parallel without sharing state
or polluting the host system.
## Playbooks
- **`review`** (default): Build, CI check, static analysis, and behavioral
proofs.
- **`fix`**: Iterative fixing of CI failures and review comments.
- **`ready`**: Final full validation (clean install + preflight) before merge.
- **`open`**: Provision a worktree and drop directly into a remote tmux session.
## Scenario and workflows
### Getting Started (Onboarding)
For a complete guide on setting up your remote environment, see the
[Maintainer Onboarding Guide](../../../MAINTAINER_ONBOARDING.md).
### Persistence and Job Recovery
The workspace system is designed for high reliability and persistence. Jobs use
a nested execution model to ensure they continue running even if your local
terminal is closed or the connection is lost.
### How it Works
1. **Host-Level Persistence**: The orchestrator launches each job in a named
**`tmux`** session on the remote VM.
2. **Container Isolation**: The actual work is performed inside the persistent
`maintainer-worker` Docker container.
### Re-attaching to a Job
If you lose your connection, you can easily resume your session:
- **Automatic**: Simply run the exact same command you started with (e.g.,
`workspace 123 review`). The system will automatically detect the existing
session and re-attach you.
- **Manual**: Use `workspace:status` to find the session name, then use
`ssh gcli-worker` to jump into the VM and `tmux attach -t <session>` to
resume.
## Technical details
This skill uses a **Worker Provider** abstraction (`GceCosProvider`) to manage
the remote lifecycle. It uses an isolated Gemini profile on the remote host
(`~/.workspace/gemini-cli-config`) to ensure that verification tasks do not
interfere with your primary configuration.
### Directory structure
- `scripts/providers/`: Modular worker implementations (GCE, etc.).
- `scripts/orchestrator.ts`: Local orchestrator (syncs scripts and pops
terminal).
- `scripts/worker.ts`: Remote engine (provisions worktree and runs playbooks).
- `scripts/check.ts`: Local status poller.
- `scripts/clean.ts`: Remote cleanup utility.
- `SKILL.md`: Instructional body used by the Gemini CLI agent.
## Contributing
If you want to improve this skill:
1. Modify the TypeScript scripts in `scripts/`.
2. Update `SKILL.md` if the agent's instructions need to change.
3. Test your changes locally using `workspace <PR>`.
## Testing
The orchestration logic for this skill is fully tested. To run the tests:
```bash
npx vitest .gemini/skills/workspace/tests/orchestration.test.ts
```
These tests mock the external environment (SSH, GitHub CLI, and the file system)
to ensure that the orchestration scripts generate the correct commands and
handle environment isolation accurately.
@@ -1,69 +0,0 @@
# Plan: Worker Provider Abstraction for Workspace System
## Objective
Abstract the remote execution infrastructure (GCE COS, GCE Linux, Cloud
Workstations) behind a common `WorkerProvider` interface. This eliminates
infrastructure-specific prompts (like "use container mode") and makes the system
extensible to new backends.
## Architectural Changes
### 1. New Provider Abstraction
Create a modular provider system where each infrastructure type implements a
standard interface.
- **Base Interface**: `WorkerProvider` (methods for `exec`, `sync`, `provision`,
`getStatus`).
- **Implementations**:
- `GceCosProvider`: Handles COS with Cloud-Init and `docker exec` wrapping.
- `GceLinuxProvider`: Handles standard Linux VMs with direct execution.
- `LocalDockerProvider`: (Future) Runs workspace tasks in a local container.
- `WorkstationProvider`: (Future) Integrates with Google Cloud Workstations.
### 2. Auto-Discovery
Modify `setup.ts` to:
- Prompt for a high-level "Provider Type" (e.g., "Google Cloud (COS)", "Google
Cloud (Linux)").
- Auto-detect environment details where possible (e.g., fetching internal IPs,
identifying container names).
### 3. Clean Orchestration
Refactor `orchestrator.ts` to be provider-agnostic:
- It asks the provider to "Ensure Ready" (wake VM).
- It asks the provider to "Prepare Environment" (worktree setup).
- It asks the provider to "Launch Task" (tmux initialization).
## Implementation Steps
### Phase 1: Infrastructure Cleanup
- Move existing procedural logic from `fleet.ts`, `setup.ts`, and
`orchestrator.ts` into a new `providers/` directory.
- Create `ProviderFactory` to instantiate the correct implementation based on
`settings.json`.
### Phase 2: Refactor Scripts
- **`fleet.ts`**: Proxy all actions (`provision`, `rebuild`, `stop`) to the
provider.
- **`orchestrator.ts`**: Use the provider for the entire lifecycle of a job.
- **`status.ts`**: Use the provider's `getStatus()` method to derive state.
### Phase 3: Validation
- Verify that the `gcli-worker` SSH alias and IAP tunneling remain functional.
- Ensure "Fast-Path SSH" is still the primary interactive gateway.
## Verification
- Run `workspace:fleet provision` and ensure it creates a COS-native worker.
- Run `workspace:setup` and verify it no longer asks cryptic infrastructure
questions.
- Launch a review and verify it uses `docker exec internally for the COS
provider.
@@ -1,95 +0,0 @@
/**
* Shared Task Runner Utility
* Handles parallel process execution, log streaming, and dashboard rendering.
*/
import { spawn } from 'child_process';
import path from 'path';
import fs from 'fs';
export interface Task {
id: string;
name: string;
cmd: string;
dep?: string;
condition?: 'success' | 'fail';
}
export class TaskRunner {
private state: Record<string, { status: string; exitCode?: number }> = {};
private tasks: Task[] = [];
private logDir: string;
private header: string;
constructor(logDir: string, header: string) {
this.logDir = logDir;
this.header = header;
fs.mkdirSync(logDir, { recursive: true });
}
register(tasks: Task[]) {
this.tasks = tasks;
tasks.forEach(t => this.state[t.id] = { status: 'PENDING' });
}
async run() {
const runQueue = this.tasks.filter(t => !t.dep);
runQueue.forEach(t => this.execute(t));
return new Promise((resolve) => {
const checkInterval = setInterval(() => {
const allDone = this.tasks.every(t =>
['SUCCESS', 'FAILED', 'SKIPPED'].includes(this.state[t.id].status)
);
if (allDone) {
clearInterval(checkInterval);
console.log('\n✨ All tasks complete.');
resolve(this.state);
}
// Check for dependencies
this.tasks.filter(t => t.dep && this.state[t.id].status === 'PENDING').forEach(t => {
const parent = this.state[t.dep!];
if (parent.status === 'SUCCESS' && (!t.condition || t.condition === 'success')) {
this.execute(t);
} else if (parent.status === 'FAILED' && t.condition === 'fail') {
this.execute(t);
} else if (['SUCCESS', 'FAILED'].includes(parent.status)) {
this.state[t.id].status = 'SKIPPED';
}
});
this.render();
}, 1500);
});
}
private execute(task: Task) {
this.state[task.id].status = 'RUNNING';
const proc = spawn(task.cmd, { shell: true, env: { ...process.env, FORCE_COLOR: '1' } });
const logStream = fs.createWriteStream(path.join(this.logDir, `${task.id}.log`));
proc.stdout.pipe(logStream);
proc.stderr.pipe(logStream);
proc.on('close', (code) => {
const exitCode = code ?? 0;
this.state[task.id].status = exitCode === 0 ? 'SUCCESS' : 'FAILED';
this.state[task.id].exitCode = exitCode;
fs.writeFileSync(path.join(this.logDir, `${task.id}.exit`), exitCode.toString());
});
}
private render() {
console.clear();
console.log('==================================================');
console.log(this.header);
console.log('==================================================\n');
this.tasks.forEach(t => {
const s = this.state[t.id];
const icon = s.status === 'SUCCESS' ? '✅' : s.status === 'FAILED' ? '❌' : s.status === 'RUNNING' ? '⏳' : s.status === 'SKIPPED' ? '⏭️ ' : '💤';
console.log(` ${icon} ${t.name.padEnd(20)}: ${s.status}`);
});
}
}
-93
View File
@@ -1,93 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import path from 'node:path';
import fs from 'node:fs';
import { spawnSync } from 'node:child_process';
import { ProviderFactory } from './providers/ProviderFactory.ts';
const REPO_ROOT = process.cwd();
const q = (str: string) => `'${str.replace(/'/g, "'\\''")}'`;
export async function runAttach(
args: string[],
env: NodeJS.ProcessEnv = process.env,
) {
const prNumber = args[0];
const action = args[1] || 'review';
const isLocal = args.includes('--local');
if (!prNumber) {
console.error('Usage: workspace attach <PR_NUMBER> [action] [--local]');
return 1;
}
const settingsPath = path.join(REPO_ROOT, '.gemini/workspaces/settings.json');
if (!fs.existsSync(settingsPath)) {
console.error('❌ Settings not found. Run "workspace setup" first.');
return 1;
}
const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
const config = settings.workspace;
if (!config) {
console.error('❌ Deep Review configuration not found.');
return 1;
}
const { projectId, zone } = config;
const targetVM = `gcli-workspace-${env.USER || 'mattkorwel'}`;
const provider = ProviderFactory.getProvider({
projectId,
zone,
instanceName: targetVM,
});
const sessionName = `workspace-${prNumber}-${action}`;
const containerAttach = `sudo docker exec -it maintainer-worker sh -c ${q(`tmux attach-session -t ${sessionName}`)}`;
const finalSSH = provider.getRunCommand(containerAttach, {
interactive: true,
});
console.log(`🔗 Attaching to session: ${sessionName}...`);
const isWithinGemini =
!!env.GEMINI_CLI || !!env.GEMINI_SESSION_ID || !!env.GCLI_SESSION_ID;
if (isWithinGemini && !isLocal) {
const tempCmdPath = path.join(
process.env.TMPDIR || '/tmp',
`workspace-attach-${prNumber}.sh`,
);
fs.writeFileSync(tempCmdPath, `#!/bin/bash\n${finalSSH}\nrm "$0"`, {
mode: 0o755,
});
const appleScript = `
on run argv
tell application "iTerm"
tell current window
set newTab to (create tab with default profile)
tell current session of newTab
write text (item 1 of argv) & return
end tell
end tell
activate
end tell
end run
`;
spawnSync('osascript', ['-', tempCmdPath], { input: appleScript });
console.log(`✅ iTerm2 tab opened for ${sessionName}.`);
return 0;
}
spawnSync(finalSSH, { stdio: 'inherit', shell: true });
return 0;
}
if (import.meta.url === `file://${process.argv[1]}`) {
runAttach(process.argv.slice(2)).catch(console.error);
}
-99
View File
@@ -1,99 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { spawnSync } from 'node:child_process';
import path from 'node:path';
import fs from 'node:fs';
import { ProviderFactory } from './providers/ProviderFactory.ts';
const REPO_ROOT = process.cwd();
export async function runChecker(
args: string[],
env: NodeJS.ProcessEnv = process.env,
) {
const prNumber = args[0];
if (!prNumber) {
console.error('Usage: npm run review:check <PR_NUMBER>');
return 1;
}
const settingsPath = path.join(REPO_ROOT, '.gemini/workspaces/settings.json');
if (!fs.existsSync(settingsPath)) {
console.error('❌ Settings not found. Run "workspace setup" first.');
return 1;
}
const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
const config = settings.workspace;
if (!config) {
console.error('❌ Deep Review configuration not found.');
return 1;
}
const { projectId, zone, remoteWorkDir } = config;
const targetVM = `gcli-workspace-${env.USER || 'mattkorwel'}`;
const provider = ProviderFactory.getProvider({
projectId,
zone,
instanceName: targetVM,
});
console.log(
`🔍 Checking remote status for PR #${prNumber} on ${targetVM}...`,
);
const branchView = spawnSync(
'gh',
['pr', 'view', prNumber, '--json', 'headRefName', '-q', '.headRefName'],
{ shell: true },
);
const branchName = branchView.stdout.toString().trim();
const logDir = `${remoteWorkDir}/${branchName}/.gemini/logs/review-${prNumber}`;
const tasks = ['build', 'ci', 'review', 'verify'];
let allDone = true;
console.log('\n--- Task Status ---');
for (const task of tasks) {
const exitFile = `${logDir}/${task}.exit`;
const checkExit = await provider.getExecOutput(
`[ -f ${exitFile} ] && cat ${exitFile}`,
{ wrapContainer: 'maintainer-worker' },
);
if (checkExit.status === 0 && checkExit.stdout.trim()) {
const code = checkExit.stdout.trim();
console.log(
` ${code === '0' ? '✅' : '❌'} ${task.padEnd(10)}: ${code === '0' ? 'SUCCESS' : `FAILED (exit ${code})`}`,
);
} else {
const checkRunning = await provider.exec(`[ -f ${logDir}/${task}.log ]`, {
wrapContainer: 'maintainer-worker',
});
if (checkRunning === 0) {
console.log(`${task.padEnd(10)}: RUNNING`);
} else {
console.log(` 💤 ${task.padEnd(10)}: PENDING`);
}
allDone = false;
}
}
if (allDone) {
console.log(
'\n✨ All remote tasks complete. You can now synthesize the results.',
);
} else {
console.log(
'\n⏳ Some tasks are still in progress. Check again in a few minutes.',
);
}
return 0;
}
if (import.meta.url === `file://${process.argv[1]}`) {
runChecker(process.argv.slice(2)).catch(console.error);
}
-131
View File
@@ -1,131 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import path from 'node:path';
import fs from 'node:fs';
import readline from 'node:readline';
import { ProviderFactory } from './providers/ProviderFactory.ts';
const REPO_ROOT = process.cwd();
async function confirm(question: string): Promise<boolean> {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) => {
rl.question(`${question} (y/n): `, (answer) => {
rl.close();
resolve(answer.trim().toLowerCase() === 'y');
});
});
}
export async function runCleanup(
args: string[],
env: NodeJS.ProcessEnv = process.env,
) {
const prNumber = args[0];
const action = args[1];
const settingsPath = path.join(REPO_ROOT, '.gemini/workspaces/settings.json');
if (!fs.existsSync(settingsPath)) {
console.error('❌ Settings not found. Run "workspace setup" first.');
return 1;
}
const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
const config = settings.workspace;
if (!config) {
console.error('❌ Workspace configuration not found.');
return 1;
}
const { projectId, zone } = config;
const targetVM = `gcli-workspace-${env.USER || 'mattkorwel'}`;
const provider = ProviderFactory.getProvider({
projectId,
zone,
instanceName: targetVM,
});
if (prNumber && action) {
const sessionName = `workspace-${prNumber}-${action}`;
const worktreePath = `/home/node/.workspaces/worktrees/${sessionName}`;
console.log(
`🧹 Surgically removing session and worktree for ${prNumber}-${action}...`,
);
// Kill specific tmux session inside container
await provider.exec(`tmux kill-session -t ${sessionName} 2>/dev/null`, {
wrapContainer: 'maintainer-worker',
});
// Remove specific worktree inside container
await provider.exec(
`cd /home/node/.workspaces/main && git worktree remove -f ${worktreePath} 2>/dev/null && git worktree prune`,
{ wrapContainer: 'maintainer-worker' },
);
console.log(`✅ Cleaned up ${prNumber}-${action}.`);
return 0;
}
// --- Bulk Cleanup ---
console.log(
`⚠️ DANGER: You are about to perform a BULK cleanup on ${targetVM}.`,
);
const confirmed = await confirm(
' Are you sure you want to kill ALL sessions and worktrees?',
);
if (!confirmed) {
console.log('❌ Cleanup cancelled.');
return 0;
}
console.log(`🧹 Starting BULK cleanup...`);
// 1. Standard Cleanup
console.log(' - Killing ALL remote tmux sessions...');
await provider.exec(`tmux kill-server`, {
wrapContainer: 'maintainer-worker',
});
console.log(' - Cleaning up Docker resources...');
await provider.exec(`sudo docker rm -f maintainer-worker || true`);
await provider.exec(`sudo docker system prune -af --volumes`);
console.log(' - Cleaning up ALL Git Worktrees...');
await provider.exec(
`cd /home/node/.workspaces/main && git worktree prune && rm -rf /home/node/.workspaces/worktrees/*`,
{ wrapContainer: 'maintainer-worker' },
);
console.log('✅ Remote environment cleared.');
// 2. Full Wipe Option
const shouldWipe = await confirm(
'\nWould you like to COMPLETELY wipe the remote workspace (main clone)?',
);
if (shouldWipe) {
console.log(`🔥 Wiping /home/node/.workspaces/main...`);
await provider.exec(
`rm -rf /home/node/.workspaces/main && mkdir -p /home/node/.workspaces/main`,
{ wrapContainer: 'maintainer-worker' },
);
console.log(
'✅ Remote hub wiped. You will need to run workspace setup again.',
);
}
return 0;
}
if (import.meta.url === `file://${process.argv[1]}`) {
runCleanup(process.argv.slice(2)).catch(console.error);
}
@@ -1,61 +0,0 @@
/**
* Deep Review Entrypoint (Remote)
*
* This script is the single command executed by the remote tmux session.
* It handles environment loading and sequence orchestration.
*/
import { spawnSync } from 'child_process';
import path from 'path';
import fs from 'fs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const prNumber = process.argv[2];
const branchName = process.argv[3];
const policyPath = process.argv[4];
const ISOLATED_CONFIG = process.env.GEMINI_CLI_HOME || path.join(process.env.HOME || '', '.workspaces/gemini-cli-config');
async function main() {
if (!prNumber || !branchName || !policyPath) {
console.error('Usage: tsx entrypoint.ts <PR_NUMBER> <BRANCH_NAME> <POLICY_PATH>');
process.exit(1);
}
const workDir = process.cwd(); // This is remoteWorkDir as set in review.ts
const targetDir = path.join(workDir, branchName);
// Use global tools pre-installed in the maintainer image
const tsxBin = 'tsx';
const geminiBin = 'gemini';
const action = process.argv[5] || 'review';
// 1. Run the Parallel Reviewer
console.log('🚀 Launching Parallel Review Worker...');
console.log(` - Script: ${path.join(__dirname, 'worker.ts')}`);
console.log(` - Action: ${action}`);
const workerResult = spawnSync(tsxBin, [path.join(__dirname, 'worker.ts'), prNumber, branchName, policyPath, action], {
stdio: 'inherit',
env: { ...process.env, GEMINI_CLI_HOME: ISOLATED_CONFIG }
});
if (workerResult.status !== 0) {
console.error(`❌ Worker failed with exit code ${workerResult.status}.`);
if (workerResult.error) console.error(' Error:', workerResult.error.message);
}
// 2. Launch the Interactive Gemini Session (Local Nightly)
console.log('\n✨ Verification complete. Joining interactive session...');
const geminiArgs = ['--policy', policyPath];
geminiArgs.push('-p', `Review for PR #${prNumber} is complete. Read the logs in .gemini/logs/review-${prNumber}/ and synthesize your findings.`);
process.chdir(targetDir);
spawnSync(geminiBin, geminiArgs, {
stdio: 'inherit',
env: { ...process.env, GEMINI_CLI_HOME: ISOLATED_CONFIG }
});
}
main().catch(console.error);
-144
View File
@@ -1,144 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { spawnSync } from 'node:child_process';
import path from 'node:path';
import fs from 'node:fs';
import { ProviderFactory } from './providers/ProviderFactory.ts';
const REPO_ROOT = process.cwd();
const USER = process.env.USER || 'mattkorwel';
const INSTANCE_PREFIX = `gcli-workspace-${USER}`;
const DEFAULT_ZONE = 'us-west1-a';
function getProjectId(): string {
const settingsPath = path.join(REPO_ROOT, '.gemini/workspaces/settings.json');
if (fs.existsSync(settingsPath)) {
try {
const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
return settings.workspace?.projectId;
} catch {
// Ignore
}
}
return process.env.GOOGLE_CLOUD_PROJECT || '';
}
async function listWorkers() {
const projectId = getProjectId();
if (!projectId) {
console.error('❌ Project ID not found. Run "workspace setup" first.');
return;
}
console.log(`🔍 Listing Workspace Workers for ${USER} in ${projectId}...`);
spawnSync(
'gcloud',
[
'compute',
'instances',
'list',
'--project',
projectId,
'--filter',
`name~^${INSTANCE_PREFIX}`,
'--format',
'table(name,zone,status,networkInterfaces[0].networkIP:label=INTERNAL_IP,creationTimestamp)',
],
{ stdio: 'inherit' },
);
}
async function provisionWorker() {
const projectId = getProjectId();
if (!projectId) {
console.error('❌ Project ID not found. Run "workspace setup" first.');
return;
}
const provider = ProviderFactory.getProvider({
projectId: projectId,
zone: DEFAULT_ZONE,
instanceName: INSTANCE_PREFIX,
});
const status = await provider.getStatus();
if (status.status !== 'UNKNOWN' && status.status !== 'ERROR') {
console.log(
`✅ Worker ${INSTANCE_PREFIX} already exists and is ${status.status}.`,
);
return;
}
await provider.provision();
}
async function stopWorker() {
const projectId = getProjectId();
const provider = ProviderFactory.getProvider({
projectId: projectId,
zone: DEFAULT_ZONE,
instanceName: INSTANCE_PREFIX,
});
console.log(`🛑 Stopping workspace worker: ${INSTANCE_PREFIX}...`);
await provider.stop();
}
async function rebuildWorker() {
const projectId = getProjectId();
console.log(`🔥 Rebuilding worker ${INSTANCE_PREFIX}...`);
const knownHostsPath = path.join(REPO_ROOT, '.gemini/workspaces_known_hosts');
if (fs.existsSync(knownHostsPath)) {
console.log(` - Clearing isolated known_hosts...`);
fs.unlinkSync(knownHostsPath);
}
spawnSync(
'gcloud',
[
'compute',
'instances',
'delete',
INSTANCE_PREFIX,
'--project',
projectId,
'--zone',
DEFAULT_ZONE,
'--quiet',
],
{ stdio: 'inherit' },
);
await provisionWorker();
}
async function main() {
const action = process.argv[2] || 'list';
switch (action) {
case 'list':
await listWorkers();
break;
case 'provision':
await provisionWorker();
break;
case 'rebuild':
await rebuildWorker();
break;
case 'stop':
await stopWorker();
break;
default:
console.error(`❌ Unknown fleet action: ${action}`);
process.exit(1);
}
}
main().catch(console.error);
-54
View File
@@ -1,54 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { spawnSync } from 'node:child_process';
import path from 'node:path';
import fs from 'node:fs';
const REPO_ROOT = process.cwd();
export async function runLogs(args: string[]) {
const prNumber = args[0];
const action = args[1] || 'review';
if (!prNumber) {
console.error('Usage: workspace logs <PR_NUMBER> [action]');
return 1;
}
const settingsPath = path.join(REPO_ROOT, '.gemini/settings.json');
const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
const config = settings.maintainer?.workspace;
const { remoteHost, remoteHome } = config;
const sshConfigPath = path.join(REPO_ROOT, '.gemini/workspace_ssh_config');
const jobDir = `${remoteHome}/dev/worktrees/workspace-${prNumber}-${action}`;
const logDir = `${jobDir}/.gemini/logs`;
console.log(`📋 Tailing latest logs for job ${prNumber}-${action}...`);
// Remote command to find the latest log file and tail it
const tailCmd = `
latest_log=$(ls -t ${logDir}/*.log 2>/dev/null | head -n 1)
if [ -z "$latest_log" ]; then
echo "❌ No logs found for this job yet."
exit 1
fi
echo "📄 Tailing: $latest_log"
tail -f "$latest_log"
`;
spawnSync(
`ssh -F ${sshConfigPath} ${remoteHost} ${JSON.stringify(tailCmd)}`,
{ stdio: 'inherit', shell: true },
);
return 0;
}
if (import.meta.url === `file://${process.argv[1]}`) {
runLogs(process.argv.slice(2)).catch(console.error);
}
@@ -1,238 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { spawnSync } from 'node:child_process';
import path from 'node:path';
import fs from 'node:fs';
import { ProviderFactory } from './providers/ProviderFactory.ts';
const REPO_ROOT = process.cwd();
function q(str: string) {
return `'${str.replace(/'/g, "'\\''")}'`;
}
export async function runOrchestrator(
args: string[],
env: NodeJS.ProcessEnv = process.env,
) {
let prNumber = args[0];
let action = args[1] || 'review';
// Handle "shell" mode: workspace shell [identifier]
const isShellMode = prNumber === 'shell';
if (isShellMode) {
prNumber = args[1] || `adhoc-${Math.floor(Math.random() * 10000)}`;
action = 'shell';
}
if (!prNumber) {
console.error(
'❌ Usage: workspace <PR_NUMBER> [action] OR workspace shell [identifier]',
);
return 1;
}
// 1. Load Settings
const settingsPath = path.join(REPO_ROOT, '.gemini/workspaces/settings.json');
if (!fs.existsSync(settingsPath)) {
console.error(
'❌ Workspace settings not found. Run "workspace setup" first.',
);
return 1;
}
const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
const config = settings.workspace;
const targetVM = `gcli-workspace-${env.USER || 'mattkorwel'}`;
const provider = ProviderFactory.getProvider({
projectId: config.projectId,
zone: config.zone,
instanceName: targetVM,
});
// 2. Wake Worker & Verify Container
await provider.ensureReady();
// Retrieve the remote user to ensure we run git commands correctly
await provider.getExecOutput('whoami');
// Paths - Unified across host and container
const hostWorkspaceRoot = `/home/node/.workspaces`;
const hostWorkDir = `${hostWorkspaceRoot}/main`;
const containerWorkspaceRoot = `/home/node/.workspaces`;
const remotePolicyPath = `${containerWorkspaceRoot}/policies/workspace-policy.toml`;
const persistentScripts = `${containerWorkspaceRoot}/scripts`;
const sessionName = `workspace-${prNumber}-${action}`;
const remoteWorktreeDir = `${containerWorkspaceRoot}/worktrees/${sessionName}`;
const hostWorktreeDir = `${hostWorkspaceRoot}/worktrees/${sessionName}`;
// 3. Remote Context Setup (Executed on HOST for permission simplicity)
console.log(
`🚀 Preparing remote environment for ${action} on ${isShellMode ? 'branch/id' : '#'}${prNumber}...`,
);
// FIX: Use the host path to check for existence
const check = await provider.getExecOutput(`ls -d ${hostWorktreeDir}/.git`);
// FIX: Ensure container user (node) owns the workspaces directories
console.log(' - Synchronizing container permissions...');
await provider.exec(`sudo chown -R 1000:1000 /home/node/.workspaces`);
if (check.status !== 0) {
console.log(` - Provisioning isolated git worktree for ${prNumber}...`);
// We run these on the host. Since setup might have left the repo root-owned, we use sudo.
// We use environment variables to bypass safe.directory checks on a read-only filesystem.
const gitEnv = `GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=safe.directory GIT_CONFIG_VALUE_0=${hostWorkDir}`;
const gitFetch = isShellMode
? `sudo ${gitEnv} git -C ${hostWorkDir} fetch --quiet origin`
: `sudo ${gitEnv} git -C ${hostWorkDir} fetch --quiet upstream pull/${prNumber}/head`;
const gitTarget = isShellMode ? 'FETCH_HEAD' : 'FETCH_HEAD';
const setupCmd = `
sudo mkdir -p ${hostWorkspaceRoot}/worktrees && \
sudo chown chronos:chronos ${hostWorkspaceRoot}/worktrees && \
${gitFetch} && \
sudo ${gitEnv} git -C ${hostWorkDir} worktree add --quiet -f ${hostWorktreeDir} ${gitTarget} 2>&1 && \
sudo chown -R 1000:1000 ${hostWorkspaceRoot}
`;
const setupRes = await provider.getExecOutput(setupCmd);
if (setupRes.status !== 0) {
console.error(' ❌ Failed to provision remote worktree.');
console.error(' STDOUT:', setupRes.stdout);
console.error(' STDERR:', setupRes.stderr);
return 1;
}
console.log(' ✅ Worktree provisioned successfully.');
} else {
console.log(' ✅ Remote worktree ready.');
}
// AUTH: Dynamically retrieve credentials from host-side config/disk
const remoteConfigPath = `${hostWorkspaceRoot}/gemini-cli-config/.gemini/settings.json`;
const remoteSettingsRes = await provider.getExecOutput(
`cat ${remoteConfigPath}`,
);
const remoteSettingsJson = remoteSettingsRes.stdout.trim();
const apiKeyRes = await provider.getExecOutput(
`cat ${remoteConfigPath} | grep apiKey | cut -d '"' -f 4`,
);
const remoteApiKey = apiKeyRes.stdout.trim();
const ghTokenRes = await provider.getExecOutput(
`cat ${hostWorkspaceRoot}/.gh_token`,
);
const remoteGhToken = ghTokenRes.stdout.trim();
// AUTH: Inject credentials and settings directly into the worktree
console.log(' - Injecting remote authentication and UI context...');
const dotEnvContent = `
GEMINI_API_KEY=${remoteApiKey}
COLORTERM=truecolor
TERM=xterm-256color
GEMINI_AUTO_UPDATE=0
GEMINI_SANDBOX=workspace
GEMINI_HOST=${targetVM}
`.trim();
await provider.exec(
`sudo docker exec maintainer-worker sh -c ${q(`echo ${q(dotEnvContent)} > ${remoteWorktreeDir}/.env`)}`,
);
// Also inject the settings.json into the worktree's .gemini folder for maximum reliability
await provider.exec(
`sudo docker exec maintainer-worker sh -c ${q(`mkdir -p ${remoteWorktreeDir}/.gemini && echo ${q(remoteSettingsJson)} > ${remoteWorktreeDir}/.gemini/settings.json`)}`,
);
// 4. Execution Logic
// In shell mode, we just start gemini. In action mode, we run the entrypoint.
const remoteWorker = isShellMode
? `gemini`
: `tsx ${persistentScripts}/entrypoint.ts ${prNumber} . ${remotePolicyPath} ${action}`;
const authEnv = `-e GEMINI_AUTO_UPDATE=0 ${remoteApiKey ? `-e GEMINI_API_KEY=${remoteApiKey} ` : ''}${remoteGhToken ? `-e GITHUB_TOKEN=${remoteGhToken} -e GH_TOKEN=${remoteGhToken} ` : ''}`;
// PERSISTENCE: Wrap the entire execution in a tmux session inside the container
// We HIDE the tmux status bar to reduce visual noise
const tmuxStyle = `
tmux set -g status off;
`.replace(/\n/g, '');
const tmuxCmd = `tmux new-session -A -s ${sessionName} ${q(`${tmuxStyle} cd ${remoteWorktreeDir} && ${remoteWorker}; exec $SHELL`)}`;
const containerWrap = `sudo docker exec -it -e COLORTERM=truecolor -e TERM=xterm-256color ${authEnv}maintainer-worker sh -c ${q(tmuxCmd)}`;
const finalSSH = provider.getRunCommand(containerWrap, { interactive: true });
const isWithinGemini =
!!env.GEMINI_CLI || !!env.GEMINI_SESSION_ID || !!env.GCLI_SESSION_ID;
// 1.5 Handle --open override
const openIdx = args.indexOf('--open');
let terminalTarget = config.terminalTarget || 'tab';
if (openIdx !== -1 && args[openIdx + 1]) {
terminalTarget = args[openIdx + 1];
}
const forceMainTerminal = terminalTarget === 'foreground';
if (
!forceMainTerminal &&
isWithinGemini &&
env.TERM_PROGRAM === 'iTerm.app'
) {
const tempCmdPath = path.join(
process.env.TMPDIR || '/tmp',
`workspace-ssh-${prNumber}.sh`,
);
fs.writeFileSync(tempCmdPath, `#!/bin/bash\n${finalSSH}\nrm "$0"`, {
mode: 0o755,
});
const appleScript =
terminalTarget === 'window'
? `
on run argv
tell application "iTerm"
set newWindow to (create window with default profile)
tell current session of newWindow
write text (quoted form of item 1 of argv) & return
end tell
activate
end tell
end run
`
: `
on run argv
tell application "iTerm"
tell current window
set newTab to (create tab with default profile)
tell current session of newTab
write text (quoted form of item 1 of argv) & return
end tell
end tell
activate
end tell
end run
`;
spawnSync('osascript', ['-', tempCmdPath], { input: appleScript });
console.log(`✅ iTerm2 ${terminalTarget} opened for job ${prNumber}.`);
return 0;
}
// Fallback: Run in current terminal
console.log(`📡 Connecting to session ${sessionName}...`);
spawnSync(finalSSH, { stdio: 'inherit', shell: true });
return 0;
}
if (import.meta.url === `file://${process.argv[1]}`) {
runOrchestrator(process.argv.slice(2)).catch(console.error);
}
@@ -1,18 +0,0 @@
import { spawnSync } from 'child_process';
import path from 'path';
export async function runFixPlaybook(prNumber: string, targetDir: string, policyPath: string, geminiBin: string) {
console.log(`🚀 Workspace | FIX | PR #${prNumber}`);
console.log('Switching to agentic fix loop inside Gemini CLI...');
// Use the nightly gemini binary to activate the fix-pr skill and iterate
// Note: Gemini doesn't support --cwd, so the caller (worker.ts) must ensure we are already in targetDir
const result = spawnSync(geminiBin, [
'--policy', policyPath,
'-p', `Please activate the 'fix-pr' skill and use it to iteratively fix PR #${prNumber}.
Ensure you handle CI failures, merge conflicts, and unaddressed review comments
until the PR is fully passing and mergeable.`
], { stdio: 'inherit' });
return result?.status ?? 1;
}
@@ -1,74 +0,0 @@
import { TaskRunner } from '../TaskRunner.js';
import path from 'path';
import { spawnSync } from 'child_process';
import { TaskRunner } from '../TaskRunner.js';
import path from 'path';
import { spawnSync } from 'child_process';
import fs from 'fs';
export async function runImplementPlaybook(issueNumber: string, workDir: string, policyPath: string, geminiBin: string) {
console.log(`🚀 Workspace | IMPLEMENT (Supervisor Loop) | Issue #${issueNumber}`);
const ghView = spawnSync('gh', ['issue', 'view', issueNumber, '--json', 'title,body', '-q', '{title:.title,body:.body}'], { shell: true });
const meta = JSON.parse(ghView.stdout.toString());
const branchName = `impl/${issueNumber}-${meta.title.toLowerCase().replace(/[^a-z0-9]/g, '-')}`.slice(0, 50);
// 1. Initial Research & Test Creation
console.log('\n🧠 Phase 1: Research & Reproduction...');
spawnSync(geminiBin, [
'--policy', policyPath, '--cwd', workDir,
'-p', `Research Issue #${issueNumber}: "${meta.title}".
Description: ${meta.body}.
ACTION: Create a NEW Vitest test file in 'tests/repro_issue_${issueNumber}.test.ts' that demonstrates the issue or feature.
Ensure this test fails currently.`
], { stdio: 'inherit' });
// 2. The Self-Healing Loop
let attempts = 0;
const maxAttempts = 5;
let success = false;
console.log('\n🛠️ Phase 2: Implementation Loop...');
while (attempts < maxAttempts && !success) {
attempts++;
console.log(`\n👉 Attempt ${attempts}/${maxAttempts}...`);
// Run the specific repro test
const testRun = spawnSync('npx', ['vitest', 'run', `tests/repro_issue_${issueNumber}.test.ts`], { cwd: workDir });
if (testRun.status === 0) {
console.log('✅ Reproduction test PASSED!');
success = true;
break;
}
console.log('❌ Test failed. Asking Gemini to fix the implementation...');
const testError = testRun.stdout.toString() + testRun.stderr.toString();
spawnSync(geminiBin, [
'--policy', policyPath, '--cwd', workDir,
'-p', `The reproduction test for Issue #${issueNumber} is still failing.
ERROR OUTPUT:
${testError.slice(-2000)}
ACTION: Modify the source code to fix this error and make the test pass.
Do not modify the test itself unless it has a syntax error.`
], { stdio: 'inherit' });
}
// 3. Final Verification
if (success) {
console.log('\n🧪 Phase 3: Final Verification...');
const finalCheck = spawnSync('npm', ['test'], { cwd: workDir, stdio: 'inherit' });
if (finalCheck.status === 0) {
console.log('\n🎉 Implementation complete and verified!');
spawnSync('git', ['add', '.'], { cwd: workDir });
spawnSync('git', ['commit', '-m', `feat: implement issue #${issueNumber}`], { cwd: workDir });
return 0;
}
}
console.error('\n❌ Supervisor: Failed to reach a passing state within retry limit.');
return 1;
}
@@ -1,17 +0,0 @@
import { TaskRunner } from '../TaskRunner.ts';
import path from 'path';
export async function runReadyPlaybook(prNumber: string, targetDir: string, policyPath: string, geminiBin: string) {
const runner = new TaskRunner(
path.join(targetDir, `.gemini/logs/workspace-${prNumber}`),
`🚀 Workspace | READY | PR #${prNumber}`
);
runner.register([
{ id: 'clean', name: 'Clean Workspace', cmd: `npm run clean && npm ci` },
{ id: 'preflight', name: 'Full Preflight', cmd: `npm run preflight`, dep: 'clean' },
{ id: 'conflicts', name: 'Main Conflict Check', cmd: `git fetch origin main && git merge-base --is-ancestor origin/main HEAD` }
]);
return runner.run();
}
@@ -1,17 +0,0 @@
import { TaskRunner } from '../TaskRunner.ts';
import path from 'path';
export async function runReviewPlaybook(prNumber: string, targetDir: string, policyPath: string, geminiBin: string) {
const runner = new TaskRunner(
path.join(targetDir, `.gemini/logs/workspace-${prNumber}`),
`🚀 Workspace | REVIEW | PR #${prNumber}`
);
runner.register([
{ id: 'build', name: 'Fast Build', cmd: `cd ${targetDir} && npm ci && npm run build` },
{ id: 'ci', name: 'CI Checks', cmd: `gh pr checks ${prNumber}` },
{ id: 'review', name: 'Workspaceed Review', cmd: `cd ${targetDir} && ${geminiBin} --policy ${policyPath} -p "Please activate the 'review-pr' skill and use it to conduct a behavioral review of PR #${prNumber}."` }
]);
return runner.run();
}
@@ -1,89 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* WorkerProvider interface defines the contract for different remote
* execution environments (GCE, Workstations, etc.).
*/
export interface WorkerProvider {
/**
* Provisions the underlying infrastructure.
*/
provision(): Promise<number>;
/**
* Ensures the workspace is running and accessible.
*/
ensureReady(): Promise<number>;
/**
* Performs the initial setup of the workspace (SSH, scripts, auth).
*/
setup(options: SetupOptions): Promise<number>;
/**
* Returns the raw command string that would be used to execute a command.
*/
getRunCommand(command: string, options?: ExecOptions): string;
/**
* Executes a command on the workspace.
*/
exec(command: string, options?: ExecOptions): Promise<number>;
/**
* Executes a command on the workspace and returns the output.
*/
getExecOutput(
command: string,
options?: ExecOptions,
): Promise<{ status: number; stdout: string; stderr: string }>;
/**
* Synchronizes local files to the workspace.
*/
sync(
localPath: string,
remotePath: string,
options?: SyncOptions,
): Promise<number>;
/**
* Returns the status of the workspace.
*/
getStatus(): Promise<WorkspaceStatus>;
/**
* Stops the workspace to save costs.
*/
stop(): Promise<number>;
}
export interface SetupOptions {
projectId: string;
zone: string;
dnsSuffix?: string;
syncAuth?: boolean;
}
export interface ExecOptions {
interactive?: boolean;
cwd?: string;
wrapContainer?: string;
}
export interface SyncOptions {
delete?: boolean;
exclude?: string[];
sudo?: boolean;
}
export interface WorkspaceStatus {
name: string;
status: string;
internalIp?: string;
externalIp?: string;
}
@@ -1,83 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { spawnSync } from 'child_process';
import os from 'os';
/**
* Centralized SSH/RSYNC management for GCE Workers.
* Handles Magic Hostname routing with Zero-Knowledge security.
* STRICTLY uses Direct Internal connection (Corporate Magic).
*/
export class GceConnectionManager {
private projectId: string;
private zone: string;
private instanceName: string;
constructor(projectId: string, zone: string, instanceName: string) {
this.projectId = projectId;
this.zone = zone;
this.instanceName = instanceName;
}
getMagicRemote(): string {
const user = `${process.env.USER || 'node'}_google_com`;
const dnsSuffix = '.internal.gcpnode.com';
return `${user}@nic0.${this.instanceName}.${this.zone}.c.${this.projectId}${dnsSuffix}`;
}
getCommonArgs(): string[] {
return [
'-o', 'StrictHostKeyChecking=no',
'-o', 'UserKnownHostsFile=/dev/null',
'-o', 'LogLevel=ERROR',
'-o', 'ConnectTimeout=60',
'-o', 'ServerAliveInterval=30',
'-o', 'ServerAliveCountMax=3',
'-o', 'SendEnv=USER',
'-i', `${os.homedir()}/.ssh/google_compute_engine`
];
}
getRunCommand(command: string, options: { interactive?: boolean } = {}): string {
const fullRemote = this.getMagicRemote();
return `ssh ${this.getCommonArgs().join(' ')} ${options.interactive ? '-t' : ''} ${fullRemote} ${this.quote(command)}`;
}
run(command: string, options: { interactive?: boolean; stdio?: 'pipe' | 'inherit' } = {}): { status: number; stdout: string; stderr: string } {
const sshCmd = this.getRunCommand(command, options);
const res = spawnSync(sshCmd, { stdio: options.stdio || 'pipe', shell: true });
return {
status: res.status ?? 1,
stdout: res.stdout?.toString() || '',
stderr: res.stderr?.toString() || ''
};
}
sync(localPath: string, remotePath: string, options: { delete?: boolean; exclude?: string[]; sudo?: boolean } = {}): number {
const fullRemote = this.getMagicRemote();
// We use --no-t and --no-perms to avoid "Operation not permitted" errors
// when syncing to volumes that might have UID mismatches with the container.
const rsyncArgs = ['-rvz', '--quiet', '--no-t', '--no-perms', '--no-owner', '--no-group'];
if (options.delete) rsyncArgs.push('--delete');
if (options.exclude) options.exclude.forEach(ex => rsyncArgs.push(`--exclude="${ex}"`));
// Use sudo on the remote side if requested to bypass permission errors
if (options.sudo) {
rsyncArgs.push('--rsync-path="sudo rsync"');
}
const sshCmd = `ssh ${this.getCommonArgs().join(' ')}`;
const directRsync = `rsync ${rsyncArgs.join(' ')} -e ${this.quote(sshCmd)} ${localPath} ${fullRemote}:${remotePath}`;
const res = spawnSync(directRsync, { stdio: 'inherit', shell: true });
return res.status ?? 1;
}
private quote(str: string) {
return `'${str.replace(/'/g, "'\\''")}'`;
}
}
@@ -1,490 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { spawnSync } from 'node:child_process';
import path from 'node:path';
import fs from 'node:fs';
import os from 'node:os';
import {
type WorkerProvider,
type SetupOptions,
type ExecOptions,
type SyncOptions,
type WorkspaceStatus,
} from './BaseProvider.ts';
import { GceConnectionManager } from './GceConnectionManager.ts';
export class GceCosProvider implements WorkerProvider {
private projectId: string;
private zone: string;
private instanceName: string;
private sshConfigPath: string;
private knownHostsPath: string;
private sshAlias = 'gcli-worker';
private conn: GceConnectionManager;
constructor(
projectId: string,
zone: string,
instanceName: string,
repoRoot: string,
) {
this.projectId = projectId;
this.zone = zone;
this.instanceName = instanceName;
const workspacesDir = path.join(repoRoot, '.gemini/workspaces');
if (!fs.existsSync(workspacesDir))
fs.mkdirSync(workspacesDir, { recursive: true });
this.sshConfigPath = path.join(workspacesDir, 'ssh_config');
this.knownHostsPath = path.join(workspacesDir, 'known_hosts');
this.conn = new GceConnectionManager(projectId, zone, instanceName);
}
async provision(): Promise<number> {
const imageUri =
'us-docker.pkg.dev/gemini-code-dev/gemini-cli/maintainer:latest';
const region = this.zone.split('-').slice(0, 2).join('-');
const vpcName = 'iap-vpc';
const subnetName = 'iap-subnet';
console.log(
`🏗️ Ensuring "Magic" Network Infrastructure in ${this.projectId}...`,
);
const vpcCheck = spawnSync(
'gcloud',
['compute', 'networks', 'describe', vpcName, '--project', this.projectId],
{ stdio: 'pipe' },
);
if (vpcCheck.status !== 0) {
spawnSync(
'gcloud',
[
'compute',
'networks',
'create',
vpcName,
'--project',
this.projectId,
'--subnet-mode=custom',
],
{ stdio: 'inherit' },
);
}
const subnetCheck = spawnSync(
'gcloud',
[
'compute',
'networks',
'subnets',
'describe',
subnetName,
'--project',
this.projectId,
'--region',
region,
],
{ stdio: 'pipe' },
);
if (subnetCheck.status !== 0) {
spawnSync(
'gcloud',
[
'compute',
'networks',
'subnets',
'create',
subnetName,
'--project',
this.projectId,
'--network',
vpcName,
'--region',
region,
'--range=10.0.0.0/24',
'--enable-private-ip-google-access',
],
{ stdio: 'inherit' },
);
} else {
spawnSync(
'gcloud',
[
'compute',
'networks',
'subnets',
'update',
subnetName,
'--project',
this.projectId,
'--region',
region,
'--enable-private-ip-google-access',
],
{ stdio: 'pipe' },
);
}
const fwCheck = spawnSync(
'gcloud',
[
'compute',
'firewall-rules',
'describe',
'allow-corporate-ssh',
'--project',
this.projectId,
],
{ stdio: 'pipe' },
);
if (fwCheck.status !== 0) {
spawnSync(
'gcloud',
[
'compute',
'firewall-rules',
'create',
'allow-corporate-ssh',
'--project',
this.projectId,
'--network',
vpcName,
'--allow=tcp:22',
'--source-ranges=0.0.0.0/0',
],
{ stdio: 'inherit' },
);
}
console.log(
`🚀 Provisioning GCE COS worker: ${this.instanceName} (Unified Workspace Setup)...`,
);
const startupScriptContent = `#!/bin/bash
set -e
echo "🚀 Initializing Unified Workspace..."
# 1. Mount Data Disk
mkdir -p /mnt/disks/data
if ! mountpoint -q /mnt/disks/data; then
DATA_DISK="/dev/disk/by-id/google-data"
[ -e "$DATA_DISK" ] || DATA_DISK="/dev/sdb"
while [ ! -e "$DATA_DISK" ]; do echo "Waiting for data disk..."; sleep 1; done
blkid "$DATA_DISK" || mkfs.ext4 -m 0 -F "$DATA_DISK"
mount -o discard,defaults "$DATA_DISK" /mnt/disks/data
fi
# 2. Prepare Stateful Directories (on the persistent disk)
mkdir -p /mnt/disks/data/main /mnt/disks/data/worktrees /mnt/disks/data/scripts /mnt/disks/data/config /mnt/disks/data/policies
chmod -R 777 /mnt/disks/data
# 3. Handle Unified Path Symlink (/home/node/.workspaces)
# This ensures absolute paths match perfectly between host and container.
mkdir -p /home/node
ln -sfn /mnt/disks/data /home/node/.workspaces
chown -R 1000:1000 /home/node
# Also ensure host users can find it
ln -sfn /mnt/disks/data /workspaces
chmod 777 /workspaces
for h in /home/*_google_com; do
[ -d "$h" ] || continue
ln -sfn /mnt/disks/data "$h/.workspaces"
chown -h $(basename $h):$(basename $h) "$h/.workspaces"
done
# 4. Container Resilience Loop
until docker info >/dev/null 2>&1; do echo "Waiting for docker..."; sleep 2; done
for i in {1..5}; do
docker pull ${imageUri} && break || (echo "Pull failed, retry $i..." && sleep 5)
done
if ! docker ps -a | grep -q "maintainer-worker"; then
docker run -d --name maintainer-worker --restart always \\
-v /mnt/disks/data:/home/node/.workspaces:rw \\
-v /mnt/disks/data/gemini-cli-config/.gemini:/home/node/.gemini:rw \\
-v ~/.config/gh:/home/node/.config/gh:rw \\
${imageUri} /bin/bash -c "while true; do sleep 1000; done"
fi
echo "✅ Unified Workspace is active."
`;
const tmpScriptPath = path.join(
os.tmpdir(),
`gcli-startup-${Date.now()}.sh`,
);
fs.writeFileSync(tmpScriptPath, startupScriptContent);
const result = spawnSync(
'gcloud',
[
'compute',
'instances',
'create',
this.instanceName,
'--project',
this.projectId,
'--zone',
this.zone,
'--machine-type',
'n2-standard-8',
'--image-family',
'cos-stable',
'--image-project',
'cos-cloud',
'--boot-disk-size',
'10GB',
'--boot-disk-type',
'pd-balanced',
'--create-disk',
`name=${this.instanceName}-data,size=200,type=pd-balanced,device-name=data,auto-delete=yes`,
'--metadata-from-file',
`startup-script=${tmpScriptPath}`,
'--metadata',
'enable-oslogin=TRUE',
'--network-interface',
`network=${vpcName},subnet=${subnetName},no-address`,
'--scopes',
'https://www.googleapis.com/auth/cloud-platform',
'--quiet',
],
{ stdio: 'inherit' },
);
fs.unlinkSync(tmpScriptPath);
if (result.status === 0) {
console.log(
'⏳ Waiting for OS Login and SSH to initialize (this takes ~45s)...',
);
await new Promise((r) => setTimeout(r, 45000));
}
return result.status ?? 1;
}
async ensureReady(): Promise<number> {
const status = await this.getStatus();
if (status.status !== 'RUNNING') {
console.log(
`⚠️ Worker ${this.instanceName} is ${status.status}. Waking it up...`,
);
const res = spawnSync(
'gcloud',
[
'compute',
'instances',
'start',
this.instanceName,
'--project',
this.projectId,
'--zone',
this.zone,
],
{ stdio: 'inherit' },
);
if (res.status !== 0) return res.status ?? 1;
console.log('⏳ Waiting for boot...');
await new Promise((r) => setTimeout(r, 20000));
}
// NEW: Verify the container is actually running AND up to date
console.log(' - Verifying remote container health and image version...');
const containerCheck = await this.getExecOutput(
'sudo docker ps -q --filter "name=maintainer-worker"',
);
let needsUpdate = false;
if (containerCheck.status === 0 && containerCheck.stdout.trim()) {
// Check if the volume mounts are correct by checking for files inside .workspaces/main
const mountCheck = await this.getExecOutput(
'sudo docker exec maintainer-worker ls -A /home/node/.workspaces/main',
);
if (mountCheck.status !== 0 || !mountCheck.stdout.trim()) {
console.log(
' ⚠️ Remote container has incorrect or empty mounts. Triggering refresh...',
);
needsUpdate = true;
} else {
// Check if the running image is stale
const tmuxCheck = await this.getExecOutput(
'sudo docker exec maintainer-worker which tmux',
);
if (tmuxCheck.status !== 0) {
console.log(
' ⚠️ Remote container is stale (missing tmux). Triggering update...',
);
needsUpdate = true;
}
}
} else {
needsUpdate = true;
}
if (needsUpdate) {
console.log(' ⚠️ Container missing or stale. Attempting refresh...');
const imageUri =
'us-docker.pkg.dev/gemini-code-dev/gemini-cli/maintainer:latest';
// Ensure data mount is available before running
const recoverCmd = `
(mountpoint -q /mnt/disks/data || sudo mount /dev/disk/by-id/google-data /mnt/disks/data) && \
sudo docker pull ${imageUri} && \
(sudo docker rm -f maintainer-worker || true) && \
sudo docker run -d --name maintainer-worker --restart always \
-v /mnt/disks/data:/home/node/.workspaces:rw \
-v /mnt/disks/data/gemini-cli-config/.gemini:/home/node/.gemini:rw \
-v ~/.config/gh:/home/node/.config/gh:rw \
${imageUri} /bin/bash -c "while true; do sleep 1000; done"
`;
const recoverRes = await this.exec(recoverCmd);
if (recoverRes !== 0) {
console.error(
' ❌ Critical: Failed to refresh maintainer container.',
);
return 1;
}
console.log(' ✅ Container refreshed.');
}
return 0;
}
async setup(options: SetupOptions): Promise<number> {
const dnsSuffix = options.dnsSuffix || '.internal.gcpnode.com';
const internalHostname = `nic0.${this.instanceName}.${this.zone}.c.${this.projectId}${dnsSuffix.startsWith('.') ? dnsSuffix : '.' + dnsSuffix}`;
const user = `${process.env.USER || 'node'}_google_com`;
const sshEntry = `
Host ${this.sshAlias}
HostName ${internalHostname}
IdentityFile ~/.ssh/google_compute_engine
User ${user}
UserKnownHostsFile /dev/null
CheckHostIP no
StrictHostKeyChecking no
ConnectTimeout 60
ServerAliveInterval 30
`;
fs.writeFileSync(this.sshConfigPath, sshEntry);
console.log(` ✅ Created project SSH config: ${this.sshConfigPath}`);
console.log(
' - Verifying direct connection (may trigger corporate SSO prompt)...',
);
const res = this.conn.run('echo 1');
if (res.status !== 0) {
console.error(
'\n❌ All connection attempts failed. Please ensure you have "gcert" and IAP permissions.',
);
return 1;
}
console.log(
' ✅ Connection verified. Waiting 10s for remote disk initialization...',
);
await new Promise((r) => setTimeout(r, 10000));
return 0;
}
getRunCommand(command: string, options: ExecOptions = {}): string {
let finalCmd = command;
if (options.wrapContainer) {
finalCmd = `sudo docker exec ${options.interactive ? '-it' : ''} ${options.cwd ? `-w ${options.cwd}` : ''} ${options.wrapContainer} sh -c ${this.quote(command)}`;
}
return this.conn.getRunCommand(finalCmd, {
interactive: options.interactive,
});
}
async exec(command: string, options: ExecOptions = {}): Promise<number> {
const res = await this.getExecOutput(command, options);
return res.status;
}
async getExecOutput(
command: string,
options: ExecOptions = {},
): Promise<{ status: number; stdout: string; stderr: string }> {
let finalCmd = command;
if (options.wrapContainer) {
finalCmd = `sudo docker exec ${options.interactive ? '-it' : ''} ${options.cwd ? `-w ${options.cwd}` : ''} ${options.wrapContainer} sh -c ${this.quote(command)}`;
}
return this.conn.run(finalCmd, {
interactive: options.interactive,
stdio: options.interactive ? 'inherit' : 'pipe',
});
}
async sync(
localPath: string,
remotePath: string,
options: SyncOptions = {},
): Promise<number> {
console.log(`📦 Syncing ${localPath} to remote:${remotePath}...`);
return this.conn.sync(localPath, remotePath, options);
}
async getStatus(): Promise<WorkspaceStatus> {
const res = spawnSync(
'gcloud',
[
'compute',
'instances',
'describe',
this.instanceName,
'--project',
this.projectId,
'--zone',
this.zone,
'--format',
'json(name,status,networkInterfaces[0].networkIP)',
],
{ stdio: 'pipe' },
);
if (res.status !== 0) {
return { name: this.instanceName, status: 'UNKNOWN' };
}
try {
const data = JSON.parse(res.stdout.toString());
return {
name: data.name,
status: data.status,
internalIp: data.networkInterfaces?.[0]?.networkIP,
};
} catch {
return { name: this.instanceName, status: 'UNKNOWN' };
}
}
async stop(): Promise<number> {
const res = spawnSync(
'gcloud',
[
'compute',
'instances',
'stop',
this.instanceName,
'--project',
this.projectId,
'--zone',
this.zone,
],
{ stdio: 'inherit' },
);
return res.status ?? 1;
}
private quote(str: string) {
return `'${str.replace(/'/g, "'\\''")}'`;
}
}
@@ -1,29 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { GceCosProvider } from './GceCosProvider.ts';
import type { WorkerProvider } from './BaseProvider.ts';
const REPO_ROOT = process.cwd();
export class ProviderFactory {
static getProvider(config: {
projectId: string;
zone: string;
instanceName: string;
}): WorkerProvider {
// Currently we only have GceCosProvider, but this is where we'd branch
return new GceCosProvider(
config.projectId,
config.zone,
config.instanceName,
REPO_ROOT,
);
}
}
@@ -1,59 +0,0 @@
#!/bin/bash
set -e
# Ensure we have a valid environment for non-interactive startup
export USER=${USER:-ubuntu}
export HOME=/home/$USER
export DEBIAN_FRONTEND=noninteractive
echo "🛠️ Provisioning High-Performance Gemini CLI Maintainer Worker..."
# Wait for apt lock
wait_for_apt() {
while sudo fuser /var/lib/dpkg/lock-frontend /var/lib/apt/lists/lock >/dev/null 2>&1 ; do
sleep 2
done
}
wait_for_apt
# 1. System Essentials (Inc. libraries for native node modules)
apt-get update && apt-get install -y \
curl git git-lfs tmux build-essential unzip jq gnupg cron \
libsecret-1-dev libkrb5-dev
# 2. GitHub CLI
if ! command -v gh &> /dev/null; then
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg
chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | tee /etc/apt/sources.list.d/github-cli.list > /dev/null
wait_for_apt
apt-get update && apt-get install gh -y
fi
# 3. Direct Node.js 20 Installation (NodeSource)
if ! command -v node &> /dev/null; then
echo "Installing Node.js 20..."
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
wait_for_apt
apt-get install -y nodejs
fi
# 4. Global Maintenance Tooling
echo "Installing global developer tools..."
npm install -g tsx vitest @google/gemini-cli@nightly
# 5. Pre-warm Repository (Main Hub)
# We clone and build the main repo in the image so that new worktrees start with a warm cache
REMOTE_WORK_DIR="$HOME/dev/main"
mkdir -p "$HOME/dev"
if [ ! -d "$REMOTE_WORK_DIR" ]; then
echo "Pre-cloning and building repository..."
git clone --filter=blob:none https://github.com/google-gemini/gemini-cli.git "$REMOTE_WORK_DIR"
cd "$REMOTE_WORK_DIR"
npm install --no-audit --no-fund
npm run build
fi
chown -R $USER:$USER $HOME/dev
echo "✅ Provisioning Complete!"
-383
View File
@@ -1,383 +0,0 @@
import { spawnSync } from 'child_process';
import path from 'path';
import fs from 'fs';
import os from 'os';
import readline from 'readline';
import { ProviderFactory } from './providers/ProviderFactory.ts';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = process.cwd();
/**
* Loads and parses a local .env file from the repository root and the home directory.
*/
function loadDotEnv() {
const envPaths = [
path.join(REPO_ROOT, '.env'),
path.join(os.homedir(), '.env')
];
envPaths.forEach(envPath => {
if (fs.existsSync(envPath)) {
const content = fs.readFileSync(envPath, 'utf8');
content.split('\n').forEach(line => {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) return;
const match = trimmed.match(/^([^=]+)=(.*)$/);
if (match) {
const key = match[1].trim();
const val = match[2].trim().replace(/^["'](.*)["']$/, '$1');
if (!process.env[key]) process.env[key] = val;
}
});
}
});
}
async function prompt(question: string, defaultValue: string, explanation?: string, sensitive: boolean = false): Promise<string> {
const autoAccept = process.argv.includes('--yes') || process.argv.includes('-y');
if (autoAccept && defaultValue) return defaultValue;
if (explanation) {
console.log(`\n📖 ${explanation}`);
}
const displayDefault = sensitive && defaultValue ? `${defaultValue.substring(0, 4)}...${defaultValue.substring(defaultValue.length - 4)}` : defaultValue;
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const promptMsg = defaultValue
? `${question} [Detected: ${displayDefault}] (Press <Enter> to keep, or type new value): `
: `${question} (<Enter> for none): `;
return new Promise((resolve) => {
rl.question(promptMsg, (answer) => {
rl.close();
resolve(answer.trim() || defaultValue);
});
});
}
async function confirm(question: string): Promise<boolean> {
const autoAccept = process.argv.includes('--yes') || process.argv.includes('-y');
if (autoAccept) return true;
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
return new Promise((resolve) => {
rl.question(`${question} (y/n): `, (answer) => {
rl.close();
resolve(answer.trim().toLowerCase() === 'y');
});
});
}
async function createFork(upstream: string): Promise<string> {
console.log(` - Creating fork for ${upstream}...`);
const forkRes = spawnSync('gh', ['repo', 'fork', upstream, '--clone=false'], { stdio: 'inherit' });
if (forkRes.status === 0) {
const userRes = spawnSync('gh', ['api', 'user', '-q', '.login'], { stdio: 'pipe' });
const user = userRes.stdout.toString().trim();
return `${user}/${upstream.split('/')[1]}`;
}
return upstream;
}
export async function runSetup(env: NodeJS.ProcessEnv = process.env) {
loadDotEnv();
console.log(`
================================================================================
🚀 GEMINI WORKSPACES: HIGH-PERFORMANCE REMOTE DEVELOPMENT
================================================================================
Workspaces allow you to delegate heavy tasks (PR reviews, agentic fixes,
and full builds) to a dedicated, high-performance GCP worker.
================================================================================
`);
console.log('📝 PHASE 1: CONFIGURATION');
console.log('--------------------------------------------------------------------------------');
const settingsPath = path.join(REPO_ROOT, '.gemini/workspaces/settings.json');
let settings: any = {};
let skipConfig = false;
if (fs.existsSync(settingsPath)) {
try {
settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
if (settings.workspace && !process.argv.includes('--reconfigure')) {
console.log(' ✅ Existing configuration found.');
const shouldSkip = await confirm('Use existing configuration and skip to execution?');
if (shouldSkip) {
skipConfig = true;
}
}
} catch (e) {}
}
// 1. Project Identity
let projectId = settings.workspace?.projectId || '';
let zone = settings.workspace?.zone || 'us-west1-a';
let terminalTarget = settings.workspace?.terminalTarget || 'tab';
let upstreamRepo = settings.workspace?.upstreamRepo || 'google-gemini/gemini-cli';
let userFork = settings.workspace?.userFork || upstreamRepo;
if (!skipConfig) {
const defaultProject = env.GOOGLE_CLOUD_PROJECT || env.WORKSPACE_PROJECT || projectId || '';
projectId = await prompt('GCP Project ID', defaultProject,
'The GCP Project where your workspace worker will live. Your personal project is recommended.');
if (!projectId) {
console.error('❌ Project ID is required. Set GOOGLE_CLOUD_PROJECT or enter it manually.');
return 1;
}
zone = await prompt('Compute Zone', env.WORKSPACE_ZONE || zone,
'The physical location of your worker. us-west1-a is the team default.');
terminalTarget = await prompt('Terminal UI Target (foreground, background, tab, window)', env.WORKSPACE_TERM_TARGET || terminalTarget,
'When you start a job in gemini-cli, should it run as a foreground shell, background shell (no attach), new iterm2 tab, or new iterm2 window?');
// 2. Repository Discovery (Dynamic)
console.log('\n🔍 Detecting repository origins...');
const repoInfoRes = spawnSync('gh', ['repo', 'view', '--json', 'nameWithOwner,parent,isFork'], { stdio: 'pipe' });
if (repoInfoRes.status === 0) {
try {
const repoInfo = JSON.parse(repoInfoRes.stdout.toString());
upstreamRepo = repoInfo.isFork && repoInfo.parent ? repoInfo.parent.nameWithOwner : repoInfo.nameWithOwner;
console.log(` - Upstream identified: ${upstreamRepo}`);
console.log(` - Searching for your forks of ${upstreamRepo}...`);
const upstreamOwner = upstreamRepo.split('/')[0];
const upstreamName = upstreamRepo.split('/')[1];
const gqlQuery = `query { viewer { repositories(first: 100, isFork: true, affiliations: OWNER) { nodes { nameWithOwner parent { nameWithOwner } } } } }`;
const forksRes = spawnSync('gh', ['api', 'graphql', '-f', `query=${gqlQuery}`, '--jq', `.data.viewer.repositories.nodes[] | select(.parent.nameWithOwner == "${upstreamRepo}") | .nameWithOwner`], { stdio: 'pipe' });
const myForks = forksRes.stdout.toString().trim().split('\n').filter(Boolean);
if (myForks.length > 0) {
console.log('\n🍴 Found existing forks:');
myForks.forEach((name: string, i: number) => console.log(` [${i + 1}] ${name}`));
console.log(` [c] Create a new fork`);
console.log(` [u] Use upstream directly (not recommended)`);
const choice = await prompt('Select an option', '1');
if (choice.toLowerCase() === 'c') {
userFork = await createFork(upstreamRepo);
} else if (choice.toLowerCase() === 'u') {
userFork = upstreamRepo;
} else {
const idx = parseInt(choice) - 1;
userFork = myForks[idx] || myForks[0];
}
} else {
const shouldFork = await confirm('No fork detected. Create a personal fork for sandboxed implementations?');
userFork = shouldFork ? await createFork(upstreamRepo) : upstreamRepo;
}
} catch (e) {
userFork = upstreamRepo;
}
}
console.log(` ✅ Upstream: ${upstreamRepo}`);
console.log(` ✅ Workspace: ${userFork}`);
}
// 3. Security & Auth (Always check for token if init is needed)
let githubToken = env.WORKSPACE_GH_TOKEN || '';
if (!skipConfig) {
if (!githubToken) {
const hasToken = await confirm('\nDo you already have a GitHub Personal Access Token (PAT) with "Read/Write" access to contents & PRs?');
if (hasToken) {
githubToken = await prompt('Paste Scoped Token', '');
} else {
const shouldGenToken = await confirm('Would you like to generate a new scoped token now? (Highly Recommended)');
if (shouldGenToken) {
const baseUrl = 'https://github.com/settings/personal-access-tokens/new';
const name = `Workspace-${env.USER}`;
const repoParams = userFork !== upstreamRepo
? `&repositories[]=${encodeURIComponent(upstreamRepo)}&repositories[]=${encodeURIComponent(userFork)}`
: `&repositories[]=${encodeURIComponent(upstreamRepo)}`;
const magicLink = `${baseUrl}?name=${encodeURIComponent(name)}&description=Gemini+Workspaces+Worker${repoParams}&contents=write&pull_requests=write&metadata=read`;
const terminalLink = `\u001b]8;;${magicLink}\u0007${magicLink}\u001b]8;;\u0007`;
console.log(`\n🔐 ACTION REQUIRED: Create a token with the required permissions:`);
console.log(`\n${terminalLink}\n`);
githubToken = await prompt('Paste Scoped Token', '');
}
}
} else {
githubToken = await prompt('GitHub Token', githubToken, 'A GitHub PAT is required for remote repository access and PR operations.', true);
}
}
// 4. Gemini API Auth Strategy
console.log('\n🔐 Detecting Gemini Authentication strategy...');
const localSettingsPath = path.join(env.HOME || '', '.gemini/settings.json');
let authStrategy = 'google_accounts';
let geminiApiKey = env.WORKSPACE_GEMINI_API_KEY || env.GEMINI_API_KEY || '';
if (fs.existsSync(localSettingsPath)) {
try {
const localSettings = JSON.parse(fs.readFileSync(localSettingsPath, 'utf8'));
authStrategy = localSettings.security?.auth?.selectedType || 'google_accounts';
if (!geminiApiKey && localSettings.security?.auth?.apiKey) {
geminiApiKey = localSettings.security.auth.apiKey;
}
console.log(` - Local Auth Method: ${authStrategy}`);
} catch (e) {}
}
if (authStrategy === 'gemini-api-key') {
if (geminiApiKey) {
console.log('\n🔐 Found Gemini API Key in environment or settings.');
geminiApiKey = await prompt('Gemini API Key', geminiApiKey, 'Enter to use? Or paste a new one', true);
} else {
console.log('\n📖 In API Key mode, the remote worker needs your Gemini API Key to authenticate.');
geminiApiKey = await prompt('Gemini API Key', '', 'Paste your Gemini API Key', true);
}
} else {
console.log(` - Using current auth strategy: ${authStrategy}`);
}
// 5. Save Confirmed State
const targetVM = `gcli-workspace-${env.USER || 'mattkorwel'}`;
if (!fs.existsSync(path.dirname(settingsPath))) fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
settings = {
workspace: {
projectId, zone, terminalTarget,
userFork, upstreamRepo,
remoteHost: 'gcli-worker',
remoteWorkDir: '~/dev/main',
useContainer: true
}
};
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
console.log(`\n✅ Configuration saved to ${settingsPath}`);
// Transition to Execution
const provider = ProviderFactory.getProvider({ projectId, zone, instanceName: targetVM });
console.log('\n🏗️ PHASE 2: INFRASTRUCTURE');
console.log('--------------------------------------------------------------------------------');
console.log(` - Verifying access and finding worker ${targetVM}...`);
let status = await provider.getStatus();
if (status.status === 'UNKNOWN' || status.status === 'ERROR') {
const shouldProvision = await confirm(`Worker ${targetVM} not found. Provision it now?`);
if (!shouldProvision) return 1;
const provisionRes = await provider.provision();
if (provisionRes !== 0) return 1;
status = await provider.getStatus();
}
if (status.status !== 'RUNNING') {
console.log(' - Waking up worker...');
await provider.ensureReady();
}
console.log('\n🚀 PHASE 3: REMOTE INITIALIZATION');
console.log('--------------------------------------------------------------------------------');
const setupRes = await provider.setup({ projectId, zone, dnsSuffix: '.internal.gcpnode.com' });
if (setupRes !== 0) return setupRes;
// Use the unified path to ensure host and container match perfectly
const workspaceRoot = `/home/node/.workspaces`;
const persistentScripts = `${workspaceRoot}/scripts`;
const remoteConfigDir = `${workspaceRoot}/gemini-cli-config/.gemini`;
console.log(`\n📦 Synchronizing Logic & Credentials...`);
// Ensure the directory structure exists on the host
await provider.exec(`sudo mkdir -p ${workspaceRoot}/main ${workspaceRoot}/worktrees ${workspaceRoot}/policies ${workspaceRoot}/scripts ${remoteConfigDir}`);
await provider.exec(`sudo chown -R 1000:1000 ${workspaceRoot}`);
await provider.exec(`sudo chmod -R 777 ${workspaceRoot}`);
// 1. Sync Scripts & Policies
await provider.sync('extensions/workspaces/scripts/', `${persistentScripts}/`, { delete: true, sudo: true });
await provider.sync('policies/workspaces/workspace-policy.toml', `${workspaceRoot}/policies/workspace-policy.toml`, { sudo: true });
// 2. Initialize Remote Gemini Config with Auth
console.log('⚙️ Initializing remote Gemini configuration...');
// NEW: Sync local theme and UI preferences
let localTheme = 'Shades Of Purple';
let useAlternateBuffer = true;
let useBackgroundColor = true;
if (fs.existsSync(localSettingsPath)) {
try {
const localSettings = JSON.parse(fs.readFileSync(localSettingsPath, 'utf8'));
localTheme = localSettings.ui?.theme || localTheme;
useAlternateBuffer = localSettings.ui?.useAlternateBuffer ?? useAlternateBuffer;
useBackgroundColor = localSettings.ui?.useBackgroundColor ?? useBackgroundColor;
} catch (e) {}
}
const remoteSettings: any = {
security: {
auth: {
selectedType: authStrategy
},
folderTrust: {
enabled: false
}
},
ui: {
theme: localTheme,
useAlternateBuffer,
useBackgroundColor,
},
general: {
enableAutoUpdate: false
}
};
if (authStrategy === 'gemini-api-key' && geminiApiKey) {
remoteSettings.security.auth.apiKey = geminiApiKey;
console.log(' ✅ Configuring remote for API Key authentication.');
}
const tmpSettingsPath = path.join(os.tmpdir(), `remote-settings-${Date.now()}.json`);
fs.writeFileSync(tmpSettingsPath, JSON.stringify(remoteSettings, null, 2));
// Ensure the remote config dir exists before syncing
await provider.exec(`sudo mkdir -p ${remoteConfigDir} && sudo chmod 777 ${remoteConfigDir}`);
await provider.sync(tmpSettingsPath, `${remoteConfigDir}/settings.json`, { sudo: true });
fs.unlinkSync(tmpSettingsPath);
// 3. Sync credentials for Google Accounts if needed
if (authStrategy === 'google_accounts' || authStrategy === 'oauth-personal') {
if (fs.existsSync(path.join(env.HOME || '', '.gemini/google_accounts.json'))) {
await provider.sync(path.join(env.HOME || '', '.gemini/google_accounts.json'), `${remoteConfigDir}/google_accounts.json`, { sudo: true });
console.log(' ✅ Synchronized Google Accounts credentials.');
}
}
if (githubToken) {
await provider.exec(`echo ${githubToken} | sudo tee ${workspaceRoot}/.gh_token > /dev/null && sudo chmod 600 ${workspaceRoot}/.gh_token`);
// Authenticate GH CLI on host
await provider.exec(`sudo -u $(whoami) gh auth login --with-token < ${workspaceRoot}/.gh_token`);
console.log(' ✅ Authenticated GitHub CLI on host.');
}
// Final Repo Sync
console.log(`🚀 Finalizing Remote Repository (${userFork})...`);
const repoUrl = `https://github.com/${userFork}.git`;
const cloneCmd = `sudo rm -rf ${workspaceRoot}/main && sudo git clone --quiet --filter=blob:none ${repoUrl} ${workspaceRoot}/main && sudo git -C ${workspaceRoot}/main remote add upstream https://github.com/${upstreamRepo}.git && sudo git -C ${workspaceRoot}/main fetch --quiet upstream && sudo chown -R 1000:1000 ${workspaceRoot}`;
await provider.exec(cloneCmd);
console.log('\n✨ ALL SYSTEMS GO! Your Gemini Workspace is ready.');
return 0;
}
if (import.meta.url === `file://${process.argv[1]}`) {
runSetup().catch(console.error);
}
-72
View File
@@ -1,72 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import path from 'node:path';
import fs from 'node:fs';
import { ProviderFactory } from './providers/ProviderFactory.ts';
const REPO_ROOT = process.cwd();
async function runStatus(env: NodeJS.ProcessEnv = process.env) {
const settingsPath = path.join(REPO_ROOT, '.gemini/workspaces/settings.json');
if (!fs.existsSync(settingsPath)) {
console.error('❌ Settings not found. Run "workspace setup" first.');
return 1;
}
const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
const config = settings.workspace;
if (!config) {
console.error('❌ Deep Review configuration not found.');
return 1;
}
const { projectId, zone } = config;
const targetVM = `gcli-workspace-${env.USER || 'mattkorwel'}`;
const provider = ProviderFactory.getProvider({
projectId,
zone,
instanceName: targetVM,
});
console.log(`\n🛰️ Workspace Mission Control: ${targetVM}`);
console.log(
`--------------------------------------------------------------------------------`,
);
const status = await provider.getStatus();
console.log(` - VM State: ${status.status}`);
console.log(` - Internal IP: ${status.internalIp || 'N/A'}`);
if (status.status === 'RUNNING') {
console.log(`\n🧵 Active Sessions (tmux):`);
// We fetch the list of sessions from INSIDE the container
const tmuxRes = await provider.getExecOutput(
'tmux list-sessions -F "#S" 2>/dev/null',
{ wrapContainer: 'maintainer-worker' },
);
if (tmuxRes.status === 0 && tmuxRes.stdout.trim()) {
const sessions = tmuxRes.stdout.trim().split('\n');
sessions.forEach((s) => {
if (s.startsWith('workspace-')) {
console.log(`${s}`);
} else {
console.log(` 🔹 ${s} (Non-workspace)`);
}
});
} else {
console.log(' - No active sessions');
}
}
console.log(
`--------------------------------------------------------------------------------\n`,
);
return 0;
}
runStatus().catch(console.error);
-74
View File
@@ -1,74 +0,0 @@
/**
* Universal Workspace Worker (Remote)
*
* Stateful orchestrator for complex development loops.
*/
import { spawnSync } from 'child_process';
import path from 'path';
import fs from 'fs';
import { runReviewPlaybook } from './playbooks/review.ts';
import { runFixPlaybook } from './playbooks/fix.ts';
import { runReadyPlaybook } from './playbooks/ready.ts';
export async function runWorker(args: string[]) {
const prNumberOrIssue = args[0];
const branchName = args[1];
const policyPath = args[2];
const action = args[3] || 'review';
if (!prNumberOrIssue || !policyPath) {
console.error('Usage: tsx worker.ts <ID> <BRANCH_NAME> <POLICY_PATH> [action]');
return 1;
}
const workDir = process.cwd();
// For 'implement', the ID is an issue number and we might not have a branch yet
const isImplement = action === 'implement';
const targetDir = isImplement ? workDir : path.join(workDir, branchName);
// 1. Provision Environment
if (!isImplement && !fs.existsSync(targetDir)) {
console.log(`🌿 Provisioning PR #${prNumberOrIssue} into ${branchName}...`);
const cloneCmd = `git clone --filter=blob:none https://github.com/google-gemini/gemini-cli.git ${targetDir}`;
spawnSync(cloneCmd, { stdio: 'inherit', shell: true });
process.chdir(targetDir);
spawnSync('gh', ['pr', 'checkout', prNumberOrIssue], { stdio: 'inherit' });
} else if (!isImplement) {
process.chdir(targetDir);
}
// Use global gemini command pre-installed in the maintainer image
const geminiBin = 'gemini';
// 2. Dispatch to Playbook
switch (action) {
case 'review':
return runReviewPlaybook(prNumberOrIssue, targetDir, policyPath, geminiBin);
case 'fix':
// The 'fix' playbook now handles its own internal loop
return runFixPlaybook(prNumberOrIssue, targetDir, policyPath, geminiBin);
case 'ready':
return runReadyPlaybook(prNumberOrIssue, targetDir, policyPath, geminiBin);
case 'implement':
// Lazy-load implement playbook (to be created)
const { runImplementPlaybook } = await import('./playbooks/implement.ts');
return runImplementPlaybook(prNumberOrIssue, workDir, policyPath, geminiBin);
case 'open':
console.log(`🚀 Dropping into manual session...`);
return 0;
default:
console.error(`❌ Unknown action: ${action}`);
return 1;
}
}
if (import.meta.url === `file://${process.argv[1]}`) {
runWorker(process.argv.slice(2)).catch(console.error);
}
@@ -1,62 +0,0 @@
---
name: workspaces
description: Expertise in managing and utilizing Gemini Workspaces for high-performance remote development tasks.
---
# Gemini Workspaces Skill
This skill enables the agent to utilize **Gemini Workspaces**—a high-performance, persistent remote development platform. It allows the agent to move intensive tasks (PR reviews, complex repairs, full builds) from the local environment to a dedicated cloud worker.
## 🛠️ Key Capabilities
1. **Persistent Execution**: Jobs run in remote `tmux` sessions. Disconnecting or crashing the local terminal does not stop the remote work.
2. **Parallel Infrastructure**: The agent can launch a heavy task (like a full build or CI run) in a workspace while continuing to assist the user locally.
3. **Behavioral Fidelity**: Remote workers have full tool access (Git, Node, Docker, etc.) and high-performance compute, allowing the agent to provide behavioral proofs of its work.
## 📋 Instructions for the Agent
### When to use Workspaces
- **Intensive Tasks**: Full preflight runs, large-scale refactors, or deep PR reviews.
- **Persistent Logic**: When a task is expected to take longer than a few minutes and needs to survive local connection drops.
- **Environment Isolation**: When you need a clean, high-performance environment to verify a fix without polluting the user's local machine.
### How to use Workspaces
1. **Setup**: If the user hasn't initialized their environment, you MUST run the setup script using npx tsx and the absolute path. Do NOT use npm scripts.
```bash
npx tsx ${extensionPath}/extensions/workspaces/scripts/setup.ts
```
2. **Launch**: Start a playbook for a specific PR/issue:
```bash
npx tsx ${extensionPath}/extensions/workspaces/scripts/orchestrator.ts <PR_NUMBER> [action]
```
- Actions: `review` (default), `fix`, `ready`.
3. **Check Status**: See global state and active sessions:
```bash
npx tsx ${extensionPath}/extensions/workspaces/scripts/status.ts
```
Or deep-dive into specific PR logs:
```bash
npx tsx ${extensionPath}/extensions/workspaces/scripts/check.ts <PR_NUMBER>
```
4. **Cleanup**:
- **Bulk**: Clear all sessions/worktrees:
```bash
npx tsx ${extensionPath}/extensions/workspaces/scripts/clean.ts --all
```
- **Surgical**: Kill a specific PR task:
```bash
npx tsx ${extensionPath}/extensions/workspaces/scripts/clean.ts <PR_NUMBER> <action>
```
5. **Fleet**: Manage VM lifecycle:
```bash
npx tsx ${extensionPath}/extensions/workspaces/scripts/fleet.ts [stop|provision|list]
```
6. **Attach/Logs**:
```bash
npx tsx ${extensionPath}/extensions/workspaces/scripts/attach.ts <PR_NUMBER>
npx tsx ${extensionPath}/extensions/workspaces/scripts/logs.ts <PR_NUMBER>
```
## ⚠️ Important Constraints
- **NO NPM**: Do NOT attempt to use `npm run` or `npm workspace`. Those commands are deprecated in favor of running the extension scripts directly.
- **npx tsx**: Always use `npx tsx` followed by the absolute path provided in `${extensionPath}`.
- **Absolute Paths**: Always use absolute paths (e.g., `/mnt/disks/data/...`) when orchestrating remote commands.
-11
View File
@@ -1,11 +0,0 @@
{
"name": "workspaces",
"version": "0.1.0",
"description": "High-performance remote development workspaces for Gemini CLI.",
"author": "Google Gemini Team",
"license": "Apache-2.0",
"skills": [
"extensions/workspaces/skills/workspaces/SKILL.md"
],
"contextFileName": "extensions/workspaces/docs/GEMINI.md"
}
@@ -1 +0,0 @@
{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"write_file","args":{"file_path":"test.txt","content":"hello"}}},{"text":"I've successfully written \"hello\" to test.txt. The file has been created with the specified content."}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":50,"totalTokenCount":150}}]}
-29
View File
@@ -203,33 +203,4 @@ describe.skipIf(!chromeAvailable)('browser-agent', () => {
// Should successfully complete all operations
assertModelHasOutput(result);
});
it('should handle tool confirmation for write_file without crashing', async () => {
rig.setup('tool-confirmation', {
fakeResponsesPath: join(
__dirname,
'browser-agent.confirmation.responses',
),
settings: {
agents: {
browser_agent: {
headless: true,
sessionMode: 'isolated',
},
},
},
});
const run = await rig.runInteractive({ approvalMode: 'default' });
await run.type('Write hello to test.txt');
await run.type('\r');
await run.expectText('Allow', 15000);
await run.type('y');
await run.type('\r');
await run.expectText('successfully written', 15000);
});
});
+5 -4
View File
@@ -42,10 +42,11 @@ describe('extension install', () => {
const listResult = await rig.runCommand(['extensions', 'list']);
expect(listResult).toContain('test-extension-install');
writeFileSync(testServerPath, extensionUpdate);
const updateResult = await rig.runCommand(
['extensions', 'update', `test-extension-install`],
{ stdin: 'y\n' },
);
const updateResult = await rig.runCommand([
'extensions',
'update',
`test-extension-install`,
]);
expect(updateResult).toContain('0.0.2');
} finally {
await rig.runCommand([
+22 -549
View File
@@ -1,12 +1,12 @@
{
"name": "@google/gemini-cli",
"version": "0.36.0-nightly.20260317.2f90b4653",
"version": "0.35.0-nightly.20260311.657f19c1f",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@google/gemini-cli",
"version": "0.36.0-nightly.20260317.2f90b4653",
"version": "0.35.0-nightly.20260311.657f19c1f",
"workspaces": [
"packages/*"
],
@@ -3038,27 +3038,6 @@
"integrity": "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==",
"license": "BSD-3-Clause"
},
"node_modules/@puppeteer/browsers": {
"version": "2.13.0",
"resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.13.0.tgz",
"integrity": "sha512-46BZJYJjc/WwmKjsvDFykHtXrtomsCIrwYQPOP7VfMJoZY2bsDF9oROBABR3paDjDcmkUye1Pb1BqdcdiipaWA==",
"license": "Apache-2.0",
"dependencies": {
"debug": "^4.4.3",
"extract-zip": "^2.0.1",
"progress": "^2.0.3",
"proxy-agent": "^6.5.0",
"semver": "^7.7.4",
"tar-fs": "^3.1.1",
"yargs": "^17.7.2"
},
"bin": {
"browsers": "lib/cjs/main-cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@rollup/rollup-android-arm-eabi": {
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz",
@@ -3783,12 +3762,6 @@
"node": ">= 10"
}
},
"node_modules/@tootallnate/quickjs-emscripten": {
"version": "0.23.0",
"resolved": "https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz",
"integrity": "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==",
"license": "MIT"
},
"node_modules/@ts-morph/common": {
"version": "0.12.3",
"resolved": "https://registry.npmjs.org/@ts-morph/common/-/common-0.12.3.tgz",
@@ -3976,13 +3949,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/json-stable-stringify": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@types/json-stable-stringify/-/json-stable-stringify-1.1.0.tgz",
"integrity": "sha512-ESTsHWB72QQq+pjUFIbEz9uSCZppD31YrVkbt2rnUciTYEvcwN6uZIhX5JZeBHqRlFJ41x/7MewCs7E2Qux6Cg==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/json5": {
"version": "0.0.29",
"resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz",
@@ -5618,18 +5584,6 @@
"node": ">=12"
}
},
"node_modules/ast-types": {
"version": "0.13.4",
"resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.13.4.tgz",
"integrity": "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w==",
"license": "MIT",
"dependencies": {
"tslib": "^2.0.1"
},
"engines": {
"node": ">=4"
}
},
"node_modules/ast-v8-to-istanbul": {
"version": "0.3.8",
"resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-0.3.8.tgz",
@@ -5722,20 +5676,6 @@
"typed-rest-client": "^1.8.4"
}
},
"node_modules/b4a": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/b4a/-/b4a-1.8.0.tgz",
"integrity": "sha512-qRuSmNSkGQaHwNbM7J78Wwy+ghLEYF1zNrSeMxj4Kgw6y33O3mXcQ6Ie9fRvfU/YnxWkOchPXbaLb73TkIsfdg==",
"license": "Apache-2.0",
"peerDependencies": {
"react-native-b4a": "*"
},
"peerDependenciesMeta": {
"react-native-b4a": {
"optional": true
}
}
},
"node_modules/balanced-match": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
@@ -5745,93 +5685,6 @@
"node": "18 || 20 || >=22"
}
},
"node_modules/bare-events": {
"version": "2.8.2",
"resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.8.2.tgz",
"integrity": "sha512-riJjyv1/mHLIPX4RwiK+oW9/4c3TEUeORHKefKAKnZ5kyslbN+HXowtbaVEqt4IMUB7OXlfixcs6gsFeo/jhiQ==",
"license": "Apache-2.0",
"peerDependencies": {
"bare-abort-controller": "*"
},
"peerDependenciesMeta": {
"bare-abort-controller": {
"optional": true
}
}
},
"node_modules/bare-fs": {
"version": "4.5.5",
"resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.5.5.tgz",
"integrity": "sha512-XvwYM6VZqKoqDll8BmSww5luA5eflDzY0uEFfBJtFKe4PAAtxBjU3YIxzIBzhyaEQBy1VXEQBto4cpN5RZJw+w==",
"license": "Apache-2.0",
"dependencies": {
"bare-events": "^2.5.4",
"bare-path": "^3.0.0",
"bare-stream": "^2.6.4",
"bare-url": "^2.2.2",
"fast-fifo": "^1.3.2"
},
"engines": {
"bare": ">=1.16.0"
},
"peerDependencies": {
"bare-buffer": "*"
},
"peerDependenciesMeta": {
"bare-buffer": {
"optional": true
}
}
},
"node_modules/bare-os": {
"version": "3.7.1",
"resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.7.1.tgz",
"integrity": "sha512-ebvMaS5BgZKmJlvuWh14dg9rbUI84QeV3WlWn6Ph6lFI8jJoh7ADtVTyD2c93euwbe+zgi0DVrl4YmqXeM9aIA==",
"license": "Apache-2.0",
"engines": {
"bare": ">=1.14.0"
}
},
"node_modules/bare-path": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.0.0.tgz",
"integrity": "sha512-tyfW2cQcB5NN8Saijrhqn0Zh7AnFNsnczRcuWODH0eYAXBsJ5gVxAUuNr7tsHSC6IZ77cA0SitzT+s47kot8Mw==",
"license": "Apache-2.0",
"dependencies": {
"bare-os": "^3.0.1"
}
},
"node_modules/bare-stream": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.8.1.tgz",
"integrity": "sha512-bSeR8RfvbRwDpD7HWZvn8M3uYNDrk7m9DQjYOFkENZlXW8Ju/MPaqUPQq5LqJ3kyjEm07siTaAQ7wBKCU59oHg==",
"license": "Apache-2.0",
"dependencies": {
"streamx": "^2.21.0",
"teex": "^1.0.1"
},
"peerDependencies": {
"bare-buffer": "*",
"bare-events": "*"
},
"peerDependenciesMeta": {
"bare-buffer": {
"optional": true
},
"bare-events": {
"optional": true
}
}
},
"node_modules/bare-url": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.3.2.tgz",
"integrity": "sha512-ZMq4gd9ngV5aTMa5p9+UfY0b3skwhHELaDkhEHetMdX0LRkW9kzaym4oo/Eh+Ghm0CCDuMTsRIGM/ytUc1ZYmw==",
"license": "Apache-2.0",
"dependencies": {
"bare-path": "^3.0.0"
}
},
"node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
@@ -5852,15 +5705,6 @@
],
"license": "MIT"
},
"node_modules/basic-ftp": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.2.0.tgz",
"integrity": "sha512-VoMINM2rqJwJgfdHq6RiUudKt2BV+FY5ZFezP/ypmwayk68+NzzAQy4XXLlqsGD4MCzq3DrmNFD/uUmBJuGoXw==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/before-after-hook": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-4.0.0.tgz",
@@ -6051,6 +5895,7 @@
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.8.tgz",
"integrity": "sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.0",
@@ -6258,32 +6103,6 @@
"node": ">=18"
}
},
"node_modules/chrome-devtools-mcp": {
"version": "0.19.0",
"resolved": "https://registry.npmjs.org/chrome-devtools-mcp/-/chrome-devtools-mcp-0.19.0.tgz",
"integrity": "sha512-LfqjOxdUjWvCQrfeI5V3ZBJCUIDKGNmexSbSAgsrjVggN4X1OSObLxleSlX2zwcXRZYxqy209cww0MXcXuN1zw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"chrome-devtools-mcp": "build/src/index.js"
},
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=23"
}
},
"node_modules/chromium-bidi": {
"version": "14.0.0",
"resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-14.0.0.tgz",
"integrity": "sha512-9gYlLtS6tStdRWzrtXaTMnqcM4dudNegMXJxkR0I/CXObHalYeYcAMPrL19eroNZHtJ8DQmu1E+ZNOYu/IXMXw==",
"license": "Apache-2.0",
"dependencies": {
"mitt": "^3.0.1",
"zod": "^3.24.1"
},
"peerDependencies": {
"devtools-protocol": "*"
}
},
"node_modules/cjs-module-lexer": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-2.2.0.tgz",
@@ -7082,6 +6901,7 @@
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz",
"integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==",
"dev": true,
"license": "MIT",
"dependencies": {
"es-define-property": "^1.0.0",
@@ -7125,20 +6945,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/degenerator": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/degenerator/-/degenerator-5.0.1.tgz",
"integrity": "sha512-TllpMR/t0M5sqCXfj85i4XaAzxmS5tVA16dqvdkMwGmzI+dXLXnw3J+3Vdv7VKw+ThlTMboK6i9rnZ6Nntj5CQ==",
"license": "MIT",
"dependencies": {
"ast-types": "^0.13.4",
"escodegen": "^2.1.0",
"esprima": "^4.0.1"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
@@ -7398,12 +7204,6 @@
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/devtools-protocol": {
"version": "0.0.1581282",
"resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1581282.tgz",
"integrity": "sha512-nv7iKtNZQshSW2hKzYNr46nM/Cfh5SEvE2oV0/SEGgc9XupIY5ggf84Cz8eJIkBce7S3bmTAauFD6aysMpnqsQ==",
"license": "BSD-3-Clause"
},
"node_modules/dezalgo": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/dezalgo/-/dezalgo-1.0.4.tgz",
@@ -7959,27 +7759,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/escodegen": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz",
"integrity": "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==",
"license": "BSD-2-Clause",
"dependencies": {
"esprima": "^4.0.1",
"estraverse": "^5.2.0",
"esutils": "^2.0.2"
},
"bin": {
"escodegen": "bin/escodegen.js",
"esgenerate": "bin/esgenerate.js"
},
"engines": {
"node": ">=6.0"
},
"optionalDependencies": {
"source-map": "~0.6.1"
}
},
"node_modules/eslint": {
"version": "9.29.0",
"resolved": "https://registry.npmjs.org/eslint/-/eslint-9.29.0.tgz",
@@ -8339,6 +8118,7 @@
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",
"integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",
"dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=4.0"
@@ -8357,6 +8137,7 @@
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",
"integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==",
"dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=0.10.0"
@@ -8408,15 +8189,6 @@
"uuid": "dist/bin/uuid"
}
},
"node_modules/events-universal": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/events-universal/-/events-universal-1.0.1.tgz",
"integrity": "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==",
"license": "Apache-2.0",
"dependencies": {
"bare-events": "^2.7.0"
}
},
"node_modules/eventsource": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",
@@ -8623,12 +8395,6 @@
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"license": "MIT"
},
"node_modules/fast-fifo": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz",
"integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==",
"license": "MIT"
},
"node_modules/fast-glob": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
@@ -9271,29 +9037,6 @@
"url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
}
},
"node_modules/get-uri": {
"version": "6.0.5",
"resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.5.tgz",
"integrity": "sha512-b1O07XYq8eRuVzBNgJLstU6FYc1tS6wnMtF1I1D9lE8LxZSOGZ7LhxN54yPP6mGw5f2CkXY2BQUL9Fx41qvcIg==",
"license": "MIT",
"dependencies": {
"basic-ftp": "^5.0.2",
"data-uri-to-buffer": "^6.0.2",
"debug": "^4.3.4"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/get-uri/node_modules/data-uri-to-buffer": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz",
"integrity": "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw==",
"license": "MIT",
"engines": {
"node": ">= 14"
}
},
"node_modules/glob": {
"version": "12.0.0",
"resolved": "https://registry.npmjs.org/glob/-/glob-12.0.0.tgz",
@@ -9718,6 +9461,7 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz",
"integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==",
"dev": true,
"license": "MIT",
"dependencies": {
"es-define-property": "^1.0.0"
@@ -9919,6 +9663,7 @@
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
"integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",
"dev": true,
"license": "MIT",
"dependencies": {
"agent-base": "^7.1.0",
@@ -10832,6 +10577,7 @@
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz",
"integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==",
"dev": true,
"license": "MIT"
},
"node_modules/isexe": {
@@ -11055,25 +10801,6 @@
"integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",
"license": "BSD-2-Clause"
},
"node_modules/json-stable-stringify": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/json-stable-stringify/-/json-stable-stringify-1.3.0.tgz",
"integrity": "sha512-qtYiSSFlwot9XHtF9bD9c7rwKjr+RecWT//ZnPvSmEjpV5mmPOCN4j8UjY5hbjNkOwZ/jQv3J6R1/pL7RwgMsg==",
"license": "MIT",
"dependencies": {
"call-bind": "^1.0.8",
"call-bound": "^1.0.4",
"isarray": "^2.0.5",
"jsonify": "^0.0.1",
"object-keys": "^1.1.1"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/json-stable-stringify-without-jsonify": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz",
@@ -11122,15 +10849,6 @@
"node": ">= 10.0.0"
}
},
"node_modules/jsonify": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/jsonify/-/jsonify-0.0.1.tgz",
"integrity": "sha512-2/Ki0GcmuqSrgFyelQq9M05y7PS0mEwuIzrf3f1fPqkVDVRvZrPZtVSMHxdgo8Aq0sxAOb/cr2aqqA3LeWHVPg==",
"license": "Public Domain",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/jsonwebtoken": {
"version": "9.0.2",
"resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz",
@@ -12041,12 +11759,6 @@
"node": ">= 18"
}
},
"node_modules/mitt": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",
"integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",
"license": "MIT"
},
"node_modules/mkdirp": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz",
@@ -12247,15 +11959,6 @@
"node": ">= 0.6"
}
},
"node_modules/netmask": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/netmask/-/netmask-2.0.2.tgz",
"integrity": "sha512-dBpDMdxv9Irdq66304OLfEmQ9tbNRFnFTuZiLo+bD+r332bBmMJ8GBLXklIXXgxd3+v9+KUnZaUR5PJMa75Gsg==",
"license": "MIT",
"engines": {
"node": ">= 0.4.0"
}
},
"node_modules/node-addon-api": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-4.3.0.tgz",
@@ -12698,6 +12401,7 @@
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",
"integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
@@ -12958,38 +12662,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/pac-proxy-agent": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.2.0.tgz",
"integrity": "sha512-TEB8ESquiLMc0lV8vcd5Ql/JAKAoyzHFXaStwjkzpOpC5Yv+pIzLfHvjTSdf3vpa2bMiUQrg9i6276yn8666aA==",
"license": "MIT",
"dependencies": {
"@tootallnate/quickjs-emscripten": "^0.23.0",
"agent-base": "^7.1.2",
"debug": "^4.3.4",
"get-uri": "^6.0.1",
"http-proxy-agent": "^7.0.0",
"https-proxy-agent": "^7.0.6",
"pac-resolver": "^7.0.1",
"socks-proxy-agent": "^8.0.5"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/pac-resolver": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/pac-resolver/-/pac-resolver-7.0.1.tgz",
"integrity": "sha512-5NPgf87AT2STgwa2ntRMr45jTKrYBGkVU36yT0ig/n/GMAa3oPqhZfIQ2kMEimReg0+t9kZViDVZ83qfVUlckg==",
"license": "MIT",
"dependencies": {
"degenerator": "^5.0.0",
"netmask": "^2.0.2"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/package-json": {
"version": "10.0.1",
"resolved": "https://registry.npmjs.org/package-json/-/package-json-10.0.1.tgz",
@@ -13460,15 +13132,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/progress": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",
"integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",
"license": "MIT",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/prompts": {
"version": "2.4.2",
"resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz",
@@ -13574,40 +13237,6 @@
"node": ">= 0.10"
}
},
"node_modules/proxy-agent": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/proxy-agent/-/proxy-agent-6.5.0.tgz",
"integrity": "sha512-TmatMXdr2KlRiA2CyDu8GqR8EjahTG3aY3nXjdzFyoZbmB8hrBsTyMezhULIXKnC0jpfjlmiZ3+EaCzoInSu/A==",
"license": "MIT",
"dependencies": {
"agent-base": "^7.1.2",
"debug": "^4.3.4",
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.6",
"lru-cache": "^7.14.1",
"pac-proxy-agent": "^7.1.0",
"proxy-from-env": "^1.1.0",
"socks-proxy-agent": "^8.0.5"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/proxy-agent/node_modules/lru-cache": {
"version": "7.18.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz",
"integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/proxy-from-env": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
"license": "MIT"
},
"node_modules/psl": {
"version": "1.15.0",
"resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz",
@@ -13661,45 +13290,6 @@
"node": ">=6"
}
},
"node_modules/puppeteer-core": {
"version": "24.39.0",
"resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-24.39.0.tgz",
"integrity": "sha512-SzIxz76Kgu17HUIi57HOejPiN0JKa9VCd2GcPY1sAh6RA4BzGZarFQdOYIYrBdUVbtyH7CrDb9uhGEwVXK/YNA==",
"license": "Apache-2.0",
"dependencies": {
"@puppeteer/browsers": "2.13.0",
"chromium-bidi": "14.0.0",
"debug": "^4.4.3",
"devtools-protocol": "0.0.1581282",
"typed-query-selector": "^2.12.1",
"webdriver-bidi-protocol": "0.4.1",
"ws": "^8.19.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/puppeteer-core/node_modules/ws": {
"version": "8.19.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz",
"integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/qs": {
"version": "6.14.2",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.14.2.tgz",
@@ -14660,9 +14250,9 @@
}
},
"node_modules/semver": {
"version": "7.7.4",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
"integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
"version": "7.7.2",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz",
"integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==",
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
@@ -14727,6 +14317,7 @@
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz",
"integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==",
"dev": true,
"license": "MIT",
"dependencies": {
"define-data-property": "^1.1.4",
@@ -14992,54 +14583,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/smart-buffer": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz",
"integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==",
"license": "MIT",
"engines": {
"node": ">= 6.0.0",
"npm": ">= 3.0.0"
}
},
"node_modules/socks": {
"version": "2.8.7",
"resolved": "https://registry.npmjs.org/socks/-/socks-2.8.7.tgz",
"integrity": "sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A==",
"license": "MIT",
"dependencies": {
"ip-address": "^10.0.1",
"smart-buffer": "^4.2.0"
},
"engines": {
"node": ">= 10.0.0",
"npm": ">= 3.0.0"
}
},
"node_modules/socks-proxy-agent": {
"version": "8.0.5",
"resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz",
"integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==",
"license": "MIT",
"dependencies": {
"agent-base": "^7.1.2",
"debug": "^4.3.4",
"socks": "^2.8.3"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
"integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
"license": "BSD-3-Clause",
"optional": true,
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -15168,17 +14711,6 @@
"integrity": "sha512-76ORR0DO1o1hlKwTbi/DM3EXWGf3ZJYO8cXX5RJwnul2DEg2oyoZyjLNoQM8WsvZiFKCRfC1O0J7iCvie3RZmQ==",
"license": "MIT"
},
"node_modules/streamx": {
"version": "2.23.0",
"resolved": "https://registry.npmjs.org/streamx/-/streamx-2.23.0.tgz",
"integrity": "sha512-kn+e44esVfn2Fa/O0CPFcex27fjIL6MkVae0Mm6q+E6f0hWv578YCERbv+4m02cjxvDsPKLnmxral/rR6lBMAg==",
"license": "MIT",
"dependencies": {
"events-universal": "^1.0.0",
"fast-fifo": "^1.3.2",
"text-decoder": "^1.1.0"
}
},
"node_modules/strict-event-emitter": {
"version": "0.5.1",
"resolved": "https://registry.npmjs.org/strict-event-emitter/-/strict-event-emitter-0.5.1.tgz",
@@ -15776,32 +15308,6 @@
"node": ">=8"
}
},
"node_modules/tar-fs": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.2.tgz",
"integrity": "sha512-QGxxTxxyleAdyM3kpFs14ymbYmNFrfY+pHj7Z8FgtbZ7w2//VAgLMac7sT6nRpIHjppXO2AwwEOg0bPFVRcmXw==",
"license": "MIT",
"dependencies": {
"pump": "^3.0.0",
"tar-stream": "^3.1.5"
},
"optionalDependencies": {
"bare-fs": "^4.0.1",
"bare-path": "^3.0.0"
}
},
"node_modules/tar-stream": {
"version": "3.1.8",
"resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.1.8.tgz",
"integrity": "sha512-U6QpVRyCGHva435KoNWy9PRoi2IFYCgtEhq9nmrPPpbRacPs9IH4aJ3gbrFC8dPcXvdSZ4XXfXT5Fshbp2MtlQ==",
"license": "MIT",
"dependencies": {
"b4a": "^1.6.4",
"bare-fs": "^4.5.5",
"fast-fifo": "^1.2.0",
"streamx": "^2.15.0"
}
},
"node_modules/teeny-request": {
"version": "9.0.0",
"resolved": "https://registry.npmjs.org/teeny-request/-/teeny-request-9.0.0.tgz",
@@ -15857,15 +15363,6 @@
"node": ">= 6"
}
},
"node_modules/teex": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz",
"integrity": "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==",
"license": "MIT",
"dependencies": {
"streamx": "^2.12.5"
}
},
"node_modules/terminal-link": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/terminal-link/-/terminal-link-4.0.0.tgz",
@@ -15898,15 +15395,6 @@
"node": ">=18"
}
},
"node_modules/text-decoder": {
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.7.tgz",
"integrity": "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==",
"license": "Apache-2.0",
"dependencies": {
"b4a": "^1.6.4"
}
},
"node_modules/text-hex": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/text-hex/-/text-hex-1.0.0.tgz",
@@ -16231,6 +15719,7 @@
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"dev": true,
"license": "0BSD"
},
"node_modules/tsx": {
@@ -16380,12 +15869,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/typed-query-selector": {
"version": "2.12.1",
"resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.1.tgz",
"integrity": "sha512-uzR+FzI8qrUEIu96oaeBJmd9E7CFEiQ3goA5qCVgc4s5llSubcfGHq9yUstZx/k4s9dXHVKsE35YWoFyvEqEHA==",
"license": "MIT"
},
"node_modules/typed-rest-client": {
"version": "1.8.11",
"resolved": "https://registry.npmjs.org/typed-rest-client/-/typed-rest-client-1.8.11.tgz",
@@ -16853,12 +16336,6 @@
}
}
},
"node_modules/webdriver-bidi-protocol": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-0.4.1.tgz",
"integrity": "sha512-ARrjNjtWRRs2w4Tk7nqrf2gBI0QXWuOmMCx2hU+1jUt6d00MjMxURrhxhGbrsoiZKJrhTSTzbIrc554iKI10qw==",
"license": "Apache-2.0"
},
"node_modules/webidl-conversions": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
@@ -17413,7 +16890,7 @@
},
"packages/a2a-server": {
"name": "@google/gemini-cli-a2a-server",
"version": "0.36.0-nightly.20260317.2f90b4653",
"version": "0.35.0-nightly.20260311.657f19c1f",
"dependencies": {
"@a2a-js/sdk": "0.3.11",
"@google-cloud/storage": "^7.16.0",
@@ -17528,7 +17005,7 @@
},
"packages/cli": {
"name": "@google/gemini-cli",
"version": "0.36.0-nightly.20260317.2f90b4653",
"version": "0.35.0-nightly.20260311.657f19c1f",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^0.12.0",
@@ -17700,7 +17177,7 @@
},
"packages/core": {
"name": "@google/gemini-cli-core",
"version": "0.36.0-nightly.20260317.2f90b4653",
"version": "0.35.0-nightly.20260311.657f19c1f",
"license": "Apache-2.0",
"dependencies": {
"@a2a-js/sdk": "0.3.11",
@@ -17749,14 +17226,12 @@
"ignore": "^7.0.0",
"ipaddr.js": "^1.9.1",
"js-yaml": "^4.1.1",
"json-stable-stringify": "^1.3.0",
"marked": "^15.0.12",
"mime": "4.0.7",
"mnemonist": "^0.40.3",
"open": "^10.1.2",
"picomatch": "^4.0.1",
"proper-lockfile": "^4.1.2",
"puppeteer-core": "^24.0.0",
"read-package-up": "^11.0.0",
"shell-quote": "^1.8.3",
"simple-git": "^3.28.0",
@@ -17774,9 +17249,7 @@
"@google/gemini-cli-test-utils": "file:../test-utils",
"@types/fast-levenshtein": "^0.0.4",
"@types/js-yaml": "^4.0.9",
"@types/json-stable-stringify": "^1.1.0",
"@types/picomatch": "^4.0.1",
"chrome-devtools-mcp": "^0.19.0",
"msw": "^2.3.4",
"typescript": "^5.3.3",
"vitest": "^3.1.1"
@@ -17966,7 +17439,7 @@
},
"packages/devtools": {
"name": "@google/gemini-cli-devtools",
"version": "0.36.0-nightly.20260317.2f90b4653",
"version": "0.35.0-nightly.20260311.657f19c1f",
"license": "Apache-2.0",
"dependencies": {
"ws": "^8.16.0"
@@ -17981,7 +17454,7 @@
},
"packages/sdk": {
"name": "@google/gemini-cli-sdk",
"version": "0.36.0-nightly.20260317.2f90b4653",
"version": "0.35.0-nightly.20260311.657f19c1f",
"license": "Apache-2.0",
"dependencies": {
"@google/gemini-cli-core": "file:../core",
@@ -17998,7 +17471,7 @@
},
"packages/test-utils": {
"name": "@google/gemini-cli-test-utils",
"version": "0.36.0-nightly.20260317.2f90b4653",
"version": "0.35.0-nightly.20260311.657f19c1f",
"license": "Apache-2.0",
"dependencies": {
"@google/gemini-cli-core": "file:../core",
@@ -18015,7 +17488,7 @@
},
"packages/vscode-ide-companion": {
"name": "gemini-cli-vscode-ide-companion",
"version": "0.36.0-nightly.20260317.2f90b4653",
"version": "0.35.0-nightly.20260311.657f19c1f",
"license": "LICENSE",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.23.0",
+2 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@google/gemini-cli",
"version": "0.36.0-nightly.20260317.2f90b4653",
"version": "0.35.0-nightly.20260311.657f19c1f",
"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.36.0-nightly.20260317.2f90b4653"
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.35.0-nightly.20260311.657f19c1f"
},
"scripts": {
"start": "cross-env NODE_ENV=development node scripts/start.js",
@@ -43,7 +43,6 @@
"test:ci": "npm run test:ci --workspaces --if-present && npm run test:scripts && npm run test:sea-launch",
"test:scripts": "vitest run --config ./scripts/tests/vitest.config.ts",
"test:sea-launch": "vitest run sea/sea-launch.test.js",
"posttest": "npm run build",
"test:always_passing_evals": "vitest run --config evals/vitest.config.ts",
"test:all_evals": "cross-env RUN_EVALS=1 vitest run --config evals/vitest.config.ts",
"test:e2e": "cross-env VERBOSE=true KEEP_OUTPUT=true npm run test:integration:sandbox:none",
-22
View File
@@ -1,22 +0,0 @@
# Gemini CLI A2A Server (`@google/gemini-cli-a2a-server`)
Experimental Agent-to-Agent (A2A) server that exposes Gemini CLI capabilities
over HTTP for inter-agent communication.
## Architecture
- `src/agent/`: Agent session management for A2A interactions.
- `src/commands/`: CLI command definitions for the A2A server binary.
- `src/config/`: Server configuration.
- `src/http/`: HTTP server and route handlers.
- `src/persistence/`: Session and state persistence.
- `src/utils/`: Shared utility functions.
- `src/types.ts`: Shared type definitions.
## Running
- Binary entry point: `gemini-cli-a2a-server`
## Testing
- Run tests: `npm test -w @google/gemini-cli-a2a-server`
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@google/gemini-cli-a2a-server",
"version": "0.36.0-nightly.20260317.2f90b4653",
"version": "0.35.0-nightly.20260311.657f19c1f",
"description": "Gemini CLI A2A Server",
"repository": {
"type": "git",
@@ -177,13 +177,10 @@ describe('a2a-server memory commands', () => {
expect.any(AbortSignal),
undefined,
{
shellExecutionConfig: {
sanitizationConfig: {
allowedEnvironmentVariables: [],
blockedEnvironmentVariables: [],
enableEnvironmentVariableRedaction: false,
},
sandboxManager: undefined,
sanitizationConfig: {
allowedEnvironmentVariables: [],
blockedEnvironmentVariables: [],
enableEnvironmentVariableRedaction: false,
},
},
);
+1 -4
View File
@@ -103,10 +103,7 @@ export class AddMemoryCommand implements Command {
const abortController = new AbortController();
const signal = abortController.signal;
await tool.buildAndExecute(result.toolArgs, signal, undefined, {
shellExecutionConfig: {
sanitizationConfig: DEFAULT_SANITIZATION_CONFIG,
sandboxManager: loopContext.sandboxManager,
},
sanitizationConfig: DEFAULT_SANITIZATION_CONFIG,
});
await refreshMemory(context.config);
return {
@@ -19,8 +19,6 @@ import {
AuthType,
isHeadlessMode,
FatalAuthenticationError,
PolicyDecision,
PRIORITY_YOLO_ALLOW_ALL,
} from '@google/gemini-cli-core';
// Mock dependencies
@@ -327,29 +325,6 @@ describe('loadConfig', () => {
);
});
it('should pass enableAgents to Config constructor', async () => {
const settings: Settings = {
experimental: {
enableAgents: false,
},
};
await loadConfig(settings, mockExtensionLoader, taskId);
expect(Config).toHaveBeenCalledWith(
expect.objectContaining({
enableAgents: false,
}),
);
});
it('should default enableAgents to true when not provided', async () => {
await loadConfig(mockSettings, mockExtensionLoader, taskId);
expect(Config).toHaveBeenCalledWith(
expect.objectContaining({
enableAgents: true,
}),
);
});
describe('interactivity', () => {
it('should set interactive true when not headless', async () => {
vi.mocked(isHeadlessMode).mockReturnValue(false);
@@ -374,41 +349,6 @@ describe('loadConfig', () => {
});
});
describe('YOLO mode', () => {
it('should enable YOLO mode and add policy rule when GEMINI_YOLO_MODE is true', async () => {
vi.stubEnv('GEMINI_YOLO_MODE', 'true');
await loadConfig(mockSettings, mockExtensionLoader, taskId);
expect(Config).toHaveBeenCalledWith(
expect.objectContaining({
approvalMode: 'yolo',
policyEngineConfig: expect.objectContaining({
rules: expect.arrayContaining([
expect.objectContaining({
decision: PolicyDecision.ALLOW,
priority: PRIORITY_YOLO_ALLOW_ALL,
modes: ['yolo'],
allowRedirection: true,
}),
]),
}),
}),
);
});
it('should use default approval mode and empty rules when GEMINI_YOLO_MODE is not true', async () => {
vi.stubEnv('GEMINI_YOLO_MODE', 'false');
await loadConfig(mockSettings, mockExtensionLoader, taskId);
expect(Config).toHaveBeenCalledWith(
expect.objectContaining({
approvalMode: 'default',
policyEngineConfig: expect.objectContaining({
rules: [],
}),
}),
);
});
});
describe('authentication fallback', () => {
beforeEach(() => {
vi.stubEnv('USE_CCPA', 'true');
+4 -22
View File
@@ -26,8 +26,6 @@ import {
isHeadlessMode,
FatalAuthenticationError,
isCloudShell,
PolicyDecision,
PRIORITY_YOLO_ALLOW_ALL,
type TelemetryTarget,
type ConfigParameters,
type ExtensionLoader,
@@ -62,11 +60,6 @@ export async function loadConfig(
}
}
const approvalMode =
process.env['GEMINI_YOLO_MODE'] === 'true'
? ApprovalMode.YOLO
: ApprovalMode.DEFAULT;
const configParams: ConfigParameters = {
sessionId: taskId,
clientName: 'a2a-server',
@@ -81,20 +74,10 @@ export async function loadConfig(
excludeTools: settings.excludeTools || settings.tools?.exclude || undefined,
allowedTools: settings.allowedTools || settings.tools?.allowed || undefined,
showMemoryUsage: settings.showMemoryUsage || false,
approvalMode,
policyEngineConfig: {
rules:
approvalMode === ApprovalMode.YOLO
? [
{
decision: PolicyDecision.ALLOW,
priority: PRIORITY_YOLO_ALLOW_ALL,
modes: [ApprovalMode.YOLO],
allowRedirection: true,
},
]
: [],
},
approvalMode:
process.env['GEMINI_YOLO_MODE'] === 'true'
? ApprovalMode.YOLO
: ApprovalMode.DEFAULT,
mcpServers: settings.mcpServers,
cwd: workspaceDir,
telemetry: {
@@ -127,7 +110,6 @@ export async function loadConfig(
interactive: !isHeadlessMode(),
enableInteractiveShell: !isHeadlessMode(),
ptyInfo: 'auto',
enableAgents: settings.experimental?.enableAgents ?? true,
};
const fileService = new FileDiscoveryService(workspaceDir, {
@@ -112,18 +112,6 @@ describe('loadSettings', () => {
expect(result.fileFiltering?.respectGitIgnore).toBe(true);
});
it('should load experimental settings correctly', () => {
const settings = {
experimental: {
enableAgents: true,
},
};
fs.writeFileSync(USER_SETTINGS_PATH, JSON.stringify(settings));
const result = loadSettings(mockWorkspaceDir);
expect(result.experimental?.enableAgents).toBe(true);
});
it('should overwrite top-level settings from workspace (shallow merge)', () => {
const userSettings = {
showMemoryUsage: false,
@@ -48,9 +48,6 @@ export interface Settings {
enableRecursiveFileSearch?: boolean;
customIgnoreFilePaths?: string[];
};
experimental?: {
enableAgents?: boolean;
};
}
export interface SettingsError {
@@ -21,9 +21,7 @@ import {
tmpdir,
type Config,
type Storage,
NoopSandboxManager,
type ToolRegistry,
type SandboxManager,
} from '@google/gemini-cli-core';
import { createMockMessageBus } from '@google/gemini-cli-core/src/test-utils/mock-message-bus.js';
import { expect, vi } from 'vitest';
@@ -99,15 +97,6 @@ export function createMockConfig(
}),
getGitService: vi.fn(),
validatePathAccess: vi.fn().mockReturnValue(undefined),
getShellExecutionConfig: vi.fn().mockReturnValue({
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
sandboxManager: new NoopSandboxManager() as unknown as SandboxManager,
sanitizationConfig: {
allowedEnvironmentVariables: [],
blockedEnvironmentVariables: [],
enableEnvironmentVariableRedaction: false,
},
}),
...overrides,
} as unknown as Config;
+1 -1
View File
@@ -5,7 +5,7 @@
- Always fix react-hooks/exhaustive-deps lint errors by adding the missing
dependencies.
- **Shortcuts**: only define keyboard shortcuts in
`packages/cli/src/ui/key/keyBindings.ts`
`packages/cli/src/config/keyBindings.ts`
- Do not implement any logic performing custom string measurement or string
truncation. Use Ink layout instead leveraging ResizeObserver as needed.
- Avoid prop drilling when at all possible.
+2 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@google/gemini-cli",
"version": "0.36.0-nightly.20260317.2f90b4653",
"version": "0.35.0-nightly.20260311.657f19c1f",
"description": "Gemini CLI",
"license": "Apache-2.0",
"repository": {
@@ -20,14 +20,13 @@
"format": "prettier --write .",
"test": "vitest run",
"test:ci": "vitest run",
"posttest": "npm run build",
"typecheck": "tsc --noEmit"
},
"files": [
"dist"
],
"config": {
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.36.0-nightly.20260317.2f90b4653"
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.35.0-nightly.20260311.657f19c1f"
},
"dependencies": {
"@agentclientprotocol/sdk": "^0.12.0",
-57
View File
@@ -176,7 +176,6 @@ describe('GeminiAgent', () => {
getGemini31LaunchedSync: vi.fn().mockReturnValue(false),
getHasAccessToPreviewModel: vi.fn().mockReturnValue(false),
getCheckpointingEnabled: vi.fn().mockReturnValue(false),
getDisableAlwaysAllow: vi.fn().mockReturnValue(false),
} as unknown as Mocked<Awaited<ReturnType<typeof loadCliConfig>>>;
mockSettings = {
merged: {
@@ -655,7 +654,6 @@ describe('Session', () => {
getCheckpointingEnabled: vi.fn().mockReturnValue(false),
getGitService: vi.fn().mockResolvedValue({} as GitService),
waitForMcpInit: vi.fn(),
getDisableAlwaysAllow: vi.fn().mockReturnValue(false),
} as unknown as Mocked<Config>;
mockConnection = {
sessionUpdate: vi.fn(),
@@ -949,61 +947,6 @@ describe('Session', () => {
);
});
it('should exclude always allow options when disableAlwaysAllow is true', async () => {
mockConfig.getDisableAlwaysAllow = vi.fn().mockReturnValue(true);
const confirmationDetails = {
type: 'info',
onConfirm: vi.fn(),
};
mockTool.build.mockReturnValue({
getDescription: () => 'Test Tool',
toolLocations: () => [],
shouldConfirmExecute: vi.fn().mockResolvedValue(confirmationDetails),
execute: vi.fn().mockResolvedValue({ llmContent: 'Tool Result' }),
});
mockConnection.requestPermission.mockResolvedValue({
outcome: {
outcome: 'selected',
optionId: ToolConfirmationOutcome.ProceedOnce,
},
});
const stream1 = createMockStream([
{
type: StreamEventType.CHUNK,
value: {
functionCalls: [{ name: 'test_tool', args: {} }],
},
},
]);
const stream2 = createMockStream([
{
type: StreamEventType.CHUNK,
value: { candidates: [] },
},
]);
mockChat.sendMessageStream
.mockResolvedValueOnce(stream1)
.mockResolvedValueOnce(stream2);
await session.prompt({
sessionId: 'session-1',
prompt: [{ type: 'text', text: 'Call tool' }],
});
expect(mockConnection.requestPermission).toHaveBeenCalledWith(
expect.objectContaining({
options: expect.not.arrayContaining([
expect.objectContaining({
optionId: ToolConfirmationOutcome.ProceedAlways,
}),
]),
}),
);
});
it('should use filePath for ACP diff content in permission request', async () => {
const confirmationDetails = {
type: 'edit',
+38 -56
View File
@@ -908,7 +908,7 @@ export class Session {
const params: acp.RequestPermissionRequest = {
sessionId: this.id,
options: toPermissionOptions(confirmationDetails, this.config),
options: toPermissionOptions(confirmationDetails),
toolCall: {
toolCallId: callId,
status: 'pending',
@@ -1004,7 +1004,6 @@ export class Session {
callId,
toolResult.llmContent,
this.config.getActiveModel(),
this.config,
),
resultDisplay: toolResult.returnDisplay,
error: undefined,
@@ -1018,7 +1017,6 @@ export class Session {
callId,
toolResult.llmContent,
this.config.getActiveModel(),
this.config,
);
} catch (e) {
const error = e instanceof Error ? e : new Error(String(e));
@@ -1459,76 +1457,60 @@ const basicPermissionOptions = [
function toPermissionOptions(
confirmation: ToolCallConfirmationDetails,
config: Config,
): acp.PermissionOption[] {
const disableAlwaysAllow = config.getDisableAlwaysAllow();
const options: acp.PermissionOption[] = [];
if (!disableAlwaysAllow) {
switch (confirmation.type) {
case 'edit':
options.push({
switch (confirmation.type) {
case 'edit':
return [
{
optionId: ToolConfirmationOutcome.ProceedAlways,
name: 'Allow All Edits',
kind: 'allow_always',
});
break;
case 'exec':
options.push({
},
...basicPermissionOptions,
];
case 'exec':
return [
{
optionId: ToolConfirmationOutcome.ProceedAlways,
name: `Always Allow ${confirmation.rootCommand}`,
kind: 'allow_always',
});
break;
case 'mcp':
options.push(
{
optionId: ToolConfirmationOutcome.ProceedAlwaysServer,
name: `Always Allow ${confirmation.serverName}`,
kind: 'allow_always',
},
{
optionId: ToolConfirmationOutcome.ProceedAlwaysTool,
name: `Always Allow ${confirmation.toolName}`,
kind: 'allow_always',
},
);
break;
case 'info':
options.push({
},
...basicPermissionOptions,
];
case 'mcp':
return [
{
optionId: ToolConfirmationOutcome.ProceedAlwaysServer,
name: `Always Allow ${confirmation.serverName}`,
kind: 'allow_always',
},
{
optionId: ToolConfirmationOutcome.ProceedAlwaysTool,
name: `Always Allow ${confirmation.toolName}`,
kind: 'allow_always',
},
...basicPermissionOptions,
];
case 'info':
return [
{
optionId: ToolConfirmationOutcome.ProceedAlways,
name: `Always Allow`,
kind: 'allow_always',
});
break;
case 'ask_user':
case 'exit_plan_mode':
// askuser and exit_plan_mode don't need "always allow" options
break;
default:
// No "always allow" options for other types
break;
}
}
options.push(...basicPermissionOptions);
// Exhaustive check
switch (confirmation.type) {
case 'edit':
case 'exec':
case 'mcp':
case 'info':
},
...basicPermissionOptions,
];
case 'ask_user':
// askuser doesn't need "always allow" options since it's asking questions
return [...basicPermissionOptions];
case 'exit_plan_mode':
break;
// exit_plan_mode doesn't need "always allow" options since it's a plan approval flow
return [...basicPermissionOptions];
default: {
const unreachable: never = confirmation;
throw new Error(`Unexpected: ${unreachable}`);
}
}
return options;
}
/**
+2 -5
View File
@@ -4,16 +4,13 @@
* SPDX-License-Identifier: Apache-2.0
*/
import {
listExtensions,
type Config,
getErrorMessage,
} from '@google/gemini-cli-core';
import { listExtensions, type Config } from '@google/gemini-cli-core';
import { SettingScope } from '../../config/settings.js';
import {
ExtensionManager,
inferInstallMetadata,
} from '../../config/extension-manager.js';
import { getErrorMessage } from '../../utils/errors.js';
import { McpServerEnablementManager } from '../../config/mcp/mcpServerEnablement.js';
import { stat } from 'node:fs/promises';
import type {
+1 -4
View File
@@ -104,10 +104,7 @@ export class AddMemoryCommand implements Command {
await context.sendMessage(`Saving memory via ${result.toolName}...`);
await tool.buildAndExecute(result.toolArgs, signal, undefined, {
shellExecutionConfig: {
sanitizationConfig: DEFAULT_SANITIZATION_CONFIG,
sandboxManager: context.config.sandboxManager,
},
sanitizationConfig: DEFAULT_SANITIZATION_CONFIG,
});
await refreshMemory(context.config);
return {
@@ -22,7 +22,7 @@ import {
SettingScope,
type LoadedSettings,
} from '../../config/settings.js';
import { getErrorMessage } from '@google/gemini-cli-core';
import { getErrorMessage } from '../../utils/errors.js';
// Mock dependencies
const emitConsoleLog = vi.hoisted(() => vi.fn());
@@ -44,12 +44,12 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => {
emitConsoleLog,
},
debugLogger,
getErrorMessage: vi.fn(),
};
});
vi.mock('../../config/extension-manager.js');
vi.mock('../../config/settings.js');
vi.mock('../../utils/errors.js');
vi.mock('../../config/extensions/consent.js', () => ({
requestConsentNonInteractive: vi.fn(),
}));
@@ -6,7 +6,8 @@
import { type CommandModule } from 'yargs';
import { loadSettings, SettingScope } from '../../config/settings.js';
import { debugLogger, getErrorMessage } from '@google/gemini-cli-core';
import { getErrorMessage } from '../../utils/errors.js';
import { debugLogger } from '@google/gemini-cli-core';
import { ExtensionManager } from '../../config/extension-manager.js';
import { requestConsentNonInteractive } from '../../config/extensions/consent.js';
import { promptForSetting } from '../../config/extensions/extensionSettings.js';
@@ -137,7 +137,6 @@ describe('handleInstall', () => {
mcps: [],
hooks: [],
skills: [],
agents: [],
settings: [],
securityWarnings: [],
discoveryErrors: [],
@@ -380,7 +379,6 @@ describe('handleInstall', () => {
mcps: [],
hooks: [],
skills: ['cool-skill'],
agents: ['cool-agent'],
settings: [],
securityWarnings: ['Security risk!'],
discoveryErrors: ['Read error'],
@@ -410,10 +408,6 @@ describe('handleInstall', () => {
expect.stringContaining('cool-skill'),
false,
);
expect(mockPromptForConsentNonInteractive).toHaveBeenCalledWith(
expect.stringContaining('cool-agent'),
false,
);
expect(mockPromptForConsentNonInteractive).toHaveBeenCalledWith(
expect.stringContaining('Security Warnings:'),
false,
@@ -11,8 +11,8 @@ import {
debugLogger,
FolderTrustDiscoveryService,
getRealPath,
getErrorMessage,
} from '@google/gemini-cli-core';
import { getErrorMessage } from '../../utils/errors.js';
import {
INSTALL_WARNING_MESSAGE,
promptForConsentNonInteractive,
@@ -99,15 +99,11 @@ export async function handleInstall(args: InstallArgs) {
if (hasDiscovery) {
promptLines.push(chalk.bold('This folder contains:'));
const groups = [
{ label: 'Commands', items: discoveryResults.commands ?? [] },
{ label: 'MCP Servers', items: discoveryResults.mcps ?? [] },
{ label: 'Hooks', items: discoveryResults.hooks ?? [] },
{ label: 'Skills', items: discoveryResults.skills ?? [] },
{ label: 'Agents', items: discoveryResults.agents ?? [] },
{
label: 'Setting overrides',
items: discoveryResults.settings ?? [],
},
{ label: 'Commands', items: discoveryResults.commands },
{ label: 'MCP Servers', items: discoveryResults.mcps },
{ label: 'Hooks', items: discoveryResults.hooks },
{ label: 'Skills', items: discoveryResults.skills },
{ label: 'Setting overrides', items: discoveryResults.settings },
].filter((g) => g.items.length > 0);
for (const group of groups) {
@@ -13,24 +13,26 @@ import {
afterEach,
type Mock,
} from 'vitest';
import { coreEvents, getErrorMessage } from '@google/gemini-cli-core';
import { coreEvents } from '@google/gemini-cli-core';
import { type Argv } from 'yargs';
import { handleLink, linkCommand } from './link.js';
import { ExtensionManager } from '../../config/extension-manager.js';
import { loadSettings, type LoadedSettings } from '../../config/settings.js';
import { getErrorMessage } from '../../utils/errors.js';
vi.mock('@google/gemini-cli-core', async (importOriginal) => {
const { mockCoreDebugLogger } = await import(
'../../test-utils/mockDebugLogger.js'
);
const actual =
await importOriginal<typeof import('@google/gemini-cli-core')>();
const mocked = mockCoreDebugLogger(actual, { stripAnsi: true });
return { ...mocked, getErrorMessage: vi.fn() };
return mockCoreDebugLogger(
await importOriginal<typeof import('@google/gemini-cli-core')>(),
{ stripAnsi: true },
);
});
vi.mock('../../config/extension-manager.js');
vi.mock('../../config/settings.js');
vi.mock('../../utils/errors.js');
vi.mock('../../config/extensions/consent.js', () => ({
requestConsentNonInteractive: vi.fn(),
}));
+1 -1
View File
@@ -8,10 +8,10 @@ import type { CommandModule } from 'yargs';
import chalk from 'chalk';
import {
debugLogger,
getErrorMessage,
type ExtensionInstallMetadata,
} from '@google/gemini-cli-core';
import { getErrorMessage } from '../../utils/errors.js';
import {
INSTALL_WARNING_MESSAGE,
requestConsentNonInteractive,
@@ -5,23 +5,27 @@
*/
import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
import { coreEvents, getErrorMessage } from '@google/gemini-cli-core';
import { coreEvents } from '@google/gemini-cli-core';
import { handleList, listCommand } from './list.js';
import { ExtensionManager } from '../../config/extension-manager.js';
import { loadSettings, type LoadedSettings } from '../../config/settings.js';
import { getErrorMessage } from '../../utils/errors.js';
vi.mock('@google/gemini-cli-core', async (importOriginal) => {
const { mockCoreDebugLogger } = await import(
'../../test-utils/mockDebugLogger.js'
);
const actual =
await importOriginal<typeof import('@google/gemini-cli-core')>();
const mocked = mockCoreDebugLogger(actual, { stripAnsi: false });
return { ...mocked, getErrorMessage: vi.fn() };
return mockCoreDebugLogger(
await importOriginal<typeof import('@google/gemini-cli-core')>(),
{
stripAnsi: false,
},
);
});
vi.mock('../../config/extension-manager.js');
vi.mock('../../config/settings.js');
vi.mock('../../utils/errors.js');
vi.mock('../../config/extensions/consent.js', () => ({
requestConsentNonInteractive: vi.fn(),
}));
+2 -1
View File
@@ -5,7 +5,8 @@
*/
import type { CommandModule } from 'yargs';
import { debugLogger, getErrorMessage } from '@google/gemini-cli-core';
import { getErrorMessage } from '../../utils/errors.js';
import { debugLogger } from '@google/gemini-cli-core';
import { ExtensionManager } from '../../config/extension-manager.js';
import { requestConsentNonInteractive } from '../../config/extensions/consent.js';
import { loadSettings } from '../../config/settings.js';
@@ -18,7 +18,7 @@ import { type Argv } from 'yargs';
import { handleUninstall, uninstallCommand } from './uninstall.js';
import { ExtensionManager } from '../../config/extension-manager.js';
import { loadSettings, type LoadedSettings } from '../../config/settings.js';
import { getErrorMessage } from '@google/gemini-cli-core';
import { getErrorMessage } from '../../utils/errors.js';
// NOTE: This file uses vi.hoisted() mocks to enable testing of sequential
// mock behaviors (mockResolvedValueOnce/mockRejectedValueOnce chaining).
@@ -66,11 +66,11 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => {
emitConsoleLog,
},
debugLogger,
getErrorMessage: vi.fn(),
};
});
vi.mock('../../config/settings.js');
vi.mock('../../utils/errors.js');
vi.mock('../../config/extensions/consent.js', () => ({
requestConsentNonInteractive: vi.fn(),
}));
@@ -5,7 +5,8 @@
*/
import type { CommandModule } from 'yargs';
import { debugLogger, getErrorMessage } from '@google/gemini-cli-core';
import { getErrorMessage } from '../../utils/errors.js';
import { debugLogger } from '@google/gemini-cli-core';
import { requestConsentNonInteractive } from '../../config/extensions/consent.js';
import { ExtensionManager } from '../../config/extension-manager.js';
import { loadSettings } from '../../config/settings.js';
@@ -12,12 +12,9 @@ import {
updateExtension,
} from '../../config/extensions/update.js';
import { checkForExtensionUpdate } from '../../config/extensions/github.js';
import { getErrorMessage } from '../../utils/errors.js';
import { ExtensionUpdateState } from '../../ui/state/extensions.js';
import {
coreEvents,
debugLogger,
getErrorMessage,
} from '@google/gemini-cli-core';
import { coreEvents, debugLogger } from '@google/gemini-cli-core';
import { ExtensionManager } from '../../config/extension-manager.js';
import { requestConsentNonInteractive } from '../../config/extensions/consent.js';
import { loadSettings } from '../../config/settings.js';
@@ -5,10 +5,11 @@
*/
import type { CommandModule } from 'yargs';
import { debugLogger, getErrorMessage } from '@google/gemini-cli-core';
import { debugLogger } from '@google/gemini-cli-core';
import * as fs from 'node:fs';
import * as path from 'node:path';
import semver from 'semver';
import { getErrorMessage } from '../../utils/errors.js';
import type { ExtensionConfig } from '../../config/extension.js';
import { ExtensionManager } from '../../config/extension-manager.js';
import { requestConsentNonInteractive } from '../../config/extensions/consent.js';
@@ -28,9 +28,6 @@ const { debugLogger, emitConsoleLog } = await vi.hoisted(async () => {
vi.mock('@google/gemini-cli-core', () => ({
debugLogger,
getErrorMessage: vi.fn((e: unknown) =>
e instanceof Error ? e.message : String(e),
),
}));
import { handleInstall, installCommand } from './install.js';
+2 -5
View File
@@ -5,11 +5,8 @@
*/
import type { CommandModule } from 'yargs';
import {
debugLogger,
type SkillDefinition,
getErrorMessage,
} from '@google/gemini-cli-core';
import { debugLogger, type SkillDefinition } from '@google/gemini-cli-core';
import { getErrorMessage } from '../../utils/errors.js';
import { exitCli } from '../utils.js';
import { installSkill } from '../../utils/skillUtils.js';
import chalk from 'chalk';
@@ -24,9 +24,6 @@ const { debugLogger } = await vi.hoisted(async () => {
vi.mock('@google/gemini-cli-core', () => ({
debugLogger,
getErrorMessage: vi.fn((e: unknown) =>
e instanceof Error ? e.message : String(e),
),
}));
vi.mock('../../config/extensions/consent.js', () => ({
+2 -1
View File
@@ -5,9 +5,10 @@
*/
import type { CommandModule } from 'yargs';
import { debugLogger, getErrorMessage } from '@google/gemini-cli-core';
import { debugLogger } from '@google/gemini-cli-core';
import chalk from 'chalk';
import { getErrorMessage } from '../../utils/errors.js';
import { exitCli } from '../utils.js';
import {
requestConsentNonInteractive,
@@ -21,9 +21,6 @@ const { debugLogger, emitConsoleLog } = await vi.hoisted(async () => {
vi.mock('@google/gemini-cli-core', () => ({
debugLogger,
getErrorMessage: vi.fn((e: unknown) =>
e instanceof Error ? e.message : String(e),
),
}));
import { handleUninstall, uninstallCommand } from './uninstall.js';
@@ -5,7 +5,8 @@
*/
import type { CommandModule } from 'yargs';
import { debugLogger, getErrorMessage } from '@google/gemini-cli-core';
import { debugLogger } from '@google/gemini-cli-core';
import { getErrorMessage } from '../../utils/errors.js';
import { exitCli } from '../utils.js';
import { uninstallSkill } from '../../utils/skillUtils.js';
import chalk from 'chalk';
+6 -57
View File
@@ -763,48 +763,6 @@ describe('loadCliConfig', () => {
});
});
it('should add IDE workspace folders from GEMINI_CLI_IDE_WORKSPACE_PATH to include directories', async () => {
vi.stubEnv(
'GEMINI_CLI_IDE_WORKSPACE_PATH',
['/project/folderA', '/project/folderB'].join(path.delimiter),
);
process.argv = ['node', 'script.js'];
const argv = await parseArguments(createTestMergedSettings());
const settings = createTestMergedSettings();
const config = await loadCliConfig(settings, 'test-session', argv);
const dirs = config.getPendingIncludeDirectories();
expect(dirs).toContain('/project/folderA');
expect(dirs).toContain('/project/folderB');
});
it('should skip inaccessible workspace folders from GEMINI_CLI_IDE_WORKSPACE_PATH', async () => {
const resolveToRealPathSpy = vi
.spyOn(ServerConfig, 'resolveToRealPath')
.mockImplementation((p) => {
if (p.toString().includes('restricted')) {
const err = new Error('EACCES: permission denied');
(err as NodeJS.ErrnoException).code = 'EACCES';
throw err;
}
return p.toString();
});
vi.stubEnv(
'GEMINI_CLI_IDE_WORKSPACE_PATH',
['/project/folderA', '/nonexistent/restricted/folder'].join(
path.delimiter,
),
);
process.argv = ['node', 'script.js'];
const argv = await parseArguments(createTestMergedSettings());
const settings = createTestMergedSettings();
const config = await loadCliConfig(settings, 'test-session', argv);
const dirs = config.getPendingIncludeDirectories();
expect(dirs).toContain('/project/folderA');
expect(dirs).not.toContain('/nonexistent/restricted/folder');
resolveToRealPathSpy.mockRestore();
});
it('should use default fileFilter options when unconfigured', async () => {
process.argv = ['node', 'script.js'];
const argv = await parseArguments(createTestMergedSettings());
@@ -840,7 +798,6 @@ describe('loadCliConfig', () => {
describe('Hierarchical Memory Loading (config.ts) - Placeholder Suite', () => {
beforeEach(() => {
vi.resetAllMocks();
vi.stubEnv('GEMINI_CLI_IDE_WORKSPACE_PATH', '');
// Restore ExtensionManager mocks that were reset
ExtensionManager.prototype.getExtensions = vi.fn().mockReturnValue([]);
ExtensionManager.prototype.loadExtensions = vi
@@ -852,15 +809,12 @@ describe('Hierarchical Memory Loading (config.ts) - Placeholder Suite', () => {
});
afterEach(() => {
vi.unstubAllEnvs();
vi.restoreAllMocks();
});
it('should pass extension context file paths to loadServerHierarchicalMemory', async () => {
process.argv = ['node', 'script.js'];
const settings = createTestMergedSettings({
experimental: { jitContext: false },
});
const settings = createTestMergedSettings();
vi.spyOn(ExtensionManager.prototype, 'getExtensions').mockReturnValue([
{
path: '/path/to/ext1',
@@ -911,7 +865,6 @@ describe('Hierarchical Memory Loading (config.ts) - Placeholder Suite', () => {
process.argv = ['node', 'script.js'];
const includeDir = path.resolve(path.sep, 'path', 'to', 'include');
const settings = createTestMergedSettings({
experimental: { jitContext: false },
context: {
includeDirectories: [includeDir],
loadMemoryFromIncludeDirectories: true,
@@ -939,7 +892,6 @@ describe('Hierarchical Memory Loading (config.ts) - Placeholder Suite', () => {
it('should NOT pass includeDirectories to loadServerHierarchicalMemory when loadMemoryFromIncludeDirectories is false', async () => {
process.argv = ['node', 'script.js'];
const settings = createTestMergedSettings({
experimental: { jitContext: false },
context: {
includeDirectories: ['/path/to/include'],
loadMemoryFromIncludeDirectories: false,
@@ -1821,7 +1773,7 @@ describe('loadCliConfig model selection', () => {
});
it('always prefers model from argv', async () => {
process.argv = ['node', 'script.js', '--model', 'gemini-2.5-flash-preview'];
process.argv = ['node', 'script.js', '--model', 'gemini-2.5-flash'];
const argv = await parseArguments(createTestMergedSettings());
const config = await loadCliConfig(
createTestMergedSettings({
@@ -1833,11 +1785,11 @@ describe('loadCliConfig model selection', () => {
argv,
);
expect(config.getModel()).toBe('gemini-2.5-flash-preview');
expect(config.getModel()).toBe('gemini-2.5-flash');
});
it('selects the model from argv if provided', async () => {
process.argv = ['node', 'script.js', '--model', 'gemini-2.5-flash-preview'];
process.argv = ['node', 'script.js', '--model', 'gemini-2.5-flash'];
const argv = await parseArguments(createTestMergedSettings());
const config = await loadCliConfig(
createTestMergedSettings({
@@ -1847,7 +1799,7 @@ describe('loadCliConfig model selection', () => {
argv,
);
expect(config.getModel()).toBe('gemini-2.5-flash-preview');
expect(config.getModel()).toBe('gemini-2.5-flash');
});
it('selects the default auto model if provided via auto alias', async () => {
@@ -3391,10 +3343,7 @@ describe('Policy Engine Integration in loadCliConfig', () => {
expect(ServerConfig.createPolicyEngineConfig).toHaveBeenCalledWith(
expect.objectContaining({
policyPaths: [
path.normalize('/path/to/policy1.toml'),
path.normalize('/path/to/policy2.toml'),
],
policyPaths: ['/path/to/policy1.toml', '/path/to/policy2.toml'],
}),
expect.anything(),
);
+81 -57
View File
@@ -31,6 +31,8 @@ import {
type HierarchicalMemory,
coreEvents,
GEMINI_MODEL_ALIAS_AUTO,
isValidModelOrAlias,
getValidModelsAndAliases,
getAdminErrorMessage,
isHeadlessMode,
Config,
@@ -125,19 +127,12 @@ export async function parseArguments(
.usage(
'Usage: gemini [options] [command]\n\nGemini CLI - Defaults to interactive mode. Use -p/--prompt for non-interactive (headless) mode.',
)
if (settings.experimental?.extensionManagement) {
yargsInstance.command(extensionsCommand);
}
if (settings.skills?.enabled ?? true) {
yargsInstance.command(skillsCommand);
}
// Register hooks command if hooks are enabled
if (settings.hooksConfig.enabled) {
yargsInstance.command(hooksCommand);
}
yargsInstance
.option('debug', {
alias: 'd',
type: 'boolean',
description: 'Run in debug mode (open debug console with F12)',
default: false,
})
.command('$0 [query..]', 'Launch Gemini CLI', (yargsInstance) =>
yargsInstance
.positional('query', {
@@ -251,11 +246,10 @@ export async function parseArguments(
// When --resume passed without a value (`gemini --resume`): value = "" (string)
// When --resume not passed at all: this `coerce` function is not called at all, and
// `yargsInstance.argv.resume` is undefined.
const trimmed = value.trim();
if (trimmed === '') {
if (value === '') {
return RESUME_LATEST;
}
return trimmed;
return value;
},
})
.option('list-sessions', {
@@ -307,6 +301,56 @@ export async function parseArguments(
description: 'Suppress the security warning when using --raw-output.',
}),
)
// Register MCP subcommands
.command(mcpCommand)
// Ensure validation flows through .fail() for clean UX
.fail((msg, err) => {
if (err) throw err;
throw new Error(msg);
})
.check((argv) => {
// The 'query' positional can be a string (for one arg) or string[] (for multiple).
// This guard safely checks if any positional argument was provided.
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const query = argv['query'] as string | string[] | undefined;
const hasPositionalQuery = Array.isArray(query)
? query.length > 0
: !!query;
if (argv['prompt'] && hasPositionalQuery) {
return 'Cannot use both a positional prompt and the --prompt (-p) flag together';
}
if (argv['prompt'] && argv['promptInteractive']) {
return 'Cannot use both --prompt (-p) and --prompt-interactive (-i) together';
}
if (argv['yolo'] && argv['approvalMode']) {
return 'Cannot use both --yolo (-y) and --approval-mode together. Use --approval-mode=yolo instead.';
}
if (
argv['outputFormat'] &&
!['text', 'json', 'stream-json'].includes(
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
argv['outputFormat'] as string,
)
) {
return `Invalid values:\n Argument: output-format, Given: "${argv['outputFormat']}", Choices: "text", "json", "stream-json"`;
}
return true;
});
if (settings.experimental?.extensionManagement) {
yargsInstance.command(extensionsCommand);
}
if (settings.skills?.enabled ?? true) {
yargsInstance.command(skillsCommand);
}
// Register hooks command if hooks are enabled
if (settings.hooksConfig.enabled) {
yargsInstance.command(hooksCommand);
}
yargsInstance
.version(await getVersion()) // This will enable the --version flag based on package.json
.alias('v', 'version')
.help()
@@ -387,6 +431,8 @@ export async function loadCliConfig(
const { cwd = process.cwd(), projectHooks } = options;
const debugMode = isDebugMode(argv);
const loadedSettings = loadSettings(cwd);
if (argv.sandbox) {
process.env['GEMINI_SANDBOX'] = 'true';
}
@@ -430,32 +476,10 @@ export async function loadCliConfig(
...settings.context?.fileFiltering,
};
//changes the includeDirectories to be absolute paths based on the cwd, and also include any additional directories specified via CLI args
const includeDirectories = (settings.context?.includeDirectories || [])
.map(resolvePath)
.concat((argv.includeDirectories || []).map(resolvePath));
// When running inside VSCode with multiple workspace folders,
// automatically add the other folders as include directories
// so Gemini has context of all open folders, not just the cwd.
const ideWorkspacePath = process.env['GEMINI_CLI_IDE_WORKSPACE_PATH'];
if (ideWorkspacePath) {
const realCwd = resolveToRealPath(cwd);
const ideFolders = ideWorkspacePath.split(path.delimiter).filter((p) => {
const trimmedPath = p.trim();
if (!trimmedPath) return false;
try {
return resolveToRealPath(trimmedPath) !== realCwd;
} catch (e) {
debugLogger.debug(
`[IDE] Skipping inaccessible workspace folder: ${trimmedPath} (${e instanceof Error ? e.message : String(e)})`,
);
return false;
}
});
includeDirectories.push(...ideFolders);
}
const extensionManager = new ExtensionManager({
settings,
requestConsent: requestConsentNonInteractive,
@@ -472,12 +496,11 @@ export async function loadCliConfig(
.getExtensions()
.find((ext) => ext.isActive && ext.plan?.directory)?.plan;
const experimentalJitContext = settings.experimental.jitContext;
let extensionRegistryURI =
process.env['GEMINI_CLI_EXTENSION_REGISTRY_URI'] ??
(trustedFolder ? settings.experimental?.extensionRegistryURI : undefined);
const experimentalJitContext = settings.experimental?.jitContext ?? false;
let extensionRegistryURI: string | undefined = trustedFolder
? settings.experimental?.extensionRegistryURI
: undefined;
if (extensionRegistryURI && !extensionRegistryURI.startsWith('http')) {
extensionRegistryURI = resolveToRealPath(
path.resolve(cwd, resolvePath(extensionRegistryURI)),
@@ -628,12 +651,8 @@ export async function loadCliConfig(
...settings.mcp,
allowed: argv.allowedMcpServerNames ?? settings.mcp?.allowed,
},
policyPaths: (argv.policy ?? settings.policyPaths)?.map((p) =>
resolvePath(p),
),
adminPolicyPaths: (argv.adminPolicy ?? settings.adminPolicyPaths)?.map(
(p) => resolvePath(p),
),
policyPaths: argv.policy ?? settings.policyPaths,
adminPolicyPaths: argv.adminPolicy ?? settings.adminPolicyPaths,
};
const { workspacePoliciesDir, policyUpdateConfirmationRequest } =
@@ -654,6 +673,18 @@ export async function loadCliConfig(
const specifiedModel =
argv.model || process.env['GEMINI_MODEL'] || settings.model?.name;
// Validate the model if one was explicitly specified
if (specifiedModel && specifiedModel !== GEMINI_MODEL_ALIAS_AUTO) {
if (!isValidModelOrAlias(specifiedModel)) {
const validModels = getValidModelsAndAliases();
throw new FatalConfigError(
`Invalid model: "${specifiedModel}"\n\n` +
`Valid models and aliases:\n${validModels.map((m) => ` - ${m}`).join('\n')}\n\n` +
`Use /model to switch models interactively.`,
);
}
}
const resolvedModel =
specifiedModel === GEMINI_MODEL_ALIAS_AUTO
? defaultModel
@@ -713,14 +744,11 @@ export async function loadCliConfig(
clientVersion: await getVersion(),
embeddingModel: DEFAULT_GEMINI_EMBEDDING_MODEL,
sandbox: sandboxConfig,
toolSandboxing: settings.security?.toolSandboxing ?? false,
targetDir: cwd,
includeDirectoryTree,
includeDirectories,
loadMemoryFromIncludeDirectories:
settings.context?.loadMemoryFromIncludeDirectories || false,
discoveryMaxDirs: settings.context?.discoveryMaxDirs,
importFormat: settings.context?.importFormat,
debugMode,
question,
@@ -756,9 +784,6 @@ export async function loadCliConfig(
approvalMode,
disableYoloMode:
settings.security?.disableYoloMode || settings.admin?.secureModeEnabled,
disableAlwaysAllow:
settings.security?.disableAlwaysAllow ||
settings.admin?.secureModeEnabled,
showMemoryUsage: settings.ui?.showMemoryUsage || false,
accessibility: {
...settings.ui?.accessibility,
@@ -798,7 +823,6 @@ export async function loadCliConfig(
disabledSkills: settings.skills?.disabled,
experimentalJitContext: settings.experimental?.jitContext,
modelSteering: settings.experimental?.modelSteering,
topicUpdateNarration: settings.experimental?.topicUpdateNarration,
toolOutputMasking: settings.experimental?.toolOutputMasking,
noBrowser: !!process.env['NO_BROWSER'],
summarizeToolOutput: settings.model?.summarizeToolOutput,
@@ -841,7 +865,7 @@ export async function loadCliConfig(
hooks: settings.hooks || {},
disabledHooks: settings.hooksConfig?.disabled || [],
projectHooks: projectHooks || {},
onModelChange: (model: string) => saveModelChange(loadSettings(cwd), model),
onModelChange: (model: string) => saveModelChange(loadedSettings, model),
onReload: async () => {
const refreshedSettings = loadSettings(cwd);
return {
@@ -20,12 +20,7 @@ import {
import { createExtension } from '../test-utils/createExtension.js';
import { ExtensionManager } from './extension-manager.js';
import { themeManager, DEFAULT_THEME } from '../ui/themes/theme-manager.js';
import {
GEMINI_DIR,
type Config,
tmpdir,
NoopSandboxManager,
} from '@google/gemini-cli-core';
import { GEMINI_DIR, type Config, tmpdir } from '@google/gemini-cli-core';
import { createTestMergedSettings, SettingScope } from './settings.js';
describe('ExtensionManager theme loading', () => {
@@ -122,7 +117,6 @@ describe('ExtensionManager theme loading', () => {
terminalHeight: 24,
showColor: false,
pager: 'cat',
sandboxManager: new NoopSandboxManager(),
sanitizationConfig: {
allowedEnvironmentVariables: [],
blockedEnvironmentVariables: [],

Some files were not shown because too many files have changed in this diff Show More