Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- docs/CONTRIBUTING.mdAdded+571
- docs/behavioral-evals.mdAdded+185
- docs/index.mdAdded+139
- docs/integration-tests.mdAdded+293
- docs/issue-and-pr-automation.mdAdded+203
- docs/local-development.mdAdded+182
- docs/npm.mdAdded+62
- docs/redirects.jsonAdded+21
- docs/release-confidence.mdAdded+168
- docs/releases.mdAdded+550
- docs/sidebar.jsonAdded+298
- integration-tests/acp-env-auth.test.tsAdded+163
- integration-tests/acp-telemetry.test.tsAdded+116
- integration-tests/api-resilience.responsesAdded+1
- integration-tests/api-resilience.test.tsAdded+50
- integration-tests/browser-agent-localhost.multistep.responsesAdded+9
- integration-tests/browser-agent-localhost.navigate.responsesAdded+5
- integration-tests/browser-agent.cleanup.responsesAdded+5
- integration-tests/browser-agent.confirmation.responsesAdded+1
- integration-tests/browser-policy.responsesAdded+5
- integration-tests/browser-policy.test.tsAdded+240
- integration-tests/checkpointing.test.tsAdded+155
- integration-tests/concurrency-limit.responsesAdded+12
- integration-tests/context-compress-interactive.compress-empty.responsesAdded
- integration-tests/context-compress-interactive.compress-failure.responsesAdded+3
- integration-tests/context-fidelity.test.tsAdded+287
- integration-tests/extensions-install.test.tsAdded+62
- integration-tests/extensions-reload.test.tsAdded+151
- integration-tests/file-system-interactive.test.tsAdded+67
- integration-tests/flicker-detector.max-height.responsesAdded+3
- integration-tests/globalSetup.tsAdded+155
- integration-tests/google_web_search.test.tsAdded+95
- integration-tests/hooks-agent-flow-multistep.responsesAdded+2
- integration-tests/hooks-agent-flow.test.tsAdded+338
- integration-tests/hooks-system.after-agent.responsesAdded+3
- integration-tests/hooks-system.after-model.responsesAdded+1
- integration-tests/hooks-system.after-tool-context.responsesAdded+2
- integration-tests/hooks-system.allow-tool.responsesAdded+4
- integration-tests/hooks-system.before-model.responsesAdded+1
- integration-tests/hooks-system.before-tool-stop.responsesAdded+1
- integration-tests/hooks-system.compress-auto.responsesAdded+1
- integration-tests/hooks-system.input-modification.responsesAdded+2
- integration-tests/hooks-system.input-validation.responsesAdded+2
- integration-tests/hooks-system.multiple-events.responsesAdded+4
- integration-tests/hooks-system.notification.responsesAdded+1
- integration-tests/hooks-system.sequential-execution.responsesAdded+1
- integration-tests/hooks-system.session-clear.responsesAdded+1
- integration-tests/hooks-system.session-startup.responsesAdded+1
- integration-tests/hooks-system.tail-tool-call.responsesAdded+2
- integration-tests/hooks-system.telemetry.responsesAdded+2
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571# How to contribute
We would love to accept your patches and contributions to this project. Thisdocument includes:
- **[Before you begin](#before-you-begin):** Essential steps to take before becoming a Gemini CLI contributor.- **[Code contribution process](#code-contribution-process):** How to contribute code to Gemini CLI.- **[Development setup and workflow](#development-setup-and-workflow):** How to set up your development environment and workflow.- **[Documentation contribution process](#documentation-contribution-process):** How to contribute documentation to Gemini CLI.
We're looking forward to seeing your contributions!
## Before you begin
### Sign our Contributor License Agreement
Contributions to this project must be accompanied by a[Contributor License Agreement](https://cla.developers.google.com/about) (CLA).You (or your employer) retain the copyright to your contribution; this simplygives us permission to use and redistribute your contributions as part of theproject.
If you or your current employer have already signed the Google CLA (even if itwas for a different project), you probably don't need to do it again.
Visit <https://cla.developers.google.com/> to see your current agreements or tosign a new one.
### Review our Community Guidelines
This project follows[Google's Open Source Community Guidelines](https://opensource.google/conduct/).
## Code contribution process
### Get started
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. 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
All submissions, including submissions by project members, require review. Weuse [GitHub pull requests](https://docs.github.com/articles/about-pull-requests)for this purpose.
To assist with the review process, we provide an automated review tool thathelps detect common anti-patterns, testing issues, and other best practices thatare easy to miss.
#### Using the automated review tool
You can run the review tool in two ways:
1. **Using the helper script (Recommended):** We provide a script that automatically handles checking out the PR into a separate worktree, installing dependencies, building the project, and launching the review tool.
```bash ./scripts/review.sh <PR_NUMBER> [model] ```
**Warning:** If you run `scripts/review.sh`, you must have first verified that the code for the PR being reviewed is safe to run and does not contain data exfiltration attacks.
**Authors are strongly encouraged to run this script on their own PRs** immediately after creation. This allows you to catch and fix simple issues locally before a maintainer performs a full review.
**Note on Models:** By default, the script uses the latest Pro model (`gemini-3.1-pro-preview`). If you do not have enough Pro quota, you can run it with the latest Flash model instead: `./scripts/review.sh <PR_NUMBER> gemini-3-flash-preview`.
2. **Manually from within Gemini CLI:** If you already have the PR checked out and built, you can run the tool directly from the CLI prompt:
```text /review-frontend <PR_NUMBER> ```
Replace `<PR_NUMBER>` with your pull request number. Reviewers should use thistool to augment, not replace, their manual review process.
### Self-assigning and unassigning issues
To assign an issue to yourself, simply add a comment with the text `/assign`. Tounassign yourself from an issue, add a comment with the text `/unassign`.
The comment must contain only that text and nothing else. These commands willassign or unassign the issue as requested, provided the conditions are met(e.g., an issue must be unassigned to be assigned).
Please note that you can have a maximum of 3 issues assigned to you at any giventime and that only[issues labeled "help wanted"](https://github.com/google-gemini/gemini-cli/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22help%20wanted%22)may be self-assigned.
### Pull request guidelines
To help us review and merge your PRs quickly, please follow these guidelines.PRs that do not meet these standards may be closed.
#### 1. Link to an existing issue
All PRs should be linked to an existing issue in our tracker. This ensures thatevery change has been discussed and is aligned with the project's goals beforeany code is written.
- **For bug fixes:** The PR should be linked to the bug report issue.- **For features:** The PR should be linked to the feature request or proposal issue that has been approved by a maintainer.
If an issue for your change doesn't exist, we will automatically close your PRalong with a comment reminding you to associate the PR with an issue. The idealworkflow starts with an issue that has been reviewed and approved by amaintainer. Please **open the issue first** and wait for feedback before youstart coding.
#### 2. Keep it small and focused
We favor small, atomic PRs that address a single issue or add a single,self-contained feature.
- **Do:** Create a PR that fixes one specific bug or adds one specific feature.- **Don't:** Bundle multiple unrelated changes (e.g., a bug fix, a new feature, and a refactor) into a single PR.
Large changes should be broken down into a series of smaller, logical PRs thatcan be reviewed and merged independently.
#### 3. Use draft PRs for work in progress
If you'd like to get early feedback on your work, please use GitHub's **DraftPull Request** feature. This signals to the maintainers that the PR is not yetready for a formal review but is open for discussion and initial feedback.
#### 4. Ensure all checks pass
Before submitting your PR, ensure that all automated checks are passing byrunning `npm run preflight`. This command runs all tests, linting, and otherstyle checks.
#### 5. Update documentation
If your PR introduces a user-facing change (e.g., a new command, a modifiedflag, or a change in behavior), you must also update the relevant documentationin the `/docs` directory.
See more about writing documentation:[Documentation contribution process](#documentation-contribution-process).
#### 6. Write clear commit messages and a good PR description
Your PR should have a clear, descriptive title and a detailed description of thechanges. Follow the [Conventional Commits](https://www.conventionalcommits.org/)standard for your commit messages.
- **Good PR title:** `feat(cli): Add --json flag to 'config get' command`- **Bad PR title:** `Made some changes`
In the PR description, explain the "why" behind your changes and link to therelevant issue (e.g., `Fixes #123`).
### Forking
If you are forking the repository you will be able to run the Build, Test andIntegration test workflows. However in order to make the integration tests runyou'll need to add a[GitHub Repository Secret](https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions#creating-secrets-for-a-repository)with a value of `GEMINI_API_KEY` and set that to a valid API key that you haveavailable. Your key and secret are private to your repo; no one without accesscan see your key and you cannot see any secrets related to this repo.
Additionally you will need to click on the `Actions` tab and enable workflowsfor your repository, you'll find it's the large blue button in the center of thescreen.
### Development setup and workflow
This section guides contributors on how to build, modify, and understand thedevelopment setup of this project.
### Setting up the development environment
**Prerequisites:**
1. **Node.js**: - **Development:** Please use Node.js `~20.19.0`. This specific version is required due to an upstream development dependency issue. You can use a tool like [nvm](https://github.com/nvm-sh/nvm) to manage Node.js versions. - **Production:** For running the CLI in a production environment, any version of Node.js `>=20` is acceptable.2. **Git**
### Build process
To clone the repository:
```bashgit clone https://github.com/google-gemini/gemini-cli.git # Or your fork's URLcd gemini-cli```
To install dependencies defined in `package.json` as well as root dependencies:
```bashnpm install```
To build the entire project (all packages):
```bashnpm run build```
This command typically compiles TypeScript to JavaScript, bundles assets, andprepares the packages for execution. Refer to `scripts/build.js` and`package.json` scripts for more details on what happens during the build.
### Enabling sandboxing
[Sandboxing](#sandboxing) is highly recommended and requires, at a minimum,setting `GEMINI_SANDBOX=true` in your `~/.env` and ensuring a sandboxingprovider (e.g. `macOS Seatbelt`, `docker`, or `podman`) is available. See[Sandboxing](#sandboxing) for details.
To build both the `gemini` CLI utility and the sandbox container, run`build:all` from the root directory:
```bashnpm run build:all```
To skip building the sandbox container, you can use `npm run build` instead.
### Running the CLI
To start the Gemini CLI from the source code (after building), run the followingcommand from the root directory:
```bashnpm start```
If you'd like to run the source build outside of the gemini-cli folder, you canutilize `npm link path/to/gemini-cli/packages/cli` (see:[docs](https://docs.npmjs.com/cli/v9/commands/npm-link)) or`alias gemini="node path/to/gemini-cli/packages/cli"` to run with `gemini`
### Running tests
This project contains two types of tests: unit tests and integration tests.
#### Unit tests
To execute the unit test suite for the project:
```bashnpm run test```
This will run tests located in the `packages/core` and `packages/cli`directories. Ensure tests pass before submitting any changes. For a morecomprehensive check, it is recommended to run `npm run preflight`.
#### Integration tests
The integration tests are designed to validate the end-to-end functionality ofthe Gemini CLI. They are not run as part of the default `npm run test` command.
To run the integration tests, use the following command:
```bashnpm run test:e2e```
For more detailed information on the integration testing framework, please seethe[Integration Tests documentation](https://geminicli.com/docs/integration-tests).
### Linting and preflight checks
To ensure code quality and formatting consistency, run the preflight check:
```bashnpm run preflight```
This command will run ESLint, Prettier, all tests, and other checks as definedin the project's `package.json`.
_ProTip_
after cloning create a git precommit hook file to ensure your commits are alwaysclean.
```bashecho "# Run npm build and check for errorsif ! npm run preflight; then echo "npm build failed. Commit aborted." exit 1fi" > .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit```
#### Formatting
To separately format the code in this project, run the following command fromthe root directory:
```bashnpm run format```
This command uses Prettier to format the code according to the project's styleguidelines.
#### Linting
To separately lint the code in this project, run the following command from theroot directory:
```bashnpm run lint```
### Coding conventions
- Please adhere to the coding style, patterns, and conventions used throughout the existing codebase.- Consult [GEMINI.md](https://github.com/google-gemini/gemini-cli/blob/main/GEMINI.md) (typically found in the project root) for specific instructions related to AI-assisted development, including conventions for React, comments, and Git usage.- **Imports:** Pay special attention to import paths. The project uses ESLint to enforce restrictions on relative imports between packages.
### Debugging
#### VS Code
0. Run the CLI to interactively debug in VS Code with `F5`1. Start the CLI in debug mode from the root directory: ```bash npm run debug ``` This command runs `node --inspect-brk dist/gemini.js` within the `packages/cli` directory, pausing execution until a debugger attaches. You can then open `chrome://inspect` in your Chrome browser to connect to the debugger.2. In VS Code, use the "Attach" launch configuration (found in `.vscode/launch.json`).
Alternatively, you can use the "Launch Program" configuration in VS Code if youprefer to launch the currently open file directly, but 'F5' is generallyrecommended.
To hit a breakpoint inside the sandbox container run:
```bashDEBUG=1 gemini```
**Note:** If you have `DEBUG=true` in a project's `.env` file, it won't affectgemini-cli due to automatic exclusion. Use `.gemini/.env` files for gemini-clispecific debug settings.
### React DevTools
To debug the CLI's React-based UI, you can use React DevTools.
1. **Start the Gemini CLI in development mode:**
```bash DEV=true npm start ```
2. **Install and run React DevTools version 6 (which matches the CLI's `react-devtools-core`):**
You can either install it globally:
```bash npm install -g react-devtools@6 react-devtools ```
Or run it directly using npx:
```bash npx react-devtools@6 ```
Your running CLI application should then connect to React DevTools. 
### Sandboxing
#### macOS Seatbelt
On macOS, `gemini` uses Seatbelt (`sandbox-exec`) under a `permissive-open`profile (see `packages/cli/src/utils/sandbox-macos-permissive-open.sb`) thatdenies operations by default, confining writes to the project folder whileallowing broad file reads and outbound network traffic ("open") by default. Youcan switch to a `strict-open` profile (see`packages/cli/src/utils/sandbox-macos-strict-open.sb`) that restricts both readsand writes to the working directory while allowing outbound network traffic bysetting `SEATBELT_PROFILE=strict-open` in your environment or `.env` file.Available built-in profiles are `permissive-{open,proxied}`,`restrictive-{open,proxied}`, and `strict-{open,proxied}` (see below for proxiednetworking). You can also switch to a custom profile`SEATBELT_PROFILE=<profile>` if you also create a file`.gemini/sandbox-macos-<profile>.sb` under your project settings directory`.gemini`.
#### Container-based sandboxing (all platforms)
For stronger container-based sandboxing on macOS or other platforms, you can set`GEMINI_SANDBOX=true|docker|podman|<command>` in your environment or `.env`file. The specified command (or if `true` then either `docker` or `podman`) mustbe installed on the host machine. Once enabled, `npm run build:all` will build aminimal container ("sandbox") image and `npm start` will launch inside a freshinstance of that container. The first build can take 20-30s (mostly due todownloading of the base image) but after that both build and start overheadshould be minimal. Default builds (`npm run build`) will not rebuild thesandbox.
Container-based sandboxing mounts the project directory (and system tempdirectory) with read-write access and is started/stopped/removed automaticallyas you start/stop Gemini CLI. Files created within the sandbox should beautomatically mapped to your user/group on host machine. You can easily specifyadditional mounts, ports, or environment variables by setting`SANDBOX_{MOUNTS,PORTS,ENV}` as needed. You can also fully customize the sandboxfor your projects by creating the files `.gemini/sandbox.Dockerfile` and/or`.gemini/sandbox.bashrc` under your project settings directory (`.gemini`) andrunning `gemini` with `BUILD_SANDBOX=1` to trigger building of your customsandbox.
#### Proxied networking
All sandboxing methods, including macOS Seatbelt using `*-proxied` profiles,support restricting outbound network traffic through a custom proxy server thatcan be specified as `GEMINI_SANDBOX_PROXY_COMMAND=<command>`, where `<command>`must start a proxy server that listens on `:::8877` for relevant requests. See`docs/examples/proxy-script.md` for a minimal proxy that only allows `HTTPS`connections to `example.com:443` (e.g. `curl https://example.com`) and declinesall other requests. The proxy is started and stopped automatically alongside thesandbox.
### Manual publish
We publish an artifact for each commit to our internal registry. But if you needto manually cut a local build, then run the following commands:
```npm run cleannpm installnpm run authnpm run prerelease:devnpm publish --workspaces```
## Documentation contribution process
Our documentation must be kept up-to-date with our code contributions. We wantour documentation to be clear, concise, and helpful to our users. We value:
- **Clarity:** Use simple and direct language. Avoid jargon where possible.- **Accuracy:** Ensure all information is correct and up-to-date.- **Completeness:** Cover all aspects of a feature or topic.- **Examples:** Provide practical examples to help users understand how to use Gemini CLI.
### Getting started
The process for contributing to the documentation is similar to contributingcode.
1. **Fork the repository** and create a new branch.2. **Make your changes** in the `/docs` directory.3. **Preview your changes locally** in Markdown rendering.4. **Lint and format your changes.** Our preflight check includes linting and formatting for documentation files. ```bash npm run preflight ```5. **Open a pull request** with your changes.
### Documentation structure
Our documentation is organized using[sidebar.json](https://github.com/google-gemini/gemini-cli/blob/main/docs/sidebar.json)as the table of contents. When adding new documentation:
1. Create your markdown file **in the appropriate directory** under `/docs`.2. Add an entry to `sidebar.json` in the relevant section.3. Ensure all internal links use relative paths and point to existing files.
### Style guide
We follow the[Google Developer Documentation Style Guide](https://developers.google.com/style).Please refer to it for guidance on writing style, tone, and formatting.
#### Key style points
- Use sentence case for headings.- Write in second person ("you") when addressing the reader.- Use present tense.- Keep paragraphs short and focused.- Use code blocks with appropriate language tags for syntax highlighting.- Include practical examples whenever possible.
### Linting and formatting
We use `prettier` to enforce a consistent style across our documentation. The`npm run preflight` command will check for any linting issues.
You can also run the linter and formatter separately:
- `npm run lint` - Check for linting issues- `npm run format` - Auto-format markdown files- `npm run lint:fix` - Auto-fix linting issues where possible
Please make sure your contributions are free of linting errors before submittinga pull request.
### Before you submit
Before submitting your documentation pull request, please:
1. Run `npm run preflight` to ensure all checks pass.2. Review your changes for clarity and accuracy.3. Check that all links work correctly.4. Ensure any code examples are tested and functional.5. Sign the [Contributor License Agreement (CLA)](https://cla.developers.google.com/) if you haven't already.
### Need help?
If you have questions about contributing documentation:
- Check our [FAQ](https://geminicli.com/docs/resources/faq).- Review existing documentation for examples.- Open [an issue](https://github.com/google-gemini/gemini-cli/issues) to discuss your proposed changes.- Reach out to the maintainers.
We appreciate your contributions to making Gemini CLI documentation better!123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185# Behavioral Evaluations & EDK Guide
This guide introduces the **Eval Development Kit (EDK)** and details how towrite, validate, run, and report on **behavioral evaluations** in the Gemini CLIcodebase.
---
## Overview
Behavioral evaluations are automated tests designed to assert on the**behavior** of the Gemini CLI agent (e.g., verifying which tools are called,checking call ordering, or avoiding destructive commands) rather than checkingthe final prose output.
Evaluating agent behavior is critical because:
1. Model responses are non-deterministic, making exact prose matching highly fragile.2. We must ensure the model utilizes the most efficient tools (e.g., batching files via `read_many_files` instead of sequential `read_file` calls).3. We must enforce safety boundaries (e.g., preventing execution of raw shell commands when safe alternatives exist).
All behavioral evaluations are stored under the `evals/` directory.
---
## EDK Developer Commands
The EDK provides CLI tools under `scripts/` to help contributors audit, check,and monitor evals.
### 1. `npm run eval:inventory`
Scans all eval files under `evals/`, statically parses them, and provides astructured overview of what exists in the repository.
- **Usage:** ```bash npm run eval:inventory ```- **JSON Output:** For CI integration or inventory indexing, generate a machine-readable JSON report: ```bash npm run eval:inventory -- --json ```- **Custom Root:** Run against another directory or repository: ```bash npm run eval:inventory -- --root /path/to/other/repo ```
---
### 2. `npm run eval:validate`
A lint-like checker that validates eval source files against standard structuralguidelines and best practices.
- **Usage:** ```bash npm run eval:validate ```- **Custom Scopes:** Validate a specific file: ```bash npm run eval:validate -- evals/my-test.eval.ts ```
#### Validation Rules & Severities
| Rule ID | Severity | Description || :------------------- | :---------- | :--------------------------------------------------------------------------------------------------------------------- || `file-naming` | **Error** | File must match `*.eval.ts` or `*.eval.tsx` naming conventions. || `valid-policy` | **Error** | Policy must be one of `ALWAYS_PASSES`, `USUALLY_PASSES`, or `USUALLY_FAILS`. || `suite-metadata` | **Error** | Both `suiteName` and `suiteType` must be present as static string literals. || `prompt-presence` | **Error** | Every eval case must have a non-empty `prompt` string. || `case-name-static` | **Error** | The case name must be a static string literal, not computed dynamically. || `invalid-tool-refs` | **Error** | All tools referenced in assertions must match known built-in or legacy tools. || `positive-assertion` | **Error** | Evaluation cases must assert on at least one tool call (e.g., check `waitForToolCall` has been invoked). || `workspace-setup` | **Error** | Workspace behaviors (like file-system edits/reads) must set up a `files` object. || `new-evals-policy` | **Warning** | New evals must not use `ALWAYS_PASSES` policy initially (they should be promoted after nightly data proves stability). |
Warnings (`new-evals-policy`) will be logged with `⚠` and will **not** causethe CLI process to exit with status `1`. Errors (`✗`) will block CI builds andreturn exit status `1`.
---
### 3. `npm run eval:report`
Aggregates local vitest `report.json` artifacts, maps them against inventorypolicies, and summarizes the pass rates per model.
- **Usage:** ```bash npm run eval:report ``` By default, it scans `evals/logs/` recursively for `report.json` files.- **Specifying Directory:** ```bash npm run eval:report -- /path/to/logs ```- **JSON Output:** ```bash npm run eval:report -- --json ```
---
## Contributor Workflow
When writing a new behavioral evaluation, adhere to this workflow to ensurehigh-quality, non-flaky test runs.
### Step-by-Step Guide
1. **Identify the Target Behavior**: Determine which tool calls need verification (e.g., `web_fetch` must be called).2. **Author the Eval File**: Create your file under `evals/<name>.eval.ts` naming it properly.3. **Configure Workspace Files**: If the eval reads or edits files, define them inside the `files` metadata field.4. **Assert Behavior, Not Prose**: Ensure the `assert` block checks tool interactions using `rig.waitForToolCall` or similar. Do not check final prose.5. **Run Locally**: ```bash RUN_EVALS=true npx vitest run evals/my-test.eval.ts ```6. **Deflake**: Run your eval at least 3 times locally to verify it does not fail due to model variance.7. **Run Validation**: Run `npm run eval:validate` to ensure no linting errors are present.
### Acceptance Criteria Checklist
- [ ] **Naming**: File ends with `.eval.ts` or `.eval.tsx`.- [ ] **Policy**: New evals start as `USUALLY_PASSES`.- [ ] **Metadata**: Static `suiteName` and `suiteType` (e.g. `'behavioral'`) are specified.- [ ] **Assertions**: Uses `rig.waitForToolCall` or asserts tool arguments explicitly.- [ ] **Clean workspace**: Does not write to files outside `rig.testDir`.
### Common Anti-Patterns to Avoid
- **Restricting core tools**: Never override `settings.tools.core` to limit tools. Evals must run against the default toolset.- **Checking model prose**: Avoid `expect(result).toContain('something')` since model wording is non-deterministic.- **Integration-only testing**: Evals that only write files without checking realistic model prompts are integration tests and belong under `integration-tests/`.
---
## CI & Dashboard Integration
You can easily automate behavioral evaluations or compile dashboard data usingEDK's JSON reporters.
### CI Validation Block
Add a step in your PR checks or GitHub workflows to automatically lint new evalsand block pull requests containing validation errors:
```yaml- name: Run Eval Validator run: npm run eval:validate```
### Publishing to a Dashboard
To record nightly performance metrics across multiple models:
1. Configure your workflow to run evaluations with the JSON reporter: ```bash cross-env GEMINI_MODEL=gemini-2.5-pro npx vitest run --config evals/vitest.config.ts --reporter=json --outputFile="evals/logs/eval-logs-gemini-2.5-pro/report.json" ```2. Aggregate all test runs using the reporting tool: ```bash npm run eval:report -- evals/logs --json > aggregated_report.json ```3. Upload `aggregated_report.json` to your dashboard storage backend to visualize pass rates over time.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139# Gemini CLI documentation
Gemini CLI brings the power of Gemini models directly into your terminal. Use itto understand code, automate tasks, and build workflows with your local projectcontext.
## Install
```bashnpm install -g @google/gemini-cli```
## Get started
Jump in to Gemini CLI.
- **[Quickstart](./get-started/index.md):** Your first session with Gemini CLI.- **[Installation](./get-started/installation.mdx):** How to install Gemini CLI on your system.- **[Authentication](./get-started/authentication.mdx):** Setup instructions for personal and enterprise accounts.- **[CLI cheatsheet](./cli/cli-reference.md):** A quick reference for common commands and options.- **[Gemini 3 on Gemini CLI](./get-started/gemini-3.md):** Learn about Gemini 3 support in Gemini CLI.
## Use Gemini CLI
User-focused guides and tutorials for daily development workflows.
- **[File management](./cli/tutorials/file-management.md):** How to work with local files and directories.- **[Get started with Agent skills](./cli/tutorials/skills-getting-started.md):** Getting started with specialized expertise.- **[Manage context and memory](./cli/tutorials/memory-management.md):** Managing persistent instructions and facts.- **[Execute shell commands](./cli/tutorials/shell-commands.md):** Executing system commands safely.- **[Manage sessions and history](./cli/tutorials/session-management.md):** Resuming, managing, and rewinding conversations.- **[Plan tasks with todos](./cli/tutorials/task-planning.md):** Using todos for complex workflows.- **[Web search and fetch](./cli/tutorials/web-tools.md):** Searching and fetching content from the web.- **[Set up an MCP server](./cli/tutorials/mcp-setup.md):** Set up an MCP server.- **[Automate tasks](./cli/tutorials/automation.md):** Automate tasks.
## Features
Technical documentation for each capability of Gemini CLI.
- **[Extensions](./extensions/index.md):** Extend Gemini CLI with new tools and capabilities.- **[Agent Skills](./cli/skills.md):** Use specialized agents for specific tasks.- **[Checkpointing](./cli/checkpointing.md):** Automatic session snapshots.- **[Headless mode](./cli/headless.md):** Programmatic and scripting interface.- **[Hooks](./hooks/index.md):** Customize Gemini CLI behavior with scripts.- **[IDE integration](./ide-integration/index.md):** Integrate Gemini CLI with your favorite IDE.- **[MCP servers](./tools/mcp-server.md):** Connect to and use remote agents.- **[Model routing](./cli/model-routing.md):** Automatic fallback resilience.- **[Model selection](./cli/model.md):** Choose the best model for your needs.- **[Plan mode 🔬](./cli/plan-mode.md):** Use a safe, read-only mode for planning complex changes.- **[Subagents 🔬](./core/subagents.md):** Using specialized agents for specific tasks.- **[Remote subagents 🔬](./core/remote-agents.md):** Connecting to and using remote agents.- **[Rewind](./cli/rewind.md):** Rewind and replay sessions.- **[Sandboxing](./cli/sandbox.md):** Isolate tool execution.- **[Settings](./cli/settings.md):** Full configuration reference.- **[Telemetry](./cli/telemetry.md):** Usage and performance metric details.- **[Token caching](./cli/token-caching.md):** Performance optimization.
## Configuration
Settings and customization options for Gemini CLI.
- **[Custom commands](./cli/custom-commands.md):** Personalized shortcuts.- **[Enterprise configuration](./cli/enterprise.md):** Professional environment controls.- **[Ignore files (.geminiignore)](./cli/gemini-ignore.md):** Exclusion pattern reference.- **[Model configuration](./cli/generation-settings.md):** Fine-tune generation parameters like temperature and thinking budget.- **[Project context (GEMINI.md)](./cli/gemini-md.md):** Technical hierarchy of context files.- **[System prompt override](./cli/system-prompt.md):** Instruction replacement logic.- **[Themes](./cli/themes.md):** UI personalization technical guide.- **[Trusted folders](./cli/trusted-folders.md):** Security permission logic.
## Reference
Deep technical documentation and API specifications.
- **[Command reference](./reference/commands.md):** Detailed slash command guide.- **[Configuration reference](./reference/configuration.md):** Settings and environment variables.- **[Keyboard shortcuts](./reference/keyboard-shortcuts.md):** Productivity tips.- **[Memory import processor](./reference/memport.md):** How Gemini CLI processes memory from various sources.- **[Policy engine](./reference/policy-engine.md):** Fine-grained execution control.- **[Tools reference](./reference/tools.md):** Information on how tools are defined, registered, and used.
## Resources
Support, release history, and legal information.
- **[FAQ](./resources/faq.md):** Answers to frequently asked questions.- **[Quota and pricing](./resources/quota-and-pricing.md):** Limits and billing details.- **[Terms and privacy](./resources/tos-privacy.md):** Official notices and terms.- **[Troubleshooting](./resources/troubleshooting.md):** Common issues and solutions.- **[Uninstall](./resources/uninstall.md):** How to uninstall Gemini CLI.
## Development
- **[Contribution guide](/docs/contributing):** How to contribute to Gemini CLI.- **[Integration testing](./integration-tests.md):** Running integration tests.- **[Issue and PR automation](./issue-and-pr-automation.md):** Automation for issues and pull requests.- **[Local development](./local-development.md):** Setting up a local development environment.- **[NPM package structure](./npm.md):** The structure of the NPM packages.
## Releases
- **[Release notes](./changelogs/index.md):** Release notes for all versions.- **[Stable release](./changelogs/latest.md):** The latest stable release.- **[Preview release](./changelogs/preview.md):** The latest preview release.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293# Integration tests
This document provides information about the integration testing framework usedin this project.
## Overview
The integration tests are designed to validate the end-to-end functionality ofGemini CLI. They execute the built binary in a controlled environment and verifythat it behaves as expected when interacting with the file system.
These tests are located in the `integration-tests` directory and are run using acustom test runner.
## Building the tests
Prior to running any integration tests, you need to create a release bundle thatyou want to actually test:
```bashnpm run bundle```
You must re-run this command after making any changes to the CLI source code,but not after making changes to tests.
## Running the tests
The integration tests are not run as part of the default `npm run test` command.They must be run explicitly using the `npm run test:integration:all` script.
The integration tests can also be run using the following shortcut:
```bashnpm run test:e2e```
## Running a specific set of tests
To run a subset of test files, you can use`npm run <integration test command> <file_name1> ....` where <integrationtest command> is either `test:e2e` or `test:integration*` and `<file_name>`is any of the `.test.js` files in the `integration-tests/` directory. Forexample, the following command runs `list_directory.test.js` and`write_file.test.js`:
```bashnpm run test:e2e list_directory write_file```
### Running a single test by name
To run a single test by its name, use the `--test-name-pattern` flag:
```bashnpm run test:e2e -- --test-name-pattern "reads a file"```
### Regenerating model responses
Some integration tests use faked out model responses, which may need to beregenerated from time to time as the implementations change.
To regenerate these golden files, set the REGENERATE_MODEL_GOLDENS environmentvariable to "true" when running the tests, for example:
**WARNING**: If running locally you should review these updated responses forany information about yourself or your system that gemini may have included inthese responses.
```bashREGENERATE_MODEL_GOLDENS="true" npm run test:e2e```
**WARNING**: Make sure you run **await rig.cleanup()** at the end of your test,else the golden files will not be updated.
### Deflaking a test
Before adding a **new** integration test, you should test it at least 5 timeswith the deflake script or workflow to make sure that it is not flaky.
### Deflake script
```bashnpm run deflake -- --runs=5 --command="npm run test:e2e -- -- --test-name-pattern '<your-new-test-name>'"```
#### Deflake workflow
```bashgh workflow run deflake.yml --ref <your-branch> -f test_name_pattern="<your-test-name-pattern>"```
### Running all tests
To run the entire suite of integration tests, use the following command:
```bashnpm run test:integration:all```
### Sandbox matrix
The `all` command will run tests for `no sandboxing`, `docker` and `podman`.Each individual type can be run using the following commands:
```bashnpm run test:integration:sandbox:none```
```bashnpm run test:integration:sandbox:docker```
```bashnpm run test:integration:sandbox:podman```
## Memory regression tests
Memory regression tests are designed to detect heap growth and leaks across keyCLI scenarios. They are located in the `memory-tests` directory.
These tests are distinct from standard integration tests because they measurememory usage and compare it against committed baselines.
### Running memory tests
Memory tests are not run as part of the default `npm run test` or`npm run test:e2e` commands. They are run nightly in CI but can be run manually:
```bashnpm run test:memory```
### Updating baselines
If you intentionally change behavior that affects memory usage, you may need toupdate the baselines. Set the `UPDATE_MEMORY_BASELINES` environment variable to`true`:
```bashUPDATE_MEMORY_BASELINES=true npm run test:memory```
This will run the tests, take median snapshots, and overwrite`memory-tests/baselines.json`. You should review the changes and commit theupdated baseline file.
### How it works
The harness (`MemoryTestHarness` in `packages/test-utils`):
- Forces garbage collection multiple times to reduce noise.- Takes median snapshots to filter spikes.- Compares against baselines with a 10% tolerance.- Can analyze sustained leaks across 3 snapshots using `analyzeSnapshots()`.
## Performance regression tests
Performance regression tests are designed to detect wall-clock time, CPU usage,and event loop delay regressions across key CLI scenarios. They are located inthe `perf-tests` directory.
These tests are distinct from standard integration tests because they measureperformance metrics and compare it against committed baselines.
### Running performance tests
Performance tests are not run as part of the default `npm run test` or`npm run test:e2e` commands. They are run nightly in CI but can be run manually:
```bashnpm run test:perf```
### Updating baselines
If you intentionally change behavior that affects performance, you may need toupdate the baselines. Set the `UPDATE_PERF_BASELINES` environment variable to`true`:
```bashUPDATE_PERF_BASELINES=true npm run test:perf```
This will run the tests multiple times (with warmup), apply IQR outlierfiltering, and overwrite `perf-tests/baselines.json`. You should review thechanges and commit the updated baseline file.
### How it works
The harness (`PerfTestHarness` in `packages/test-utils`):
- Measures wall-clock time using `performance.now()`.- Measures CPU usage using `process.cpuUsage()`.- Monitors event loop delay using `perf_hooks.monitorEventLoopDelay()`.- Applies IQR (Interquartile Range) filtering to remove outlier samples.- Compares against baselines with a 15% tolerance.
## Diagnostics
The integration test runner provides several options for diagnostics to helptrack down test failures.
### Keeping test output
You can preserve the temporary files created during a test run for inspection.This is useful for debugging issues with file system operations.
To keep the test output set the `KEEP_OUTPUT` environment variable to `true`.
```bashKEEP_OUTPUT=true npm run test:integration:sandbox:none```
When output is kept, the test runner will print the path to the unique directoryfor the test run.
### Verbose output
For more detailed debugging, set the `VERBOSE` environment variable to `true`.
```bashVERBOSE=true npm run test:integration:sandbox:none```
When using `VERBOSE=true` and `KEEP_OUTPUT=true` in the same command, the outputis streamed to the console and also saved to a log file within the test'stemporary directory.
The verbose output is formatted to clearly identify the source of the logs:
```--- TEST: <log dir>:<test-name> ---... output from the gemini command ...--- END TEST: <log dir>:<test-name> ---```
## Linting and formatting
To ensure code quality and consistency, the integration test files are linted aspart of the main build process. You can also manually run the linter andauto-fixer.
### Running the linter
To check for linting errors, run the following command:
```bashnpm run lint```
You can include the `:fix` flag in the command to automatically fix any fixablelinting errors:
```bashnpm run lint:fix```
## Directory structure
The integration tests create a unique directory for each test run inside the`.integration-tests` directory. Within this directory, a subdirectory is createdfor each test file, and within that, a subdirectory is created for eachindividual test case.
This structure makes it easy to locate the artifacts for a specific test run,file, or case.
```.integration-tests/└── <run-id>/ └── <test-file-name>.test.js/ └── <test-case-name>/ ├── output.log └── ...other test artifacts...```
## Continuous integration
To ensure the integration tests are always run, a GitHub Actions workflow isdefined in `.github/workflows/chained_e2e.yml`. This workflow automatically runsthe integrations tests for pull requests against the `main` branch, or when apull request is added to a merge queue.
The workflow runs the tests in different sandboxing environments to ensureGemini CLI is tested across each:
- `sandbox:none`: Runs the tests without any sandboxing.- `sandbox:docker`: Runs the tests in a Docker container.- `sandbox:podman`: Runs the tests in a Podman container.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203# Automation and triage processes
This document provides a detailed overview of the automated processes we use tomanage and triage issues and pull requests. Our goal is to provide promptfeedback and ensure that contributions are reviewed and integrated efficiently.Understanding this automation will help you as a contributor know what to expectand how to best interact with our repository bots.
## Guiding principle: Issues and pull requests
First and foremost, almost every Pull Request (PR) should be linked to acorresponding Issue. The issue describes the "what" and the "why" (the bug orfeature), while the PR is the "how" (the implementation). This separation helpsus track work, prioritize features, and maintain clear historical context. Ourautomation is built around this principle.
<!-- prettier-ignore -->> [!NOTE]> Issues tagged as "🔒Maintainers only" are reserved for project> maintainers. We will not accept pull requests related to these issues.
---
## Detailed automation workflows
Here is a breakdown of the specific automation workflows that run in ourrepository.
### 1. When you open an issue: `Automated Issue Triage`
This is the first bot you will interact with when you create an issue. Its jobis to perform an initial analysis and apply the correct labels.
- **Workflow File**: `.github/workflows/gemini-automated-issue-triage.yml`- **When it runs**: Immediately after an issue is created or reopened.- **What it does**: - It uses a Gemini model to analyze the issue's title and body against a detailed set of guidelines. - **Applies one `area/*` label**: Categorizes the issue into a functional area of the project (for example, `area/ux`, `area/models`, `area/platform`). - **Applies one `kind/*` label**: Identifies the type of issue (for example, `kind/bug`, `kind/enhancement`, `kind/question`). - **Applies one `priority/*` label**: Assigns a priority from P0 (critical) to P3 (low) based on the described impact. - **May apply `status/need-information`**: If the issue lacks critical details (like logs or reproduction steps), it will be flagged for more information. - **May apply `status/need-retesting`**: If the issue references a CLI version that is more than six versions old, it will be flagged for retesting on a current version.- **What you should do**: - Fill out the issue template as completely as possible. The more detail you provide, the more accurate the triage will be. - If the `status/need-information` label is added, provide the requested details in a comment.
### 2. When you open a pull request: `Continuous Integration (CI)`
This workflow ensures that all changes meet our quality standards before theycan be merged.
- **Workflow File**: `.github/workflows/ci.yml`- **When it runs**: On every push to a pull request.- **What it does**: - **Lint**: Checks that your code adheres to our project's formatting and style rules. - **Test**: Runs our full suite of automated tests across macOS, Windows, and Linux, and on multiple Node.js versions. This is the most time-consuming part of the CI process. - **Post Coverage Comment**: After all tests have successfully passed, a bot will post a comment on your PR. This comment provides a summary of how well your changes are covered by tests.- **What you should do**: - Ensure all CI checks pass. A green checkmark ✅ will appear next to your commit when everything is successful. - If a check fails (a red "X" ❌), click the "Details" link next to the failed check to view the logs, identify the problem, and push a fix.
### 3. Ongoing triage for pull requests: `PR Auditing and Label Sync`
This workflow runs periodically to ensure all open PRs are correctly linked toissues and have consistent labels.
- **Workflow File**: `.github/workflows/gemini-scheduled-pr-triage.yml`- **When it runs**: Every 15 minutes on all open pull requests.- **What it does**: - **Checks for a linked issue**: The bot scans your PR description for a keyword that links it to an issue (for example, `Fixes #123`, `Closes #456`). - **Adds `status/need-issue`**: If no linked issue is found, the bot will add the `status/need-issue` label to your PR. This is a clear signal that an issue needs to be created and linked. - **Synchronizes labels**: If an issue _is_ linked, the bot ensures the PR's labels perfectly match the issue's labels. It will add any missing labels and remove any that don't belong, and it will remove the `status/need-issue` label if it was present.- **What you should do**: - **Always link your PR to an issue.** This is the most important step. Add a line like `Resolves #<issue-number>` to your PR description. - This will ensure your PR is correctly categorized and moves through the review process smoothly.
### 4. Ongoing triage for issues: `Scheduled Issue Triage`
This is a fallback workflow to ensure that no issue gets missed by the triageprocess.
- **Workflow File**: `.github/workflows/gemini-scheduled-issue-triage.yml`- **When it runs**: Every hour on all open issues.- **What it does**: - It actively seeks out issues that either have no labels at all or still have the `status/need-triage` label. - It then triggers the same powerful Gemini-based analysis as the initial triage bot to apply the correct labels.- **What you should do**: - You typically don't need to do anything. This workflow is a safety net to ensure every issue is eventually categorized, even if the initial triage fails.
### 5. Automatic unassignment of inactive contributors: `Unassign Inactive Issue Assignees`
To keep the list of open `help wanted` issues accessible to all contributors,this workflow automatically removes **external contributors** who have notopened a linked pull request within **7 days** of being assigned. Maintainers,org members, and repo collaborators with write access or above are always exemptand will never be auto-unassigned.
- **Workflow File**: `.github/workflows/unassign-inactive-assignees.yml`- **When it runs**: Every day at 09:00 UTC, and can be triggered manually with an optional `dry_run` mode.- **What it does**: 1. Finds every open issue labeled `help wanted` that has at least one assignee. 2. Identifies privileged users (team members, repo collaborators with write+ access, maintainers) and skips them entirely. 3. For each remaining (external) assignee it reads the issue's timeline to determine: - The exact date they were assigned (using `assigned` timeline events). - Whether they have opened a PR that is already linked/cross-referenced to the issue. 4. Each cross-referenced PR is fetched to verify it is **ready for review**: open and non-draft, or already merged. Draft PRs do not count. 5. If an assignee has been assigned for **more than 7 days** and no qualifying PR is found, they are automatically unassigned and a comment is posted explaining the reason and how to re-claim the issue. 6. Assignees who have a non-draft, open or merged PR linked to the issue are **never** unassigned by this workflow.- **What you should do**: - **Open a real PR, not a draft**: Within 7 days of being assigned, open a PR that is ready for review and include `Fixes #<issue-number>` in the description. Draft PRs do not satisfy the requirement and will not prevent auto-unassignment. - **Re-assign if unassigned by mistake**: Comment `/assign` on the issue to assign yourself again. - **Unassign yourself** if you can no longer work on the issue by commenting `/unassign`, so other contributors can pick it up right away.
### 6. Automatically label PRs by size: `PR Size Labeler`
To help maintainers estimate review effort and keep the PR history clean, thisworkflow automatically tags every pull request with a size label representingthe total volume of line changes.
- **Workflow File**: `.github/workflows/pr-size-labeler.yml`- **When it runs**: Immediately after a pull request is created, synchronized (new commits pushed), or reopened. It can also be triggered manually via `workflow_dispatch` with a PR number.- **What it does**: - **Calculates total changes**: Summarizes additions and deletions across all changed files in a single consolidated API request. - **Applies standard size labels**: - `size/XS`: < 10 lines changed - `size/S`: 10-49 lines changed - `size/M`: 50-249 lines changed - `size/L`: 250-999 lines changed - `size/XL`: >= 1000 lines changed - **Updates size tag atomically**: Adds the new correct size label and removes any obsolete size labels in one atomic step. - **Updates/Posts PR size info comment**: Instead of spamming a new comment on every commit push, it updates the existing size labeler status comment inline to keep the PR conversation timeline perfectly neat and clean.- **What you should do**: - You do not need to take any actions. The workflow runs automatically and updates the label and comment seamlessly as you push new updates.
### 7. Release automation
This workflow handles the process of packaging and publishing new versions ofGemini CLI.
- **Workflow File**: `.github/workflows/release-manual.yml`- **When it runs**: On a daily schedule for "nightly" releases, and manually for official patch/minor releases.- **What it does**: - Automatically builds the project, bumps the version numbers, and publishes the packages to npm. - Creates a corresponding release on GitHub with generated release notes.- **What you should do**: - As a contributor, you don't need to do anything for this process. You can be confident that once your PR is merged into the `main` branch, your changes will be included in the very next nightly release.
We hope this detailed overview is helpful. If you have any questions about ourautomation or processes, don't hesitate to ask!123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182# Local development guide
This guide provides instructions for setting up and using local developmentfeatures for Gemini CLI.
## Tracing
Gemini CLI uses OpenTelemetry (OTel) to record traces that help you debug agentbehavior. Traces instrument key events like model calls, tool scheduleroperations, and tool calls.
Traces provide deep visibility into agent behavior and help you debug complexissues. They are captured automatically when you enable telemetry.
### View traces
You can view traces using Genkit Developer UI, Jaeger, or Google Cloud.
#### Use Genkit
Genkit provides a web-based UI for viewing traces and other telemetry data.
1. **Start the Genkit telemetry server:**
Run the following command to start the Genkit server:
```bash npm run telemetry -- --target=genkit ```
The script will output the URL for the Genkit Developer UI. For example: `Genkit Developer UI: http://localhost:4000`
2. **Run Gemini CLI:**
In a separate terminal, run your Gemini CLI command:
```bash gemini ```
3. **View the traces:**
Open the Genkit Developer UI URL in your browser and navigate to the **Traces** tab to view the traces.
#### Use Jaeger
You can view traces in the Jaeger UI for local development.
1. **Start the telemetry collector:**
Run the following command in your terminal to download and start Jaeger and an OTel collector:
```bash npm run telemetry -- --target=local ```
This command configures your workspace for local telemetry and provides a link to the Jaeger UI (usually `http://localhost:16686`).
- **Collector logs:** `~/.gemini/tmp/<projectHash>/otel/collector.log`
2. **Run Gemini CLI:**
In a separate terminal, run your Gemini CLI command:
```bash gemini ```
3. **View the traces:**
After running your command, open the Jaeger UI link in your browser to view the traces.
#### Use Google Cloud
You can use an OpenTelemetry collector to forward telemetry data to Google CloudTrace for custom processing or routing.
<!-- prettier-ignore -->> [!WARNING]> Ensure you complete the> [Google Cloud telemetry prerequisites](./cli/telemetry.md#prerequisites)> (Project ID, authentication, IAM roles, and APIs) before using this method.
1. **Configure `.gemini/settings.json`:**
```json { "telemetry": { "enabled": true, "target": "gcp", "useCollector": true } } ```
2. **Start the telemetry collector:**
Run the following command to start a local OTel collector that forwards to Google Cloud:
```bash npm run telemetry -- --target=gcp ```
The script outputs links to view traces, metrics, and logs in the Google Cloud Console.
- **Collector logs:** `~/.gemini/tmp/<projectHash>/otel/collector-gcp.log`
3. **Run Gemini CLI:**
In a separate terminal, run your Gemini CLI command:
```bash gemini ```
4. **View logs, metrics, and traces:**
After sending prompts, view your data in the Google Cloud Console. See the [telemetry documentation](./cli/telemetry.md#view-google-cloud-telemetry) for links to Logs, Metrics, and Trace explorers.
For more detailed information on telemetry, see the[telemetry documentation](./cli/telemetry.md).
### Instrument code with traces
You can add traces to your own code for more detailed instrumentation.
Adding traces helps you debug and understand the flow of execution. Use the`runInDevTraceSpan` function to wrap any section of code in a trace span.
Here is a basic example:
```typescriptimport { runInDevTraceSpan } from '@google/gemini-cli-core';import { GeminiCliOperation } from '@google/gemini-cli-core/lib/telemetry/constants.js';
await runInDevTraceSpan( { operation: GeminiCliOperation.ToolCall, attributes: { [GEN_AI_AGENT_NAME]: 'gemini-cli', }, }, async ({ metadata }) => { // metadata allows you to record the input and output of the // operation as well as other attributes. metadata.input = { key: 'value' }; // Set custom attributes. metadata.attributes['custom.attribute'] = 'custom.value';
// Your code to be traced goes here. try { const output = await somethingRisky(); metadata.output = output; return output; } catch (e) { metadata.error = e; throw e; } },);```
In this example:
- `operation`: The operation type of the span, represented by the `GeminiCliOperation` enum.- `metadata.input`: (Optional) An object containing the input data for the traced operation.- `metadata.output`: (Optional) An object containing the output data from the traced operation.- `metadata.attributes`: (Optional) A record of custom attributes to add to the span.- `metadata.error`: (Optional) An error object to record if the operation fails.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162# Package overview
This monorepo contains two main packages: `@google/gemini-cli` and`@google/gemini-cli-core`.
## `@google/gemini-cli`
This is the main package for Gemini CLI. It is responsible for the userinterface, command parsing, and all other user-facing functionality.
When this package is published, it is bundled into a single executable file.This bundle includes all of the package's dependencies, including`@google/gemini-cli-core`. This means that whether a user installs the packagewith `npm install -g @google/gemini-cli` or runs it directly with`npx @google/gemini-cli`, they are using this single, self-contained executable.
## `@google/gemini-cli-core`
This package contains the core logic for interacting with the Gemini API. It isresponsible for making API requests, handling authentication, and managing thelocal cache.
This package is not bundled. When it is published, it is published as a standardNode.js package with its own dependencies. This allows it to be used as astandalone package in other projects, if needed. All transpiled js code in the`dist` folder is included in the package.
## NPM workspaces
This project uses[NPM Workspaces](https://docs.npmjs.com/cli/v10/using-npm/workspaces) to managethe packages within this monorepo. This simplifies development by allowing us tomanage dependencies and run scripts across multiple packages from the root ofthe project.
### How it works
The root `package.json` file defines the workspaces for this project:
```json{ "workspaces": ["packages/*"]}```
This tells NPM that any folder inside the `packages` directory is a separatepackage that should be managed as part of the workspace.
### Benefits of workspaces
- **Simplified dependency management**: Running `npm install` from the root of the project will install all dependencies for all packages in the workspace and link them together. This means you don't need to run `npm install` in each package's directory.- **Automatic linking**: Packages within the workspace can depend on each other. When you run `npm install`, NPM will automatically create symlinks between the packages. This means that when you make changes to one package, the changes are immediately available to other packages that depend on it.- **Simplified script execution**: You can run scripts in any package from the root of the project using the `--workspace` flag. For example, to run the `build` script in the `cli` package, you can run `npm run build --workspace @google/gemini-cli`.123456789101112131415161718192021{ "/docs/architecture": "/docs/cli/index", "/docs/cli/commands": "/docs/reference/commands", "/docs/cli": "/docs", "/docs/cli/index": "/docs", "/docs/cli/keyboard-shortcuts": "/docs/reference/keyboard-shortcuts", "/docs/cli/uninstall": "/docs/resources/uninstall", "/docs/core/concepts": "/docs", "/docs/core/memport": "/docs/reference/memport", "/docs/core/policy-engine": "/docs/reference/policy-engine", "/docs/core/tools-api": "/docs/reference/tools", "/docs/reference/tools-api": "/docs/reference/tools", "/docs/faq": "/docs/resources/faq", "/docs/get-started/configuration": "/docs/reference/configuration", "/docs/get-started/configuration-v1": "/docs/reference/configuration", "/docs/get-started/examples": "/docs/get-started/index", "/docs/index": "/docs", "/docs/quota-and-pricing": "/docs/resources/quota-and-pricing", "/docs/tos-privacy": "/docs/resources/tos-privacy", "/docs/troubleshooting": "/docs/resources/troubleshooting"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168# Release confidence strategy
This document outlines the strategy for gaining confidence in every release ofGemini CLI. It serves as a checklist and quality gate for release manager toensure we are shipping a high-quality product.
## The goal
To answer the question, "Is this release _truly_ ready for our users?" with ahigh degree of confidence, based on a holistic evaluation of automated signals,manual verification, and data.
## Level 1: Automated gates (must pass)
These are the baseline requirements. If any of these fail, the release is ano-go.
### 1. CI/CD health
All workflows in `.github/workflows/ci.yml` must pass on the `main` branch (fornightly) or the release branch (for preview/stable).
- **Platforms:** Tests must pass on **Linux and macOS**.
- **Checks:** - **Linting:** No linting errors (ESLint, Prettier, etc.). - **Typechecking:** No TypeScript errors. - **Unit Tests:** All unit tests in `packages/core` and `packages/cli` must pass. - **Build:** The project must build and bundle successfully.
### 2. End-to-end (E2E) tests
All workflows in `.github/workflows/chained_e2e.yml` must pass.
- **Platforms:** **Linux, macOS and Windows**.- **Sandboxing:** Tests must pass with both `sandbox:none` and `sandbox:docker` on Linux.
### 3. Post-deployment smoke tests
After a release is published to npm, the `smoke-test.yml` workflow runs. Thismust pass to confirm the package is installable and the binary is executable.
- **Command:** `npx -y @google/gemini-cli@<tag> --version` must return the correct version without error.- **Platform:** Currently runs on `ubuntu-latest`.
## Level 2: Manual verification and dogfooding
Automated tests cannot catch everything, especially UX issues.
### 1. Dogfooding via `preview` tag
The weekly release cadence promotes code from `main` -> `nightly` -> `preview`-> `stable`.
- **Requirement:** The `preview` release must be used by maintainers for at least **one week** before being promoted to `stable`.- **Action:** Maintainers should install the preview version locally: ```bash npm install -g @google/gemini-cli@preview ```- **Goal:** To catch regressions and UX issues in day-to-day usage before they reach the broad user base.
### 2. Critical user journey (CUJ) checklist
Before promoting a `preview` release to `stable`, a release manager mustmanually run through this checklist.
- **Setup:**
- [ ] Uninstall any existing global version: `npm uninstall -g @google/gemini-cli` - [ ] Clear npx cache (optional but recommended): `npm cache clean --force` - [ ] Install the preview version: `npm install -g @google/gemini-cli@preview` - [ ] Verify version: `gemini --version`
- **Authentication:**
- [ ] In interactive mode run `/auth` and verify all sign in flows work: - [ ] Sign in with Google - [ ] API Key - [ ] Vertex AI
- **Basic prompting:**
- [ ] Run `gemini "Tell me a joke"` and verify a sensible response. - [ ] Run in interactive mode: `gemini`. Ask a follow-up question to test context.
- **Piped input:**
- [ ] Run `echo "Summarize this" | gemini` and verify it processes stdin.
- **Context management:**
- [ ] In interactive mode, use `@file` to add a local file to context. Ask a question about it.
- **Settings:**
- [ ] In interactive mode run `/settings` and make modifications - [ ] Validate that setting is changed
- **Function calling:** - [ ] In interactive mode, ask gemini to "create a file named hello.md with the content 'hello world'" and verify the file is created correctly.
If any of these CUJs fail, the release is a no-go until a patch is applied tothe `preview` channel.
### 3. Pre-Launch bug bash (tier 1 and 2 launches)
For high-impact releases, an organized bug bash is required to ensure a higherlevel of quality and to catch issues across a wider range of environments anduse cases.
**Definition of tiers:**
- **Tier 1:** Industry-Moving News 🚀- **Tier 2:** Important News for Our Users 📣- **Tier 3:** Relevant, but Not Life-Changing 💡- **Tier 4:** Bug Fixes ⚒️
**Requirement:**
A bug bash must be scheduled at least **72 hours in advance** of any Tier 1 orTier 2 launch.
**Rule of thumb:**
A bug bash should be considered for any release that involves:
- A blog post- Coordinated social media announcements- Media relations or press outreach- A "Turbo" launch event
## Level 3: Telemetry and data review
### Dashboard health
- [ ] Go to `go/gemini-cli-dash`.- [ ] Navigate to the "Tool Call" tab.- [ ] Validate that there are no spikes in errors for the release you would like to promote.
### Model evaluation
- [ ] Navigate to `go/gemini-cli-offline-evals-dash`.- [ ] Make sure that the release you want to promote's recurring run is within average eval runs.
## The "go/no-go" decision
Before triggering the `Release: Promote` workflow to move `preview` to `stable`:
1. [ ] **Level 1:** CI and E2E workflows are green for the commit corresponding to the current `preview` tag.2. [ ] **Level 2:** The `preview` version has been out for one week, and the CUJ checklist has been completed successfully by a release manager. No blocking issues have been reported.3. [ ] **Level 3:** Dashboard Health and Model Evaluation checks have been completed and show no regressions.
If all checks pass, proceed with the promotion.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550# Gemini CLI releases
<!-- prettier-ignore -->> [!IMPORTANT]> **Coordinate with the Release Manager:** The release manager is responsible for coordinating patches and releases. Please update them before performing any of the release actions described in this document.
## `dev` vs `prod` environment
Our release flows support both `dev` and `prod` environments.
The `dev` environment pushes to a private GitHub-hosted NPM repository, with thepackage names beginning with `@google-gemini/**` instead of `@google/**`.
The `prod` environment pushes to the public global NPM registry via WombatDressing Room, which is Google's system for managing NPM packages in the`@google/**` namespace. The packages are all named `@google/**`.
More information can be found about these systems in the[NPM Package Overview](npm.md)
### Package scopes
| Package | `prod` (Wombat Dressing Room) | `dev` (GitHub Private NPM Repo) || ---------- | ----------------------------- | ----------------------------------------- || CLI | @google/gemini-cli | @google-gemini/gemini-cli || Core | @google/gemini-cli-core | @google-gemini/gemini-cli-core A2A Server || A2A Server | @google/gemini-cli-a2a-server | @google-gemini/gemini-cli-a2a-server |
## Release cadence and tags
We will follow https://semver.org/ as closely as possible but will call out whenor if we have to deviate from it. Our weekly releases will be minor versionincrements and any bug or hotfixes between releases will go out as patchversions on the most recent release.
Each Tuesday ~20:00 UTC new Stable and Preview releases will be cut. Thepromotion flow is:
- Code is committed to main and pushed each night to nightly- After no more than 1 week on main, code is promoted to the `preview` channel- After 1 week the most recent `preview` channel is promoted to `stable` channel- Patch fixes will be produced against both `preview` and `stable` as needed, with the final 'patch' version number incrementing each time.
### Preview
These releases will not have been fully vetted and may contain regressions orother outstanding issues. Help us test and install with `preview` tag.
```bashnpm install -g @google/gemini-cli@preview```
### Stable
This will be the full promotion of last week's release + any bug fixes andvalidations. Use `latest` tag.
```bashnpm install -g @google/gemini-cli@latest```
### Nightly
- New releases will be published each day at UTC 00:00. This will be all changes from the main branch as represented at time of release. It should be assumed there are pending validations and issues. Use `nightly` tag.
```bashnpm install -g @google/gemini-cli@nightly```
## Weekly release promotion
Each Tuesday, the on-call engineer will trigger the "Promote Release" workflow.This single action automates the entire weekly release process:
1. **Promotes preview to stable:** The workflow identifies the latest `preview` release and promotes it to `stable`. This becomes the new `latest` version on npm.2. **Promotes nightly to preview:** The latest `nightly` release is then promoted to become the new `preview` version.3. **Prepares for next nightly:** A pull request is automatically created and merged to bump the version in `main` in preparation for the next nightly release.
This process ensures a consistent and reliable release cadence with minimalmanual intervention.
### Source of truth for versioning
To ensure the highest reliability, the release promotion process uses the **NPMregistry as the single source of truth** for determining the current version ofeach release channel (`stable`, `preview`, and `nightly`).
1. **Fetch from NPM:** The workflow begins by querying NPM's `dist-tags` (`latest`, `preview`, `nightly`) to get the exact version strings for the packages currently available to users.2. **Cross-check for integrity:** For each version retrieved from NPM, the workflow performs a critical integrity check: - It verifies that a corresponding **git tag** exists in the repository. - It verifies that a corresponding **GitHub release** has been created.3. **Halt on discrepancy:** If either the git tag or the GitHub Release is missing for a version listed on NPM, the workflow will immediately fail. This strict check prevents promotions from a broken or incomplete previous release and alerts the on-call engineer to a release state inconsistency that must be manually resolved.4. **Calculate next version:** Only after these checks pass does the workflow proceed to calculate the next semantic version based on the trusted version numbers retrieved from NPM.
This NPM-first approach, backed by integrity checks, makes the release processhighly robust and prevents the kinds of versioning discrepancies that can arisefrom relying solely on git history or API outputs.
## Manual releases
For situations requiring a release outside of the regular nightly and weeklypromotion schedule, and NOT already covered by patching process, you can use the`Release: Manual` workflow. This workflow provides a direct way to publish aspecific version from any branch, tag, or commit SHA.
### How to create a manual release
1. Navigate to the **Actions** tab of the repository.2. Select the **Release: Manual** workflow from the list.3. Click the **Run workflow** dropdown button.4. Fill in the required inputs: - **Version**: The exact version to release (for example, `v0.6.1`). This must be a valid semantic version with a `v` prefix. - **Ref**: The branch, tag, or full commit SHA to release from. - **NPM Channel**: The npm channel to publish to. The options are `preview`, `nightly`, `latest` (for stable releases), and `dev`. The default is `dev`. - **Dry Run**: Leave as `true` to run all steps without publishing, or set to `false` to perform a live release. - **Force Skip Tests**: Set to `true` to skip the test suite. This is not recommended for production releases. - **Skip GitHub Release**: Set to `true` to skip creating a GitHub release and create an npm release only. - **Environment**: Select the appropriate environment. The `dev` environment is intended for testing. The `prod` environment is intended for production releases. `prod` is the default and will require authorization from a release administrator.5. Click **Run workflow**.
The workflow will then proceed to test (if not skipped), build, and publish therelease. If the workflow fails during a non-dry run, it will automaticallycreate a GitHub issue with the failure details.
## Rollback/rollforward
In the event that a release has a critical regression, you can quickly roll backto a previous stable version or roll forward to a new patch by changing the npm`dist-tag`. The `Release: Change Tags` workflow provides a safe and controlledway to do this.
This is the preferred method for both rollbacks and rollforwards, as it does notrequire a full release cycle.
### How to change a release tag
1. Navigate to the **Actions** tab of the repository.2. Select the **Release: Change Tags** workflow from the list.3. Click the **Run workflow** dropdown button.4. Fill in the required inputs: - **Version**: The existing package version that you want to point the tag to (for example, `0.5.0-preview-2`). This version **must** already be published to the npm registry. - **Channel**: The npm `dist-tag` to apply (for example, `preview`, `stable`). - **Dry Run**: Leave as `true` to log the action without making changes, or set to `false` to perform the live tag change. - **Environment**: Select the appropriate environment. The `dev` environment is intended for testing. The `prod` environment is intended for production releases. `prod` is the default and will require authorization from a release administrator.5. Click **Run workflow**.
The workflow will then run `npm dist-tag add` for the appropriate `gemini-cli`,`gemini-cli-core` and `gemini-cli-a2a-server` packages, pointing the specifiedchannel to the specified version.
## Patching
If a critical bug that is already fixed on `main` needs to be patched on a`stable` or `preview` release, the process is now highly automated.
### How to patch
#### 1. Create the patch pull request
There are two ways to create a patch pull request:
**Option A: From a GitHub comment (recommended)**
After a pull request containing the fix has been merged, a maintainer can add acomment on that same PR with the following format:
`/patch [channel]`
- **channel** (optional): - _no channel_ - patches both stable and preview channels (default, recommended for most fixes) - `both` - patches both stable and preview channels (same as default) - `stable` - patches only the stable channel - `preview` - patches only the preview channel
Examples:
- `/patch` (patches both stable and preview - default)- `/patch both` (patches both stable and preview - explicit)- `/patch stable` (patches only stable)- `/patch preview` (patches only preview)
The `Release: Patch from Comment` workflow will automatically find the mergecommit SHA and trigger the `Release: Patch (1) Create PR` workflow. If the PR isnot yet merged, it will post a comment indicating the failure.
**Option B: Manually triggering the workflow**
Navigate to the **Actions** tab and run the **Release: Patch (1) Create PR**workflow.
- **Commit**: The full SHA of the commit on `main` that you want to cherry-pick.- **Channel**: The channel you want to patch (`stable` or `preview`).
This workflow will automatically:
1. Find the latest release tag for the channel.2. Create a release branch from that tag if one doesn't exist (for example, `release/v0.5.1-pr-12345`).3. Create a new hotfix branch from the release branch.4. Cherry-pick your specified commit into the hotfix branch.5. Create a pull request from the hotfix branch back to the release branch.
#### 2. Review and merge
Review the automatically created pull request(s) to ensure the cherry-pick wassuccessful and the changes are correct. Once approved, merge the pull request.
<!-- prettier-ignore -->> [!WARNING]> The `release/*` branches are protected by branch protection> rules. A pull request to one of these branches requires at least one review from> a code owner before it can be merged. This ensures that no unauthorized code is> released.
#### 2.5. Adding multiple commits to a hotfix (advanced)
If you need to include multiple fixes in a single patch release, you can addadditional commits to the hotfix branch after the initial patch PR has beencreated:
1. **Start with the primary fix**: Use `/patch` (or `/patch both`) on the most important PR to create the initial hotfix branch and PR.
2. **Checkout the hotfix branch locally**:
```bash git fetch origin git checkout hotfix/v0.5.1/stable/cherry-pick-abc1234 # Use the actual branch name from the PR ```
3. **Cherry-pick additional commits**:
```bash git cherry-pick <commit-sha-1> git cherry-pick <commit-sha-2> # Add as many commits as needed ```
4. **Push the updated branch**:
```bash git push origin hotfix/v0.5.1/stable/cherry-pick-abc1234 ```
5. **Test and review**: The existing patch PR will automatically update with your additional commits. Test thoroughly since you're now releasing multiple changes together.
6. **Update the PR description**: Consider updating the PR title and description to reflect that it includes multiple fixes.
This approach lets you group related fixes into a single patch release whilemaintaining full control over what gets included and how conflicts are resolved.
#### 3. Automatic release
Upon merging the pull request, the `Release: Patch (2) Trigger` workflow isautomatically triggered. It will then start the `Release: Patch (3) Release`workflow, which will:
1. Build and test the patched code.2. Publish the new patch version to npm.3. Create a new GitHub release with the patch notes.
This fully automated process ensures that patches are created and releasedconsistently and reliably.
#### Troubleshooting: Older branch workflows
**Issue**: If the patch trigger workflow fails with errors like "Resource notaccessible by integration" or references to non-existent workflow files (forexample, `patch-release.yml`), this indicates the hotfix branch contains anoutdated version of the workflow files.
**Root cause**: When a PR is merged, GitHub Actions runs the workflow definitionfrom the **source branch** (the hotfix branch), not from the target branch (therelease branch). If the hotfix branch was created from an older release branchthat predates workflow improvements, it will use the old workflow logic.
**Solutions**:
**Option 1: Manual trigger (quick fix)** Manually trigger the updated workflowfrom the branch with the latest workflow code:
```bash# For a preview channel patch with tests skippedgh workflow run release-patch-2-trigger.yml --ref <branch-with-updated-workflow> \ --field ref="hotfix/v0.6.0-preview.2/preview/cherry-pick-abc1234" \ --field workflow_ref=<branch-with-updated-workflow> \ --field dry_run=false \ --field force_skip_tests=true
# For a stable channel patchgh workflow run release-patch-2-trigger.yml --ref <branch-with-updated-workflow> \ --field ref="hotfix/v0.5.1/stable/cherry-pick-abc1234" \ --field workflow_ref=<branch-with-updated-workflow> \ --field dry_run=false \ --field force_skip_tests=false
# Example using main branch (most common case)gh workflow run release-patch-2-trigger.yml --ref main \ --field ref="hotfix/v0.6.0-preview.2/preview/cherry-pick-abc1234" \ --field workflow_ref=main \ --field dry_run=false \ --field force_skip_tests=true```
**Note**: Replace `<branch-with-updated-workflow>` with the branch containingthe latest workflow improvements (usually `main`, but could be a feature branchif testing updates).
**Option 2: Update the hotfix branch** Merge the latest main branch into yourhotfix branch to get the updated workflows:
```bashgit checkout hotfix/v0.6.0-preview.2/preview/cherry-pick-abc1234git merge maingit push```
Then close and reopen the PR to retrigger the workflow with the updated version.
**Option 3: Direct release trigger** Skip the trigger workflow entirely anddirectly run the release workflow:
```bash# Replace channel and release_ref with appropriate valuesgh workflow run release-patch-3-release.yml --ref main \ --field type="preview" \ --field dry_run=false \ --field force_skip_tests=true \ --field release_ref="release/v0.6.0-preview.2"```
### Docker
We also run a Google cloud build called[release-docker.yml](../.gcp/release-docker.yml). Which publishes the sandboxdocker to match your release. This will also be moved to GH and combined withthe main release file once service account permissions are sorted out.
## Release validation
After pushing a new release smoke testing should be performed to ensure that thepackages are working as expected. This can be done by installing the packageslocally and running a set of tests to ensure that they are functioningcorrectly.
- `npx -y @google/gemini-cli@latest --version` to validate the push worked as expected if you were not doing a rc or dev tag- `npx -y @google/gemini-cli@<release tag> --version` to validate the tag pushed appropriately- _This is destructive locally_ `npm uninstall @google/gemini-cli && npm uninstall -g @google/gemini-cli && npm cache clean --force && npm install @google/gemini-cli@<version>`- Smoke testing a basic run through of exercising a few llm commands and tools is recommended to ensure that the packages are working as expected. We'll codify this more in the future.
## Local testing and validation: Changes to the packaging and publishing process
If you need to test the release process without actually publishing to NPM orcreating a public GitHub release, you can trigger the workflow manually from theGitHub UI.
1. Go to the [Actions tab](https://github.com/google-gemini/gemini-cli/actions/workflows/release-manual.yml) of the repository.2. Click on the "Run workflow" dropdown.3. Leave the `dry_run` option checked (`true`).4. Click the "Run workflow" button.
This will run the entire release process but will skip the `npm publish` and`gh release create` steps. You can inspect the workflow logs to ensureeverything is working as expected.
It is crucial to test any changes to the packaging and publishing processlocally before committing them. This ensures that the packages will be publishedcorrectly and that they will work as expected when installed by a user.
To validate your changes, you can perform a dry run of the publishing process.This will simulate the publishing process without actually publishing thepackages to the npm registry.
```bashnpm_package_version=9.9.9 SANDBOX_IMAGE_REGISTRY="registry" SANDBOX_IMAGE_NAME="thename" npm run publish:npm --dry-run```
This command will do the following:
1. Build all the packages.2. Run all the prepublish scripts.3. Create the package tarballs that would be published to npm.4. Print a summary of the packages that would be published.
You can then inspect the generated tarballs to ensure that they contain thecorrect files and that the `package.json` files have been updated correctly. Thetarballs will be created in the root of each package's directory (for example,`packages/cli/google-gemini-cli-0.1.6.tgz`).
By performing a dry run, you can be confident that your changes to the packagingprocess are correct and that the packages will be published successfully.
## Release deep dive
The release process creates two distinct types of artifacts for differentdistribution channels: standard packages for the NPM registry and a single,self-contained executable for GitHub Releases.
Here are the key stages:
**Stage 1: Pre-release sanity checks and versioning**
- **What happens:** Before any files are moved, the process ensures the project is in a good state. This involves running tests, linting, and type-checking (`npm run preflight`). The version number in the root `package.json` and `packages/cli/package.json` is updated to the new release version.
**Stage 2: Building the source code for NPM**
- **What happens:** The TypeScript source code in `packages/core/src` and `packages/cli/src` is compiled into standard JavaScript.- **File movement:** - `packages/core/src/**/*.ts` -> compiled to -> `packages/core/dist/` - `packages/cli/src/**/*.ts` -> compiled to -> `packages/cli/dist/`- **Why:** The TypeScript code written during development needs to be converted into plain JavaScript that can be run by Node.js. The `core` package is built first as the `cli` package depends on it.
**Stage 3: Publishing standard packages to NPM**
- **What happens:** The `npm publish` command is run for the `@google/gemini-cli-core` and `@google/gemini-cli` packages.- **Why:** This publishes them as standard Node.js packages. Users installing via `npm install -g @google/gemini-cli` will download these packages, and `npm` will handle installing the `@google/gemini-cli-core` dependency automatically. The code in these packages is not bundled into a single file.
**Stage 4: Assembling and creating the GitHub release asset**
This stage happens _after_ the NPM publish and creates the single-fileexecutable that enables `npx` usage directly from the GitHub repository.
1. **The JavaScript bundle is created:**
- **What happens:** The built JavaScript from both `packages/core/dist` and `packages/cli/dist`, along with all third-party JavaScript dependencies, are bundled by `esbuild` into a single, executable JavaScript file (for example, `gemini.js`). The `node-pty` library is excluded from this bundle as it contains native binaries. - **Why:** This creates a single, optimized file that contains all the necessary application code. It simplifies execution for users who want to run the CLI without a full `npm install`, as all dependencies (including the `core` package) are included directly.
2. **The `bundle` directory is assembled:**
- **What happens:** A temporary `bundle` folder is created at the project root. The single `gemini.js` executable is placed inside it, along with other essential files. - **File movement:** - `gemini.js` (from esbuild) -> `bundle/gemini.js` - `README.md` -> `bundle/README.md` - `LICENSE` -> `bundle/LICENSE` - `packages/cli/src/utils/*.sb` (sandbox profiles) -> `bundle/` - **Why:** This creates a clean, self-contained directory with everything needed to run the CLI and understand its license and usage.
3. **The GitHub release is created:** - **What happens:** The contents of the `bundle` directory, including the `gemini.js` executable, are attached as assets to a new GitHub Release. - **Why:** This makes the single-file version of the CLI available for direct download and enables the `npx https://github.com/google-gemini/gemini-cli` command, which downloads and runs this specific bundled asset.
**Summary of artifacts**
- **NPM:** Publishes standard, un-bundled Node.js packages. The primary artifact is the code in `packages/cli/dist`, which depends on `@google/gemini-cli-core`.- **GitHub release:** Publishes a single, bundled `gemini.js` file that contains all dependencies, for easy execution via `npx`.
This dual-artifact process ensures that both traditional `npm` users and thosewho prefer the convenience of `npx` have an optimized experience.
## Notifications
Failing release workflows will automatically create an issue with the label`release-failure`.
A notification will be posted to the maintainer's chat channel when issues withthis type are created.
### Modifying chat notifications
Notifications use[GitHub for Google Chat](https://workspace.google.com/marketplace/app/github_for_google_chat/536184076190).To modify the notifications, use `/github-settings` within the chat space.
<!-- prettier-ignore -->> [!WARNING]> The following instructions describe a fragile workaround that depends on the> internal structure of the chat application's UI. It is likely to break with> future updates.
The list of available labels is not currently populated correctly. If you wantto add a label that does not appear alphabetically in the first 30 labels in therepo, you must use your browser's developer tools to manually modify the UI:
1. Open your browser's developer tools (for example, Chrome DevTools).2. In the `/github-settings` dialog, inspect the list of labels.3. Locate one of the `<li>` elements representing a label.4. In the HTML, modify the `data-option-value` attribute of that `<li>` element to the desired label name (for example, `release-failure`).5. Click on your modified label in the UI to select it, then save your settings.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298[ { "label": "docs_tab", "items": [ { "label": "Get started", "items": [ { "label": "Overview", "slug": "docs" }, { "label": "Quickstart", "slug": "docs/get-started" }, { "label": "Installation", "slug": "docs/get-started/installation" }, { "label": "Authentication", "slug": "docs/get-started/authentication" }, { "label": "CLI cheatsheet", "slug": "docs/cli/cli-reference" }, { "label": "Gemini 3 on Gemini CLI", "slug": "docs/get-started/gemini-3" } ] }, { "label": "Use Gemini CLI", "items": [ { "label": "File management", "slug": "docs/cli/tutorials/file-management" }, { "label": "Get started with Agent Skills", "slug": "docs/cli/tutorials/skills-getting-started" }, { "label": "Manage context and memory", "slug": "docs/cli/tutorials/memory-management" }, { "label": "Execute shell commands", "slug": "docs/cli/tutorials/shell-commands" }, { "label": "Manage sessions and history", "slug": "docs/cli/tutorials/session-management" }, { "label": "Plan tasks with todos", "slug": "docs/cli/tutorials/task-planning" }, { "label": "Use Plan Mode with model steering", "badge": "🔬", "slug": "docs/cli/tutorials/plan-mode-steering" }, { "label": "Web search and fetch", "slug": "docs/cli/tutorials/web-tools" }, { "label": "Set up an MCP server", "slug": "docs/cli/tutorials/mcp-setup" }, { "label": "Automate tasks", "slug": "docs/cli/tutorials/automation" } ] }, { "label": "Features", "items": [ { "label": "Extensions", "collapsed": true, "items": [ { "label": "Overview", "slug": "docs/extensions" }, { "label": "User guide: Install and manage", "link": "/docs/extensions/#manage-extensions" }, { "label": "Developer guide: Build extensions", "slug": "docs/extensions/writing-extensions" }, { "label": "Developer guide: Best practices", "slug": "docs/extensions/best-practices" }, { "label": "Developer guide: Releasing", "slug": "docs/extensions/releasing" }, { "label": "Developer guide: Reference", "slug": "docs/extensions/reference" } ] }, { "label": "Agent Skills", "collapsed": true, "items": [ { "label": "Overview", "slug": "docs/cli/skills" }, { "label": "Get started with Agent Skills", "slug": "docs/cli/tutorials/skills-getting-started" }, { "label": "Creating Agent Skills", "slug": "docs/cli/creating-skills" }, { "label": "Using Agent Skills", "slug": "docs/cli/using-agent-skills" }, { "label": "Developer guide: Best practices", "slug": "docs/cli/skills-best-practices" } ] }, { "label": "Auto Memory", "badge": "🔬", "slug": "docs/cli/auto-memory" }, { "label": "Checkpointing", "slug": "docs/cli/checkpointing" }, { "label": "Headless mode", "slug": "docs/cli/headless" }, { "label": "Git worktrees", "badge": "🔬", "slug": "docs/cli/git-worktrees" }, { "label": "Hooks", "collapsed": true, "items": [ { "label": "Overview", "slug": "docs/hooks" }, { "label": "Reference", "slug": "docs/hooks/reference" } ] }, { "label": "IDE integration", "collapsed": true, "items": [ { "label": "Overview", "slug": "docs/ide-integration" }, { "label": "Developer guide: ACP mode", "slug": "docs/cli/acp-mode" } ] }, { "label": "MCP servers", "collapsed": true, "items": [ { "label": "Overview", "slug": "docs/tools/mcp-server" }, { "label": "Resource tools", "slug": "docs/tools/mcp-resources" } ] }, { "label": "Model routing", "slug": "docs/cli/model-routing" }, { "label": "Model selection", "slug": "docs/cli/model" }, { "label": "Model steering", "badge": "🔬", "slug": "docs/cli/model-steering" }, { "label": "Notifications", "badge": "🔬", "slug": "docs/cli/notifications" }, { "label": "Plan mode", "slug": "docs/cli/plan-mode" }, { "label": "Subagents", "slug": "docs/core/subagents" }, { "label": "Remote subagents", "slug": "docs/core/remote-agents" }, { "label": "Rewind", "slug": "docs/cli/rewind" }, { "label": "Sandboxing", "slug": "docs/cli/sandbox" }, { "label": "Settings", "slug": "docs/cli/settings" }, { "label": "Telemetry", "slug": "docs/cli/telemetry" }, { "label": "Token caching", "slug": "docs/cli/token-caching" } ] }, { "label": "Configuration", "items": [ { "label": "Custom commands", "slug": "docs/cli/custom-commands" }, { "label": "Enterprise configuration", "slug": "docs/cli/enterprise" }, { "label": "Ignore files (.geminiignore)", "slug": "docs/cli/gemini-ignore" }, { "label": "Model configuration", "slug": "docs/cli/generation-settings" }, { "label": "Project context (GEMINI.md)", "slug": "docs/cli/gemini-md" }, { "label": "Settings", "slug": "docs/cli/settings" }, { "label": "System prompt override", "slug": "docs/cli/system-prompt" }, { "label": "Themes", "slug": "docs/cli/themes" }, { "label": "Trusted folders", "slug": "docs/cli/trusted-folders" } ] }, { "label": "Development", "items": [ { "label": "Behavioral evaluations", "slug": "docs/behavioral-evals" }, { "label": "Contribution guide", "slug": "docs/contributing" }, { "label": "Integration testing", "slug": "docs/integration-tests" }, { "label": "Issue and PR automation", "slug": "docs/issue-and-pr-automation" }, { "label": "Local development", "slug": "docs/local-development" }, { "label": "NPM package structure", "slug": "docs/npm" } ] } ] }, { "label": "reference_tab", "items": [ { "label": "Reference", "items": [ { "label": "Command reference", "slug": "docs/reference/commands" }, { "label": "Configuration reference", "slug": "docs/reference/configuration" }, { "label": "Keyboard shortcuts", "slug": "docs/reference/keyboard-shortcuts" }, { "label": "Memory import processor", "slug": "docs/reference/memport" }, { "label": "Policy engine", "slug": "docs/reference/policy-engine" }, { "label": "Tools reference", "slug": "docs/reference/tools" } ] } ] }, { "label": "resources_tab", "items": [ { "label": "Resources", "items": [ { "label": "FAQ", "slug": "docs/resources/faq" }, { "label": "Quota and pricing", "slug": "docs/resources/quota-and-pricing" }, { "label": "Terms and privacy", "slug": "docs/resources/tos-privacy" }, { "label": "Troubleshooting", "slug": "docs/resources/troubleshooting" }, { "label": "Uninstall", "slug": "docs/resources/uninstall" } ] } ] }, { "label": "releases_tab", "items": [ { "label": "Releases", "items": [ { "label": "Release notes", "slug": "docs/changelogs/" }, { "label": "Stable release", "slug": "docs/changelogs/latest" }, { "label": "Preview release", "slug": "docs/changelogs/preview" } ] } ] }]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163/** * @license * Copyright 2025 Google LLC * SPDX-License-Identifier: Apache-2.0 */
import { describe, it, expect, beforeEach, afterEach } from 'vitest';import { TestRig } from './test-helper.js';import { spawn, ChildProcess } from 'node:child_process';import { join, resolve } from 'node:path';import { writeFileSync, mkdirSync } from 'node:fs';import { Writable, Readable } from 'node:stream';import { env } from 'node:process';import * as acp from '@agentclientprotocol/sdk';
const sandboxEnv = env['GEMINI_SANDBOX'];const itMaybe = sandboxEnv && sandboxEnv !== 'false' ? it.skip : it;
class MockClient implements acp.Client { updates: acp.SessionNotification[] = []; sessionUpdate = async (params: acp.SessionNotification) => { this.updates.push(params); }; requestPermission = async (): Promise<acp.RequestPermissionResponse> => { throw new Error('unexpected'); };}
describe.skip('ACP Environment and Auth', () => { let rig: TestRig; let child: ChildProcess | undefined;
beforeEach(() => { rig = new TestRig(); });
afterEach(async () => { child?.kill(); child = undefined; await rig.cleanup(); });
itMaybe( 'should load .env from project directory and use the provided API key', async () => { rig.setup('acp-env-loading');
// Create a project directory with a .env file containing a recognizable invalid key const projectDir = resolve(join(rig.testDir!, 'project')); mkdirSync(projectDir, { recursive: true }); writeFileSync( join(projectDir, '.env'), 'GEMINI_API_KEY=test-key-from-env\n', );
const bundlePath = join(import.meta.dirname, '..', 'bundle/gemini.js');
child = spawn('node', [bundlePath, '--acp'], { cwd: rig.homeDir!, stdio: ['pipe', 'pipe', 'inherit'], env: { ...process.env, GEMINI_CLI_HOME: rig.homeDir!, GEMINI_API_KEY: undefined, VERBOSE: 'true', }, });
const input = Writable.toWeb(child.stdin!); const output = Readable.toWeb( child.stdout!, ) as ReadableStream<Uint8Array>; const testClient = new MockClient(); const stream = acp.ndJsonStream(input, output); const connection = new acp.ClientSideConnection(() => testClient, stream);
await connection.initialize({ protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, }, });
// 1. newSession should succeed because it finds the key in .env const { sessionId } = await connection.newSession({ cwd: projectDir, mcpServers: [], });
expect(sessionId).toBeDefined();
// 2. prompt should fail because the key is invalid, // but the error should come from the API, not the internal auth check. await expect( connection.prompt({ sessionId, prompt: [{ type: 'text', text: 'hello' }], }), ).rejects.toSatisfy((error: unknown) => { const acpError = error as acp.RequestError; const errorData = acpError.data as | { error?: { message?: string } } | undefined; const message = String(errorData?.error?.message || acpError.message); // It should NOT be our internal "Authentication required" message expect(message).not.toContain('Authentication required'); // It SHOULD be an API error mentioning the invalid key expect(message).toContain('API key not valid'); return true; });
child.stdin!.end(); }, );
itMaybe( 'should fail with authRequired when no API key is found', async () => { rig.setup('acp-auth-failure');
const bundlePath = join(import.meta.dirname, '..', 'bundle/gemini.js');
child = spawn('node', [bundlePath, '--acp'], { cwd: rig.homeDir!, stdio: ['pipe', 'pipe', 'inherit'], env: { ...process.env, GEMINI_CLI_HOME: rig.homeDir!, GEMINI_API_KEY: undefined, VERBOSE: 'true', }, });
const input = Writable.toWeb(child.stdin!); const output = Readable.toWeb( child.stdout!, ) as ReadableStream<Uint8Array>; const testClient = new MockClient(); const stream = acp.ndJsonStream(input, output); const connection = new acp.ClientSideConnection(() => testClient, stream);
await connection.initialize({ protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, }, });
await expect( connection.newSession({ cwd: resolve(rig.testDir!), mcpServers: [], }), ).rejects.toMatchObject({ message: expect.stringContaining( 'Gemini API key is missing or not configured.', ), });
child.stdin!.end(); }, );});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116/** * @license * Copyright 2025 Google LLC * SPDX-License-Identifier: Apache-2.0 */
import { describe, it, expect, beforeEach, afterEach } from 'vitest';import { TestRig } from './test-helper.js';import { spawn, ChildProcess } from 'node:child_process';import { join } from 'node:path';import { readFileSync, existsSync } from 'node:fs';import { Writable, Readable } from 'node:stream';import { env } from 'node:process';import * as acp from '@agentclientprotocol/sdk';
// Skip in sandbox mode - test spawns CLI directly which behaves differently in containersconst sandboxEnv = env['GEMINI_SANDBOX'];const itMaybe = sandboxEnv && sandboxEnv !== 'false' ? it.skip : it;
// Reuse existing fake responses that return a simple "Hello" responseconst SIMPLE_RESPONSE_PATH = 'hooks-system.session-startup.responses';
class SessionUpdateCollector implements acp.Client { updates: acp.SessionNotification[] = [];
sessionUpdate = async (params: acp.SessionNotification) => { this.updates.push(params); };
requestPermission = async (): Promise<acp.RequestPermissionResponse> => { throw new Error('unexpected'); };}
describe('ACP telemetry', () => { let rig: TestRig; let child: ChildProcess | undefined;
beforeEach(() => { rig = new TestRig(); });
afterEach(async () => { child?.kill(); child = undefined; await rig.cleanup(); });
itMaybe('should flush telemetry when connection closes', async () => { rig.setup('acp-telemetry-flush', { fakeResponsesPath: join(import.meta.dirname, SIMPLE_RESPONSE_PATH), });
const telemetryPath = join(rig.homeDir!, 'telemetry.log'); const bundlePath = join(import.meta.dirname, '..', 'bundle/gemini.js');
child = spawn( 'node', [ bundlePath, '--acp', '--fake-responses', join(rig.testDir!, 'fake-responses.json'), ], { cwd: rig.testDir!, stdio: ['pipe', 'pipe', 'inherit'], env: { ...process.env, GEMINI_API_KEY: 'fake-key', GEMINI_CLI_HOME: rig.homeDir!, GEMINI_TELEMETRY_ENABLED: 'true', GEMINI_TELEMETRY_TRACES_ENABLED: 'true', GEMINI_TELEMETRY_TARGET: 'local', GEMINI_TELEMETRY_OUTFILE: telemetryPath, }, }, );
const input = Writable.toWeb(child.stdin!); const output = Readable.toWeb(child.stdout!) as ReadableStream<Uint8Array>; const testClient = new SessionUpdateCollector(); const stream = acp.ndJsonStream(input, output); const connection = new acp.ClientSideConnection(() => testClient, stream);
await connection.initialize({ protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false } }, });
const { sessionId } = await connection.newSession({ cwd: rig.testDir!, mcpServers: [], });
await connection.prompt({ sessionId, prompt: [{ type: 'text', text: 'Say hello' }], });
expect(JSON.stringify(testClient.updates)).toContain('Hello');
// Close stdin to trigger telemetry flush via runExitCleanup() child.stdin!.end(); await new Promise<void>((resolve) => { child!.on('close', () => resolve()); }); child = undefined;
// gen_ai.output.messages is the last OTEL log emitted (after prompt response) expect(existsSync(telemetryPath)).toBe(true); expect(readFileSync(telemetryPath, 'utf-8')).toContain( 'gen_ai.output.messages', ); });});1{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"Part 1. "}],"role":"model"},"index":0}]},{"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":10,"totalTokenCount":110}},{"candidates":[{"content":{"parts":[{"text":"Part 2."}],"role":"model"},"index":0,"finishReason":"STOP"}]}]}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950/** * @license * Copyright 2026 Google LLC * SPDX-License-Identifier: Apache-2.0 */
import { describe, it, expect, beforeEach, afterEach } from 'vitest';import { TestRig } from './test-helper.js';import { join, dirname } from 'node:path';import { fileURLToPath } from 'node:url';
describe('API Resilience E2E', () => { let rig: TestRig;
beforeEach(() => { rig = new TestRig(); });
afterEach(async () => { await rig.cleanup(); });
it('should not crash when receiving metadata-only chunks in a stream', async () => { await rig.setup('api-resilience-metadata-only', { fakeResponsesPath: join( dirname(fileURLToPath(import.meta.url)), 'api-resilience.responses', ), settings: { planSettings: { modelRouting: false }, }, });
// Run the CLI with a simple prompt. // The fake responses will provide a stream with a metadata-only chunk in the middle. // We use gemini-3-pro-preview to minimize internal service calls. const result = await rig.run({ args: ['hi', '--model', 'gemini-3-pro-preview'], });
// Verify the output contains text from the normal chunks. // If the CLI crashed on the metadata chunk, rig.run would throw. expect(result).toContain('Part 1.'); expect(result).toContain('Part 2.');
// Verify telemetry event for the prompt was still generated const hasUserPromptEvent = await rig.waitForTelemetryEvent('user_prompt'); expect(hasUserPromptEvent).toBe(true); });});123456789{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"I'll go through the multi-step flow on the localhost server."},{"functionCall":{"name":"invoke_agent","args":{"agent_name":"browser_agent","prompt":"Navigate to http://127.0.0.1:18923/multi-step/step1.html, fill in 'testuser' as the username, click Next, then on step 2 select 'Option B' and click Finish. Report the final result page content."}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":50,"totalTokenCount":150}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"navigate_page","args":{"url":"http://127.0.0.1:18923/multi-step/step1.html"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":20,"totalTokenCount":120}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"fill","args":{"selector":"#username","value":"testuser"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":150,"candidatesTokenCount":25,"totalTokenCount":175}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"click","args":{"selector":"#next-btn"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":180,"candidatesTokenCount":20,"totalTokenCount":200}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"take_snapshot","args":{}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":210,"candidatesTokenCount":15,"totalTokenCount":225}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"click","args":{"selector":"#finish-btn"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":240,"candidatesTokenCount":20,"totalTokenCount":260}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"take_snapshot","args":{}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":270,"candidatesTokenCount":15,"totalTokenCount":285}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"complete_task","args":{"result":{"success":true,"summary":"Completed all steps. Step 1: entered username 'testuser'. Step 2: selected default option. Final result page shows 'Multi-Step Complete' with '✓ Complete' status badge."}}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":300,"candidatesTokenCount":40,"totalTokenCount":340}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"I've completed the multi-step flow:\n\n1. **Step 1**: Entered 'testuser' as username and clicked Next\n2. **Step 2**: Confirmed selection and clicked Finish\n3. **Result**: Final page shows 'Multi-Step Complete' with a '✓ Complete' status badge\n\nAll steps were successfully navigated."}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":300,"candidatesTokenCount":60,"totalTokenCount":360}}]}12345{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"I'll navigate to the localhost page and read its content using the browser agent."},{"functionCall":{"name":"invoke_agent","args":{"agent_name":"browser_agent","prompt":"Navigate to http://127.0.0.1:18923/index.html and tell me the page title and list all links on the page"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":40,"totalTokenCount":140}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"navigate_page","args":{"url":"http://127.0.0.1:18923/index.html"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":20,"totalTokenCount":120}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"take_snapshot","args":{}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":150,"candidatesTokenCount":20,"totalTokenCount":170}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"complete_task","args":{"result":{"success":true,"summary":"Page title is 'Test Fixture - Home'. Found 3 links: Contact Form (/form.html), Multi-Step Flow (/multi-step/step1.html), Dynamic Content (/dynamic.html)."}}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":200,"candidatesTokenCount":40,"totalTokenCount":240}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"The localhost test fixture page has:\n\n**Title**: Test Fixture - Home\n\n**Links**:\n1. Contact Form (form.html)\n2. Multi-Step Flow (multi-step/step1.html)\n3. Dynamic Content (dynamic.html)\n\nThe page also has a heading 'Test Fixture Home Page' and footer content."}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":200,"candidatesTokenCount":60,"totalTokenCount":260}}]}12345{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"I'll open https://example.com and check the page title for you."},{"functionCall":{"name":"invoke_agent","args":{"agent_name":"browser_agent","prompt":"Open https://example.com and get the page title"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":35,"totalTokenCount":135}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"navigate_page","args":{"url":"https://example.com"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":20,"totalTokenCount":120}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"take_snapshot","args":{}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":150,"candidatesTokenCount":20,"totalTokenCount":170}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"complete_task","args":{"result":{"success":true,"summary":"The page title is 'Example Domain'."}}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":200,"candidatesTokenCount":30,"totalTokenCount":230}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"I have opened the page and the title is 'Example Domain'. The browser session has been cleaned up successfully."}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":200,"candidatesTokenCount":30,"totalTokenCount":230}}]}1{"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}}]}12345{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"I'll help you with that."},{"functionCall":{"name":"invoke_agent","args":{"agent_name":"browser_agent","prompt":"Open https://example.com and check if there is a heading"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":50,"totalTokenCount":150}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"new_page","args":{"url":"https://example.com"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":50,"totalTokenCount":150}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"take_snapshot","args":{}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":50,"totalTokenCount":150}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"complete_task","args":{"success":true,"summary":"SUCCESS_POLICY_TEST_COMPLETED"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":50,"totalTokenCount":150}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"Task completed successfully. The page has the heading \"Example Domain\"."}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":200,"candidatesTokenCount":50,"totalTokenCount":250}}]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240/** * @license * Copyright 2026 Google LLC * SPDX-License-Identifier: Apache-2.0 */
import { describe, it, expect, beforeEach, afterEach } from 'vitest';import { TestRig, poll } from './test-helper.js';import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';import { execSync } from 'node:child_process';import { existsSync, writeFileSync, readFileSync, mkdirSync } from 'node:fs';import { env } from 'node:process';import stripAnsi from 'strip-ansi';
// Browser agent Chrome DevTools MCP connection is flaky in Docker sandbox.// See: https://github.com/google-gemini/gemini-cli/issues/24382const isDockerSandbox = env['GEMINI_SANDBOX'] === 'docker';
const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);
const chromeAvailable = (() => { try { if (process.platform === 'darwin') { execSync( 'test -d "/Applications/Google Chrome.app" || test -d "/Applications/Chromium.app"', { stdio: 'ignore', }, ); } else if (process.platform === 'linux') { execSync( 'which google-chrome || which chromium-browser || which chromium', { stdio: 'ignore' }, ); } else if (process.platform === 'win32') { const chromePaths = [ 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe', 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe', `${process.env['LOCALAPPDATA'] ?? ''}\\Google\\Chrome\\Application\\chrome.exe`, ]; const found = chromePaths.some((p) => existsSync(p)); if (!found) { execSync('where chrome || where chromium', { stdio: 'ignore' }); } } else { return false; } return true; } catch { return false; }})();
describe.skipIf(!chromeAvailable)('browser-policy', () => { let rig: TestRig;
beforeEach(() => { rig = new TestRig(); });
afterEach(async () => { await rig.cleanup(); });
it.skipIf(isDockerSandbox)( 'should skip confirmation when "Allow all server tools for this session" is chosen', async () => { rig.setup('browser-policy-skip-confirmation', { fakeResponsesPath: join(__dirname, 'browser-policy.responses'), settings: { agents: { overrides: { browser_agent: { enabled: true, }, }, browser: { headless: true, sessionMode: 'isolated', allowedDomains: ['example.com'], }, }, }, });
// Manually trust the folder to avoid the dialog and enable option 3 const geminiDir = join(rig.homeDir!, '.gemini'); mkdirSync(geminiDir, { recursive: true });
// Write to trustedFolders.json const trustedFoldersPath = join(geminiDir, 'trustedFolders.json'); const trustedFolders = { [rig.testDir!]: 'TRUST_FOLDER', }; writeFileSync( trustedFoldersPath, JSON.stringify(trustedFolders, null, 2), );
// Force confirmation for browser agent. // NOTE: We don't force confirm browser tools here because "Allow all server tools" // adds a rule with ALWAYS_ALLOW_PRIORITY (3.9x) which would be overshadowed by // a rule in the user tier (4.x) like the one from this TOML. // By removing the explicit mcp rule, the first MCP tool will still prompt // due to default approvalMode = 'default', and then "Allow all" will correctly // bypass subsequent tools. const policyFile = join(rig.testDir!, 'force-confirm.toml'); writeFileSync( policyFile, `[[rule]]name = "Force confirm browser_agent"toolName = "invoke_agent"argsPattern = "\\"agent_name\\":\\\\s*\\"browser_agent\\""decision = "ask_user"priority = 200`, );
// Update settings.json in both project and home directories to point to the policy file for (const baseDir of [rig.testDir!, rig.homeDir!]) { const settingsPath = join(baseDir, '.gemini', 'settings.json'); if (existsSync(settingsPath)) { const settings = JSON.parse(readFileSync(settingsPath, 'utf-8')); settings.policyPaths = [policyFile]; // Ensure folder trust is enabled settings.security = settings.security || {}; settings.security.folderTrust = settings.security.folderTrust || {}; settings.security.folderTrust.enabled = true; writeFileSync(settingsPath, JSON.stringify(settings, null, 2)); } }
const run = await rig.runInteractive({ approvalMode: 'default', env: { GEMINI_CLI_INTEGRATION_TEST: 'true', }, });
await run.sendKeys( 'Open https://example.com and check if there is a heading\r', ); await run.sendKeys('\r');
// Handle confirmations. // 1. Initial browser_agent delegation (likely only 3 options, so use option 1: Allow once) await poll( () => stripAnsi(run.output).toLowerCase().includes('action required'), 60000, 1000, ); await run.sendKeys('1\r'); await new Promise((r) => setTimeout(r, 2000));
// Handle privacy notice await poll( () => stripAnsi(run.output).toLowerCase().includes('privacy notice'), 5000, 100, ); await run.sendKeys('1\r'); await new Promise((r) => setTimeout(r, 5000));
// new_page (MCP tool, should have 4 options, use option 3: Allow all server tools) await poll( () => { const stripped = stripAnsi(run.output).toLowerCase(); return ( stripped.includes('new_page') && stripped.includes('allow all server tools for this session') ); }, 60000, 1000, );
// Select "Allow all server tools for this session" (option 3) await run.sendKeys('3\r');
// Wait for the browser agent to finish (success or failure) await poll( () => { const stripped = stripAnsi(run.output).toLowerCase(); return ( stripped.includes('completed successfully') || stripped.includes('agent error') ); }, 120000, 1000, );
const output = stripAnsi(run.output).toLowerCase();
expect(output).toContain('browser_agent'); // The test validates that "Allow all server tools" skips subsequent // tool confirmations — the browser agent may still fail due to // Chrome/MCP issues in CI, which is acceptable for this policy test. expect( output.includes('completed successfully') || output.includes('agent error'), ).toBe(true); }, );
it('should show the visible warning when browser agent starts in existing session mode', async () => { rig.setup('browser-session-warning', { fakeResponsesPath: join(__dirname, 'browser-agent.cleanup.responses'), settings: { general: { enableAutoUpdateNotification: false, }, agents: { overrides: { browser_agent: { enabled: true, }, }, browser: { sessionMode: 'existing', headless: true, }, }, }, });
const stdout = await rig.runCommand(['Open https://example.com'], { env: { GEMINI_API_KEY: 'fake-key', GEMINI_TELEMETRY_DISABLED: 'true', DEV: 'true', }, });
expect(stdout).toContain('saved logins will be visible'); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155/** * @license * Copyright 2025 Google LLC * SPDX-License-Identifier: Apache-2.0 */
import { describe, it, expect, beforeEach, afterEach } from 'vitest';import * as fs from 'node:fs/promises';import * as path from 'node:path';import * as os from 'node:os';import { GitService, Storage } from '@google/gemini-cli-core';
describe('Checkpointing Integration', () => { let tmpDir: string; let projectRoot: string; let fakeHome: string; let originalEnv: NodeJS.ProcessEnv;
beforeEach(async () => { tmpDir = await fs.mkdtemp( path.join(os.tmpdir(), 'gemini-checkpoint-test-'), ); projectRoot = path.join(tmpDir, 'project'); fakeHome = path.join(tmpDir, 'home');
await fs.mkdir(projectRoot, { recursive: true }); await fs.mkdir(fakeHome, { recursive: true });
// Save original env originalEnv = { ...process.env };
// Simulate environment with NO global gitconfig process.env['HOME'] = fakeHome; delete process.env['GIT_CONFIG_GLOBAL']; delete process.env['GIT_CONFIG_SYSTEM']; });
afterEach(async () => { // Restore env process.env = originalEnv;
// Cleanup try { await fs.rm(tmpDir, { recursive: true, force: true }); } catch (e) { console.error('Failed to cleanup temp dir', e); } });
it('should successfully create and restore snapshots without global git config', async () => { const storage = new Storage(projectRoot); const gitService = new GitService(projectRoot, storage);
// 1. Initialize await gitService.initialize();
// Verify system config empty file creation // We need to access getHistoryDir logic or replicate it. // Since we don't have access to private getHistoryDir, we can infer it or just trust the functional test.
// 2. Create initial state await fs.writeFile(path.join(projectRoot, 'file1.txt'), 'version 1'); await fs.writeFile(path.join(projectRoot, 'file2.txt'), 'permanent file');
// 3. Create Snapshot const snapshotHash = await gitService.createFileSnapshot('Checkpoint 1'); expect(snapshotHash).toBeDefined();
// 4. Modify files await fs.writeFile( path.join(projectRoot, 'file1.txt'), 'version 2 (BAD CHANGE)', ); await fs.writeFile( path.join(projectRoot, 'file3.txt'), 'new file (SHOULD BE GONE)', ); await fs.rm(path.join(projectRoot, 'file2.txt'));
// 5. Restore await gitService.restoreProjectFromSnapshot(snapshotHash);
// 6. Verify state const file1Content = await fs.readFile( path.join(projectRoot, 'file1.txt'), 'utf-8', ); expect(file1Content).toBe('version 1');
const file2Exists = await fs .stat(path.join(projectRoot, 'file2.txt')) .then(() => true) .catch(() => false); expect(file2Exists).toBe(true); const file2Content = await fs.readFile( path.join(projectRoot, 'file2.txt'), 'utf-8', ); expect(file2Content).toBe('permanent file');
const file3Exists = await fs .stat(path.join(projectRoot, 'file3.txt')) .then(() => true) .catch(() => false); expect(file3Exists).toBe(false); });
it('should ignore user global git config and use isolated identity', async () => { // 1. Create a fake global gitconfig with a specific user const globalConfigPath = path.join(fakeHome, '.gitconfig'); const globalConfigContent = `[user] name = Global User email = global@example.com`; await fs.writeFile(globalConfigPath, globalConfigContent);
// Point HOME to fakeHome so git picks up this global config (if we didn't isolate it) process.env['HOME'] = fakeHome; // Ensure GIT_CONFIG_GLOBAL is NOT set for the process initially, // so it would default to HOME/.gitconfig if GitService didn't override it. delete process.env['GIT_CONFIG_GLOBAL'];
const storage = new Storage(projectRoot); const gitService = new GitService(projectRoot, storage);
await gitService.initialize();
// 2. Create a file and snapshot await fs.writeFile(path.join(projectRoot, 'test.txt'), 'content'); await gitService.createFileSnapshot('Snapshot with global config present');
// 3. Verify the commit author in the shadow repo const historyDir = storage.getHistoryDir();
const { execFileSync } = await import('node:child_process');
const logOutput = execFileSync( 'git', ['log', '-1', '--pretty=format:%an <%ae>'], { cwd: historyDir, env: { ...process.env, GIT_DIR: path.join(historyDir, '.git'), GIT_CONFIG_GLOBAL: path.join(historyDir, '.gitconfig'), GIT_CONFIG_SYSTEM: path.join(historyDir, '.gitconfig_system_empty'), }, encoding: 'utf-8', }, );
expect(logOutput).toBe('Gemini CLI <gemini-cli@google.com>'); expect(logOutput).not.toContain('Global User'); });});123456789101112{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"web_fetch","args":{"prompt":"fetch https://example.com/1"}}},{"functionCall":{"name":"web_fetch","args":{"prompt":"fetch https://example.com/2"}}},{"functionCall":{"name":"web_fetch","args":{"prompt":"fetch https://example.com/3"}}},{"functionCall":{"name":"web_fetch","args":{"prompt":"fetch https://example.com/4"}}},{"functionCall":{"name":"web_fetch","args":{"prompt":"fetch https://example.com/5"}}},{"functionCall":{"name":"web_fetch","args":{"prompt":"fetch https://example.com/6"}}},{"functionCall":{"name":"web_fetch","args":{"prompt":"fetch https://example.com/7"}}},{"functionCall":{"name":"web_fetch","args":{"prompt":"fetch https://example.com/8"}}},{"functionCall":{"name":"web_fetch","args":{"prompt":"fetch https://example.com/9"}}},{"functionCall":{"name":"web_fetch","args":{"prompt":"fetch https://example.com/10"}}},{"functionCall":{"name":"web_fetch","args":{"prompt":"fetch https://example.com/11"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":500,"totalTokenCount":600}}]}{"method":"generateContent","response":{"candidates":[{"content":{"parts":[{"text":"Page 1 content"}],"role":"model"},"finishReason":"STOP","index":0}]}}{"method":"generateContent","response":{"candidates":[{"content":{"parts":[{"text":"Page 2 content"}],"role":"model"},"finishReason":"STOP","index":0}]}}{"method":"generateContent","response":{"candidates":[{"content":{"parts":[{"text":"Page 3 content"}],"role":"model"},"finishReason":"STOP","index":0}]}}{"method":"generateContent","response":{"candidates":[{"content":{"parts":[{"text":"Page 4 content"}],"role":"model"},"finishReason":"STOP","index":0}]}}{"method":"generateContent","response":{"candidates":[{"content":{"parts":[{"text":"Page 5 content"}],"role":"model"},"finishReason":"STOP","index":0}]}}{"method":"generateContent","response":{"candidates":[{"content":{"parts":[{"text":"Page 6 content"}],"role":"model"},"finishReason":"STOP","index":0}]}}{"method":"generateContent","response":{"candidates":[{"content":{"parts":[{"text":"Page 7 content"}],"role":"model"},"finishReason":"STOP","index":0}]}}{"method":"generateContent","response":{"candidates":[{"content":{"parts":[{"text":"Page 8 content"}],"role":"model"},"finishReason":"STOP","index":0}]}}{"method":"generateContent","response":{"candidates":[{"content":{"parts":[{"text":"Page 9 content"}],"role":"model"},"finishReason":"STOP","index":0}]}}{"method":"generateContent","response":{"candidates":[{"content":{"parts":[{"text":"Page 10 content"}],"role":"model"},"finishReason":"STOP","index":0}]}}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"Some requests were rate limited: Rate limit exceeded for host. Please wait 60 seconds before trying again."}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":1000,"candidatesTokenCount":50,"totalTokenCount":1050}}]}123{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"thought":true,"text":"**Observing Initial Conditions**\n\nI'm currently focused on the initial context. I've taken note of the provided date, OS, and working directory. I'm also carefully examining the file structure presented within the current working directory. It's helping me understand the starting point for further analysis.\n\n\n"}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12270,"totalTokenCount":12316,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12270}],"thoughtsTokenCount":46}},{"candidates":[{"content":{"parts":[{"thought":true,"text":"**Assessing User Intent**\n\nI'm now shifting my focus. I've successfully registered the provided data and file structure. My current task is to understand the user's ultimate goal, given the information provided. The \"Hello.\" command is straightforward, but I'm checking if there's an underlying objective.\n\n\n"}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12270,"totalTokenCount":12341,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12270}],"thoughtsTokenCount":71}},{"candidates":[{"content":{"parts":[{"thoughtSignature":"CiQB0e2Kb3dRh+BYdbZvmulSN2Pwbc75DfQOT3H4EN0rn039hoMKfwHR7YpvvyqNKoxXAiCbYw3gbcTr/+pegUpgnsIrt8oQPMytFMjKSsMyshfygc21T2MkyuI6Q5I/fNCcHROWexdZnIeppVCDB2TarN4LGW4T9Yci6n/ynMMFT2xc2/vyHpkDgRM7avhMElnBhuxAY+e4TpxkZIncGWCEHP1TouoKpgEB0e2Kb8Xpwm0hiKhPt2ZLizpxjk+CVtcbnlgv69xo5VsuQ+iNyrVGBGRwNx+eTeNGdGpn6e73WOCZeP91FwOZe7URyL12IA6E6gYWqw0kXJR4hO4p6Lwv49E3+FRiG2C4OKDF8LF5XorYyCHSgBFT1/RUAVj81GDTx1xxtmYKN3xq8Ri+HsPbqU/FM/jtNZKkXXAtufw2Bmw8lJfmugENIv/TQI7xCo8BAdHtim8KgAXJfZ7ASfutVLKTylQeaslyB/SmcHJ0ZiNr5j8WP1prZdb6XnZZ1ZNbhjxUf/ymoxHKGvtTPBgLE9azMj8Lx/k0clhd2a+wNsiIqW9qCzlVah0tBMytpQUjIDtQe9Hj4LLUprF9PUe/xJkj000Z0ZzsgFm2ncdTWZTdkhCQDpyETVAxdE+oklwKJAHR7YpvUjSkD6KwY1gLrOsHKy0UNfn2lMbxjVetKNMVBRqsTg==","text":"Hello."}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12270,"totalTokenCount":12341,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12270}],"thoughtsTokenCount":71}}]}{"method":"generateContent","response":{"candidates":[{"content":{"parts":[{"text":"<state_snapshot>\n <overall_goal>\n <!-- The user has not yet specified a goal. -->\n </overall_goal>\n\n <key_knowledge>\n - OS: linux\n - Date: Friday, October 24, 2025\n </key_knowledge>\n\n <file_system_state>\n - OBSERVED: The directory contains `telemetry.log` and a `.gemini/` directory.\n - OBSERVED: The `.gemini/` directory contains `settings.json` and `settings.json.orig`.\n </file_system_state>\n\n <recent_actions>\n - The user initiated the chat.\n </recent_actions>\n\n <current_plan>\n 1. [TODO] Await the user's first instruction to formulate a plan.\n </current_plan>\n</state_snapshot>"}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":983,"candidatesTokenCount":299,"totalTokenCount":1637,"promptTokensDetails":[{"modality":"TEXT","tokenCount":983}],"thoughtsTokenCount":355}}}{"method":"generateContent","response":{"candidates":[{"content":{"parts":[{"text":"<state_snapshot>\n <overall_goal>\n <!-- The user has not yet specified a goal. -->\n </overall_goal>\n\n <key_knowledge>\n - OS: linux\n - Date: Friday, October 24, 2025\n </key_knowledge>\n\n <file_system_state>\n - OBSERVED: The directory contains `telemetry.log` and a `.gemini/` directory.\n - OBSERVED: The `.gemini/` directory contains `settings.json` and `settings.json.orig`.\n </file_system_state>\n\n <recent_actions>\n - The user initiated the chat.\n </recent_actions>\n\n <current_plan>\n 1. [TODO] Await the user's first instruction to formulate a plan.\n </current_plan>\n</state_snapshot>"}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":983,"candidatesTokenCount":299,"totalTokenCount":1637,"promptTokensDetails":[{"modality":"TEXT","tokenCount":983}],"thoughtsTokenCount":355}}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287/** * @license * Copyright 2026 Google LLC * SPDX-License-Identifier: Apache-2.0 */
import { describe, it, expect, beforeEach, afterEach } from 'vitest';import { TestRig } from './test-helper.js';import * as path from 'node:path';import * as fs from 'node:fs';import { FinishReason, GenerateContentResponse } from '@google/genai';import type { FakeResponse, HistoryTurn } from '@google/gemini-cli-core';
describe('Context Management Fidelity E2E', () => { let rig: TestRig;
function generateRandomString(length: number): string { const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let result = ''; for (let i = 0; i < length; i++) { result += characters.charAt( Math.floor(Math.random() * characters.length), ); } return result; }
beforeEach(() => { rig = new TestRig(); });
afterEach(async () => await rig.cleanup());
it( 'should reproduce the exact context working buffer on resume', { timeout: 300000 }, async () => { // Mock responses to trigger GC (summarization) const snapshotResponse: FakeResponse = { method: 'generateContent', response: { candidates: [ { content: { parts: [ { text: JSON.stringify({ new_facts: ['GC Triggered.'], new_constraints: [], new_tasks: [], resolved_task_ids: [], obsolete_fact_indices: [], obsolete_constraint_indices: [], chronological_summary: 'Snapshot created.', }), }, ], role: 'model', }, finishReason: FinishReason.STOP, index: 0, }, ], } as unknown as GenerateContentResponse, };
const countTokensResponse: FakeResponse = { method: 'countTokens', response: { totalTokens: 1000 }, };
const streamResponse = (text: string): FakeResponse => ({ method: 'generateContentStream', response: [ { candidates: [ { content: { parts: [{ text }], role: 'model' }, finishReason: FinishReason.STOP, index: 0, }, ], }, ] as unknown as GenerateContentResponse[], });
const setupResponses = (fileName: string, mocks: FakeResponse[]) => { const filePath = path.join(rig.testDir!, fileName); fs.writeFileSync( filePath, mocks.map((m) => JSON.stringify(m)).join('\n'), ); return filePath; };
await rig.setup('context-fidelity', { settings: { experimental: { stressTestProfile: true, // Lowers thresholds to trigger GC easily }, }, });
const traceDir = path.join(rig.testDir!, 'traces'); fs.mkdirSync(traceDir, { recursive: true }); const traceLog = path.join(traceDir, 'trace.log');
// Ignore trace and response files to keep environment context clean and stable fs.writeFileSync( path.join(rig.testDir!, '.geminiignore'), 'traces/\nresp*.json\ndebug.log\n', );
const commonEnv = { GEMINI_API_KEY: 'mock-key', GEMINI_CONTEXT_TRACE_DIR: traceDir, GEMINI_CONTEXT_TRACE_ENABLED: 'true', GEMINI_DEBUG_LOG_FILE: path.join(rig.testDir!, 'debug.log'), };
const runMocks: FakeResponse[] = [ streamResponse('Ack 1'), streamResponse('Ack 2'), streamResponse('Ack 3'), streamResponse('Ack 4'), streamResponse('Ack 5'), streamResponse('Ack 6'), streamResponse('Ack 7'), streamResponse('Ack 8'), streamResponse('Ack 9'), streamResponse('Ack 10'), streamResponse('Ack 11'), streamResponse('Ack 12'), ]; for (let i = 0; i < 50; i++) { runMocks.push(snapshotResponse); runMocks.push(countTokensResponse); }
// Turns 1-10: Build up history for (let i = 1; i <= 10; i++) { await rig.run({ args: [ '--debug', i === 1 ? '' : '--resume', i === 1 ? '' : 'latest', '--fake-responses-non-strict', setupResponses(`resp_init_${i}.json`, runMocks), ].filter(Boolean), stdin: `Turn ${i}: ` + generateRandomString(900), env: commonEnv, }); }
// Turn 11: Penultimate turn await rig.run({ args: [ '--debug', '--resume', 'latest', '--fake-responses-non-strict', setupResponses('resp2.json', runMocks), ], stdin: 'Turn 11: ' + generateRandomString(900), env: commonEnv, });
// Turn 12: Breach threshold and force GC await rig.run({ args: [ '--debug', '--resume', 'latest', '--fake-responses-non-strict', setupResponses('resp3.json', runMocks), ], stdin: 'Turn 12: ' + generateRandomString(900), env: commonEnv, });
// Extract the rendered context asset from the log const getRenderedContext = (logContent: string): HistoryTurn[] | null => { const lines = logContent.split('\n'); const renderLines = lines.filter( (l) => l.includes('[Render] Render Sanitized Context for LLM') || l.includes('[Render] Render Context for LLM'), ); if (renderLines.length === 0) return null;
const lastRender = renderLines[renderLines.length - 1]; const detailsMatch = lastRender.match(/\| Details: (.*)$/); if (!detailsMatch) return null;
const details = JSON.parse(detailsMatch[1]); const assetInfo = details.renderedContextSanitized || details.renderedContext; if (assetInfo && assetInfo.$asset) { const assetPath = path.join(traceDir, 'assets', assetInfo.$asset); return JSON.parse(fs.readFileSync(assetPath, 'utf-8')); } return assetInfo; };
const log1 = fs.readFileSync(traceLog, 'utf-8'); const contextBeforeExit = getRenderedContext(log1); expect(contextBeforeExit).toBeDefined(); console.log( 'Context Before Exit (First 2 turns):', JSON.stringify(contextBeforeExit!.slice(0, 2), null, 2), );
// Turn 4: Resume and run a small command await rig.run({ args: [ '--debug', '--resume', 'latest', '--fake-responses-non-strict', setupResponses('resp4.json', runMocks), 'continue', ], env: commonEnv, });
const log2 = fs.readFileSync(traceLog, 'utf-8'); const contextAfterResume = getRenderedContext(log2); expect(contextAfterResume).toBeDefined(); console.log( 'Context After Resume (First 2 turns):', JSON.stringify(contextAfterResume!.slice(0, 2), null, 2), );
expect(contextAfterResume!.length).toBeGreaterThanOrEqual( contextBeforeExit!.length, );
// The environment context is intentionally refreshed on resume to reflect // the current state of the workspace (e.g. new files, current date). // We allow its content to differ but ensure it's still an environment context. const isEnvContext = (turn: HistoryTurn) => turn.content.parts?.some((p) => p.text?.includes('<session_context>'));
for (let i = 0; i < contextBeforeExit!.length; i++) { expect(contextAfterResume![i].id).toBe(contextBeforeExit![i].id);
const turnBefore = contextBeforeExit![i]; const turnAfter = contextAfterResume![i];
if (isEnvContext(turnBefore)) { expect(isEnvContext(turnAfter)).toBe(true); continue; }
expect(turnAfter.content).toEqual(turnBefore.content); }
// Most importantly, synthetic IDs (like summaries) must be stable. const syntheticTurns = contextBeforeExit!.filter( (t: HistoryTurn) => t.content.parts?.some((p) => p.text?.includes('active_tasks')) || (t.id && t.id.length === 32), ); expect(syntheticTurns.length).toBeGreaterThan(0);
const syntheticTurnsAfter = contextAfterResume!.filter( (t: HistoryTurn) => t.content.parts?.some((p) => p.text?.includes('active_tasks')) || (t.id && t.id.length === 32), ); expect(syntheticTurnsAfter.length).toBeGreaterThanOrEqual( syntheticTurns.length, );
// Check if the first synthetic turn is identical (with relaxation for environment context) expect(syntheticTurnsAfter[0].id).toBe(syntheticTurns[0].id); if (isEnvContext(syntheticTurns[0])) { expect(isEnvContext(syntheticTurnsAfter[0])).toBe(true); } else { expect(syntheticTurnsAfter[0].content).toEqual( syntheticTurns[0].content, ); } }, );});1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162/** * @license * Copyright 2025 Google LLC * SPDX-License-Identifier: Apache-2.0 */
import { describe, expect, it, beforeEach, afterEach } from 'vitest';import { TestRig } from './test-helper.js';import { writeFileSync } from 'node:fs';import { join } from 'node:path';
const extension = `{ "name": "test-extension-install", "version": "0.0.1"}`;
const extensionUpdate = `{ "name": "test-extension-install", "version": "0.0.2"}`;
describe('extension install', () => { let rig: TestRig;
beforeEach(() => { rig = new TestRig(); });
afterEach(async () => await rig.cleanup());
it('installs a local extension, verifies a command, and updates it', async () => { rig.setup('extension install test'); const testServerPath = join(rig.testDir!, 'gemini-extension.json'); writeFileSync(testServerPath, extension); try { const result = await rig.runCommand( ['--debug', 'extensions', 'install', `${rig.testDir!}`], { stdin: 'y\n' }, ); expect(result).toContain('test-extension-install');
const listResult = await rig.runCommand([ '--debug', 'extensions', 'list', ]); expect(listResult).toContain('test-extension-install'); writeFileSync(testServerPath, extensionUpdate); const updateResult = await rig.runCommand( ['--debug', 'extensions', 'update', `test-extension-install`], { stdin: 'y\n' }, ); expect(updateResult).toContain('0.0.2'); } finally { await rig.runCommand([ 'extensions', 'uninstall', 'test-extension-install', ]); } });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151/** * @license * Copyright 2025 Google LLC * SPDX-License-Identifier: Apache-2.0 */
import { expect, it, describe, beforeEach, afterEach } from 'vitest';import { TestRig } from './test-helper.js';import { TestMcpServer } from './test-mcp-server.js';import { writeFileSync } from 'node:fs';import { join } from 'node:path';import { safeJsonStringify } from '@google/gemini-cli-core/src/utils/safeJsonStringify.js';
import stripAnsi from 'strip-ansi';
describe('extension reloading', () => { let rig: TestRig;
beforeEach(() => { rig = new TestRig(); });
afterEach(async () => await rig.cleanup());
// always fails // TODO(#14527): Re-enable this once fixed it.skip('installs a local extension, updates it, checks it was reloaded properly', async () => { const serverA = new TestMcpServer(); const portA = await serverA.start({ hello: () => ({ content: [{ type: 'text', text: 'world' }] }), }); const extension = { name: 'test-extension', version: '0.0.1', mcpServers: { 'test-server': { httpUrl: `http://localhost:${portA}/mcp`, }, }, };
rig.setup('extension reload test', { settings: { experimental: { extensionReloading: true }, }, }); const testServerPath = join(rig.testDir!, 'gemini-extension.json'); writeFileSync(testServerPath, safeJsonStringify(extension, 2)); // defensive cleanup from previous tests. try { await rig.runCommand(['extensions', 'uninstall', 'test-extension']); } catch { /* empty */ }
const result = await rig.runCommand( ['--debug', 'extensions', 'install', `${rig.testDir!}`], { stdin: 'y\n' }, ); expect(result).toContain('test-extension');
// Now create the update, but its not installed yet const serverB = new TestMcpServer(); const portB = await serverB.start({ goodbye: () => ({ content: [{ type: 'text', text: 'world' }] }), }); extension.version = '0.0.2'; extension.mcpServers['test-server'].httpUrl = `http://localhost:${portB}/mcp`; writeFileSync(testServerPath, safeJsonStringify(extension, 2));
// Start the CLI. const run = await rig.runInteractive({ args: '--debug' }); await run.expectText('You have 1 extension with an update available'); // See the outdated extension await run.sendText('/extensions list'); await run.type('\r'); await run.expectText('test-extension (v0.0.1) - active (update available)'); // Wait for the UI to settle and retry the command until we see the update await new Promise((resolve) => setTimeout(resolve, 1000));
// Poll for the updated list await rig.pollCommand( async () => { await run.sendText('/mcp list'); await run.type('\r'); }, () => { const output = stripAnsi(run.output); return ( output.includes( 'test-server (from test-extension) - Ready (1 tool)', ) && output.includes('- mcp_test-server_hello') ); }, 30000, // 30s timeout );
// Update the extension, expect the list to update, and mcp servers as well. await run.sendKeys('\u0015/extensions update test-extension'); await run.expectText('/extensions update test-extension'); await run.type('\r'); await new Promise((resolve) => setTimeout(resolve, 500)); await run.type('\r'); await run.expectText( ` * test-server (remote): http://localhost:${portB}/mcp`, ); await run.type('\r'); // consent await run.expectText( 'Extension "test-extension" successfully updated: 0.0.1 → 0.0.2', );
// Poll for the updated extension version await rig.pollCommand( async () => { await run.sendText('/extensions list'); await run.type('\r'); }, () => stripAnsi(run.output).includes( 'test-extension (v0.0.2) - active (updated)', ), 30000, );
// Poll for the updated mcp tool await rig.pollCommand( async () => { await run.sendText('/mcp list'); await run.type('\r'); }, () => { const output = stripAnsi(run.output); return ( output.includes( 'test-server (from test-extension) - Ready (1 tool)', ) && output.includes('- mcp_test-server_goodbye') ); }, 30000, );
await run.sendText('/quit'); await run.type('\r');
// Clean things up. await serverA.stop(); await serverB.stop(); await rig.runCommand(['extensions', 'uninstall', 'test-extension']); });});12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667/** * @license * Copyright 2025 Google LLC * SPDX-License-Identifier: Apache-2.0 */
import { expect, describe, it, beforeEach, afterEach } from 'vitest';import { TestRig, skipFlaky } from './test-helper.js';
describe.skipIf(skipFlaky)('Interactive file system', () => { let rig: TestRig;
beforeEach(() => { rig = new TestRig(); });
afterEach(async () => { await rig.cleanup(); });
it('should perform a read-then-write sequence', async () => { const fileName = 'version.txt'; await rig.setup('interactive-read-then-write', { settings: { security: { auth: { selectedType: 'gemini-api-key', }, disableYoloMode: false, }, }, }); rig.createFile(fileName, '1.0.0');
const run = await rig.runInteractive({ env: { GEMINI_CLI_TRUST_WORKSPACE: 'true', }, });
// Step 1: Read the file const readPrompt = `Read the version from ${fileName} using the read_file tool`; await run.type(readPrompt); await run.type('\r');
const readCall = await rig.waitForToolCall('read_file', 30000); expect(readCall, 'Expected to find a read_file tool call').toBe(true);
// Wait for the CLI to finish outputting the response and show the prompt again await run.expectText('Type your message', 30000);
// Step 2: Write the file const writePrompt = `now change the version to 1.0.1 in ${fileName} using the write_file tool`; await run.type(writePrompt); await run.type('\r');
// Check tool calls made with right args await rig.expectToolCallSuccess( ['write_file', 'replace'], 30000, (args) => args.includes('1.0.1') && args.includes(fileName), );
// Wait for telemetry to flush and file system to sync, especially in sandboxed environments await rig.waitForTelemetryReady(); }, 120000);});123{"method":"generateContent","response":{"candidates":[{"content":{"parts":[{"text":"{\n \"reasoning\": \"The user is asking for a simple piece of information ('a fun fact'). This is a direct, bounded request with low operational complexity and does not require strategic planning, extensive investigation, or debugging.\",\n \"model_choice\": \"flash\"\n}"}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":1173,"candidatesTokenCount":59,"totalTokenCount":1344,"promptTokensDetails":[{"modality":"TEXT","tokenCount":1173}],"thoughtsTokenCount":112}}}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"thought":true,"text":"**Locating a fun fact**\n\nI'm now searching for a fun fact using the web search tool, focusing on finding something engaging and potentially surprising. The goal is to provide a brief, interesting piece of information.\n\n\n"}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12226,"totalTokenCount":12255,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12226}],"thoughtsTokenCount":29}},{"candidates":[{"content":{"parts":[{"thoughtSignature":"CikB0e2Kb1vYSbIdmBfclWY7z4mOZgPxUGi3CtNXYYV9CSmG+SpVXZZkmQpZAdHtim9HVruyrUZZcHKDvIfn3j6/zLMgepC4Pqd79pG641PkPJnnCqEfVFRxmE2NX3Tj2lwRhtuIYT9Cc3CfvWGjbuuvwzynMCApxpIvxdXac/fXJYeRHTsKQQHR7Ypv6eOvWUFUTRGm1x29v8ZnGjtudG31H/Dgc65Y47c594ZJfX9RqJJil0I52Bxsm8UQ74rbARqwT7zYEbNO","functionCall":{"name":"google_web_search","args":{"query":"fun fact"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12226,"candidatesTokenCount":17,"totalTokenCount":12272,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12226}],"thoughtsTokenCount":29}}]}{"method":"generateContent","response":{"candidates":[{"content":{"parts":[{"text":"Here's a fun fact: A day on Venus is longer than a year on Venus. It takes approximately 243 Earth days for Venus to rotate once on its axis, while its orbit around the Sun is about 225 Earth days."}],"role":"model"},"finishReason":"STOP","groundingMetadata":{"searchEntryPoint":{"renderedContent":"<style>\n.container {\n align-items: center;\n border-radius: 8px;\n display: flex;\n font-family: Google Sans, Roboto, sans-serif;\n font-size: 14px;\n line-height: 20px;\n padding: 8px 12px;\n}\n.chip {\n display: inline-block;\n border: solid 1px;\n border-radius: 16px;\n min-width: 14px;\n padding: 5px 16px;\n text-align: center;\n user-select: none;\n margin: 0 8px;\n -webkit-tap-highlight-color: transparent;\n}\n.carousel {\n overflow: auto;\n scrollbar-width: none;\n white-space: nowrap;\n margin-right: -12px;\n}\n.headline {\n display: flex;\n margin-right: 4px;\n}\n.gradient-container {\n position: relative;\n}\n.gradient {\n position: absolute;\n transform: translate(3px, -9px);\n height: 36px;\n width: 9px;\n}\n@media (prefers-color-scheme: light) {\n .container {\n background-color: #fafafa;\n box-shadow: 0 0 0 1px #0000000f;\n }\n .headline-label {\n color: #1f1f1f;\n }\n .chip {\n background-color: #ffffff;\n border-color: #d2d2d2;\n color: #5e5e5e;\n text-decoration: none;\n }\n .chip:hover {\n background-color: #f2f2f2;\n }\n .chip:focus {\n background-color: #f2f2f2;\n }\n .chip:active {\n background-color: #d8d8d8;\n border-color: #b6b6b6;\n }\n .logo-dark {\n display: none;\n }\n .gradient {\n background: linear-gradient(90deg, #fafafa 15%, #fafafa00 100%);\n }\n}\n@media (prefers-color-scheme: dark) {\n .container {\n background-color: #1f1f1f;\n box-shadow: 0 0 0 1px #ffffff26;\n }\n .headline-label {\n color: #fff;\n }\n .chip {\n background-color: #2c2c2c;\n border-color: #3c4043;\n color: #fff;\n text-decoration: none;\n }\n .chip:hover {\n background-color: #353536;\n }\n .chip:focus {\n background-color: #353536;\n }\n .chip:active {\n background-color: #464849;\n border-color: #53575b;\n }\n .logo-light {\n display: none;\n }\n .gradient {\n background: linear-gradient(90deg, #1f1f1f 15%, #1f1f1f00 100%);\n }\n}\n</style>\n<div class=\"container\">\n <div class=\"headline\">\n <svg class=\"logo-light\" width=\"18\" height=\"18\" viewBox=\"9 9 35 35\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M42.8622 27.0064C42.8622 25.7839 42.7525 24.6084 42.5487 23.4799H26.3109V30.1568H35.5897C35.1821 32.3041 33.9596 34.1222 32.1258 35.3448V39.6864H37.7213C40.9814 36.677 42.8622 32.2571 42.8622 27.0064V27.0064Z\" fill=\"#4285F4\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M26.3109 43.8555C30.9659 43.8555 34.8687 42.3195 37.7213 39.6863L32.1258 35.3447C30.5898 36.3792 28.6306 37.0061 26.3109 37.0061C21.8282 37.0061 18.0195 33.9811 16.6559 29.906H10.9194V34.3573C13.7563 39.9841 19.5712 43.8555 26.3109 43.8555V43.8555Z\" fill=\"#34A853\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M16.6559 29.8904C16.3111 28.8559 16.1074 27.7588 16.1074 26.6146C16.1074 25.4704 16.3111 24.3733 16.6559 23.3388V18.8875H10.9194C9.74388 21.2072 9.06992 23.8247 9.06992 26.6146C9.06992 29.4045 9.74388 32.022 10.9194 34.3417L15.3864 30.8621L16.6559 29.8904V29.8904Z\" fill=\"#FBBC05\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M26.3109 16.2386C28.85 16.2386 31.107 17.1164 32.9095 18.8091L37.8466 13.8719C34.853 11.082 30.9659 9.3736 26.3109 9.3736C19.5712 9.3736 13.7563 13.245 10.9194 18.8875L16.6559 23.3388C18.0195 19.2636 21.8282 16.2386 26.3109 16.2386V16.2386Z\" fill=\"#EA4335\"/>\n </svg>\n <svg class=\"logo-dark\" width=\"18\" height=\"18\" viewBox=\"0 0 48 48\" xmlns=\"http://www.w3.org/2000/svg\">\n <circle cx=\"24\" cy=\"23\" fill=\"#FFF\" r=\"22\"/>\n <path d=\"M33.76 34.26c2.75-2.56 4.49-6.37 4.49-11.26 0-.89-.08-1.84-.29-3H24.01v5.99h8.03c-.4 2.02-1.5 3.56-3.07 4.56v.75l3.91 2.97h.88z\" fill=\"#4285F4\"/>\n <path d=\"M15.58 25.77A8.845 8.845 0 0 0 24 31.86c1.92 0 3.62-.46 4.97-1.31l4.79 3.71C31.14 36.7 27.65 38 24 38c-5.93 0-11.01-3.4-13.45-8.36l.17-1.01 4.06-2.85h.8z\" fill=\"#34A853\"/>\n <path d=\"M15.59 20.21a8.864 8.864 0 0 0 0 5.58l-5.03 3.86c-.98-2-1.53-4.25-1.53-6.64 0-2.39.55-4.64 1.53-6.64l1-.22 3.81 2.98.22 1.08z\" fill=\"#FBBC05\"/>\n <path d=\"M24 14.14c2.11 0 4.02.75 5.52 1.98l4.36-4.36C31.22 9.43 27.81 8 24 8c-5.93 0-11.01 3.4-13.45 8.36l5.03 3.85A8.86 8.86 0 0 1 24 14.14z\" fill=\"#EA4335\"/>\n </svg>\n <div class=\"gradient-container\"><div class=\"gradient\"></div></div>\n </div>\n <div class=\"carousel\">\n <a class=\"chip\" href=\"https://vertexaisearch.cloud.google.com/grounding-api-redirect/AUZIYQGn08vWlJZ4WluVTi_HlxdQkeXfoN9NWENM8cEINX-BCIIAjcsUGPJ6fPYpoDZM8jiOnbW3cfNip1ONou6w0w34KxnYlV8uNgO8fzTZTkxAcORxmy0KeaUnVbKd6AL6i8M05TqIWCzB4flc3XIEtwVAYStd5HFtahr75GNSZ_VzV1mD1POLYD2rwTfT\">fun fact</a>\n </div>\n</div>\n"},"groundingChunks":[{"web":{"uri":"https://vertexaisearch.cloud.google.com/grounding-api-redirect/AUZIYQF-NBVWZeEqhT2BixBuiSaCHeF50iewha2f3M2FfpiNsStuPxhc3sLEzXLR7IFsBbzUBO2kbUmm-usnToWabMSvOIT4ZnTXedj5ZkpwFlYyuadyuBhLNKKJQtOGgg9JTNiwvKxBWt2beHYUjelTJXfVPb0Iy8SVJTahtA3GDA==","title":"hellosubs.co"}}],"groundingSupports":[{"segment":{"startIndex":66,"endIndex":197,"text":"It takes approximately 243 Earth days for Venus to rotate once on its axis, while its orbit around the Sun is about 225 Earth days."},"groundingChunkIndices":[0]}],"webSearchQueries":["fun fact"]},"index":0}],"usageMetadata":{"promptTokenCount":8186,"candidatesTokenCount":65,"totalTokenCount":16468,"cachedContentTokenCount":5360,"promptTokensDetails":[{"modality":"TEXT","tokenCount":8186}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":5360}],"toolUsePromptTokenCount":8207,"toolUsePromptTokensDetails":[{"modality":"TEXT","tokenCount":8207}],"thoughtsTokenCount":10}}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155/** * @license * Copyright 2025 Google LLC * SPDX-License-Identifier: Apache-2.0 */
// Unset NO_COLOR environment variable to ensure consistent theme behavior between local and CI test runsif (process.env['NO_COLOR'] !== undefined) { delete process.env['NO_COLOR'];}
import { mkdir, readdir, rm, readFile } from 'node:fs/promises';import { join, dirname, extname } from 'node:path';import { fileURLToPath } from 'node:url';import { resolveRipgrepPath } from '../packages/core/src/tools/ripGrep.js';import { disableMouseTracking } from '@google/gemini-cli-core';import { isolateTestEnv } from '../packages/test-utils/src/env-setup.js';import { createServer, type Server } from 'node:http';
const __dirname = dirname(fileURLToPath(import.meta.url));const rootDir = join(__dirname, '..');const integrationTestsDir = join(rootDir, '.integration-tests');let runDir = ''; // Make runDir accessible in teardownlet fixtureServer: Server | undefined;
const FIXTURE_PORT = 18923;const FIXTURE_DIR = join(__dirname, 'test-fixtures');
const MIME_TYPES: Record<string, string> = { '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml',};
async function startFixtureServer(): Promise<number> { return new Promise((resolve, reject) => { const server = createServer(async (req, res) => { const urlPath = req.url?.split('?')[0] || '/'; const relativePath = urlPath === '/' ? 'index.html' : urlPath; const filePath = join(FIXTURE_DIR, relativePath);
if (!filePath.startsWith(FIXTURE_DIR)) { res.writeHead(403, { 'Content-Type': 'text/html' }); res.end('<h1>403 Forbidden</h1>'); return; }
try { const content = await readFile(filePath); const ext = extname(filePath); res.writeHead(200, { 'Content-Type': MIME_TYPES[ext] || 'application/octet-stream', }); res.end(content); } catch { res.writeHead(404, { 'Content-Type': 'text/html' }); res.end('<h1>404 Not Found</h1>'); } });
server.on('error', (err: NodeJS.ErrnoException) => { if (err.code === 'EADDRINUSE') { console.warn( `Port ${FIXTURE_PORT} in use, trying ${FIXTURE_PORT + 1}...`, ); server.listen(FIXTURE_PORT + 1, '127.0.0.1'); } else { reject(err); } });
server.on('listening', () => { const addr = server.address(); const port = typeof addr === 'object' && addr ? addr.port : FIXTURE_PORT; fixtureServer = server; console.log(`Test fixture server listening on http://127.0.0.1:${port}`); resolve(port); });
server.listen(FIXTURE_PORT, '127.0.0.1'); });}
export async function setup() { runDir = join(integrationTestsDir, `${Date.now()}`); await mkdir(runDir, { recursive: true });
// Isolate environment variables isolateTestEnv(runDir);
// Download ripgrep to avoid race conditions in parallel tests const available = await resolveRipgrepPath(); if (!available) { throw new Error('Failed to download ripgrep binary'); }
// Start the test fixture server const port = await startFixtureServer(); process.env['TEST_FIXTURE_PORT'] = String(port);
// Clean up old test runs, but keep the latest few for debugging try { const testRuns = await readdir(integrationTestsDir); if (testRuns.length > 5) { const oldRuns = testRuns.sort().slice(0, testRuns.length - 5); await Promise.all( oldRuns.map((oldRun) => rm(join(integrationTestsDir, oldRun), { recursive: true, force: true, }), ), ); } } catch (e) { console.error('Error cleaning up old test runs:', e); }
process.env['INTEGRATION_TEST_FILE_DIR'] = runDir;
if (process.env['KEEP_OUTPUT']) { console.log(`Keeping output for test run in: ${runDir}`); } process.env['VERBOSE'] = process.env['VERBOSE'] ?? 'false';
console.log(`\nIntegration test output directory: ${runDir}`);}
export async function teardown() { // Stop the fixture server if (fixtureServer) { await new Promise<void>((resolve) => { fixtureServer!.close(() => resolve()); }); fixtureServer = undefined; }
// Disable mouse tracking if (process.stdout.isTTY) { disableMouseTracking(); }
// Cleanup the test run directory unless KEEP_OUTPUT is set if (process.env['KEEP_OUTPUT'] !== 'true' && runDir) { try { await rm(runDir, { recursive: true, force: true }); } catch (e) { console.warn('Failed to clean up test run directory:', e); } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495/** * @license * Copyright 2025 Google LLC * SPDX-License-Identifier: Apache-2.0 */
import { WEB_SEARCH_TOOL_NAME } from '../packages/core/src/tools/tool-names.js';import { describe, it, expect, beforeEach, afterEach } from 'vitest';import { TestRig, printDebugInfo, assertModelHasOutput, checkModelOutputContent,} from './test-helper.js';
describe('web search tool', () => { let rig: TestRig;
beforeEach(() => { rig = new TestRig(); });
afterEach(async () => await rig.cleanup());
it('should be able to search the web', async () => { await rig.setup('should be able to search the web', { settings: { tools: { core: [WEB_SEARCH_TOOL_NAME] } }, });
let result; try { result = await rig.run({ args: `what is the weather in London` }); } catch (error) { // Network errors can occur in CI environments if ( error instanceof Error && (error.message.includes('network') || error.message.includes('timeout')) ) { console.warn( 'Skipping test due to network error:', (error as Error).message, ); return; // Skip the test } throw error; // Re-throw if not a network error }
const foundToolCall = await rig.waitForToolCall(WEB_SEARCH_TOOL_NAME);
// Add debugging information if (!foundToolCall) { const allTools = printDebugInfo(rig, result);
// Check if the tool call failed due to network issues const failedSearchCalls = allTools.filter( (t) => t.toolRequest.name === WEB_SEARCH_TOOL_NAME && !t.toolRequest.success, ); if (failedSearchCalls.length > 0) { console.warn( `${WEB_SEARCH_TOOL_NAME} tool was called but failed, possibly due to network issues`, ); console.warn( 'Failed calls:', failedSearchCalls.map((t) => t.toolRequest.args), ); return; // Skip the test if network issues } }
expect( foundToolCall, `Expected to find a call to ${WEB_SEARCH_TOOL_NAME}`, ).toBeTruthy();
assertModelHasOutput(result); const hasExpectedContent = checkModelOutputContent(result, { expectedContent: ['weather', 'london'], testName: 'Google web search test', });
// If content was missing, log the search queries used if (!hasExpectedContent) { const searchCalls = rig .readToolLogs() .filter((t) => t.toolRequest.name === WEB_SEARCH_TOOL_NAME); if (searchCalls.length > 0) { console.warn( 'Search queries used:', searchCalls.map((t) => t.toolRequest.args), ); } } });});12{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"list_dir","args":{"path":"."}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":10,"totalTokenCount":20}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"Final Answer"}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":10,"totalTokenCount":20}}]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338/** * @license * Copyright 2025 Google LLC * SPDX-License-Identifier: Apache-2.0 */
import { describe, it, expect, beforeEach, afterEach } from 'vitest';import { TestRig, normalizePath } from './test-helper.js';import { join } from 'node:path';import { writeFileSync } from 'node:fs';
describe('Hooks Agent Flow', () => { let rig: TestRig;
beforeEach(() => { rig = new TestRig(); });
afterEach(async () => { if (rig) { await rig.cleanup(); } });
describe('BeforeAgent Hooks', () => { it('should inject additional context via BeforeAgent hook', async () => { await rig.setup('should inject additional context via BeforeAgent hook', { fakeResponsesPath: join( import.meta.dirname, 'hooks-agent-flow.responses', ), });
const hookScript = ` try { const output = { decision: "allow", hookSpecificOutput: { hookEventName: "BeforeAgent", additionalContext: "SYSTEM INSTRUCTION: This is injected context." } }; process.stdout.write(JSON.stringify(output)); } catch (e) { console.error('Failed to write stdout:', e); process.exit(1); } console.error('DEBUG: BeforeAgent hook executed'); `;
const scriptPath = join(rig.testDir!, 'before_agent_context.cjs'); writeFileSync(scriptPath, hookScript);
await rig.setup('should inject additional context via BeforeAgent hook', { settings: { hooksConfig: { enabled: true, }, hooks: { BeforeAgent: [ { hooks: [ { type: 'command', command: `node "${scriptPath}"`, timeout: 5000, }, ], }, ], }, }, });
await rig.run({ args: 'Hello test' });
// Verify hook execution and telemetry const hookTelemetryFound = await rig.waitForTelemetryEvent('hook_call'); expect(hookTelemetryFound).toBeTruthy();
const hookLogs = rig.readHookLogs(); const beforeAgentLog = hookLogs.find( (log) => log.hookCall.hook_event_name === 'BeforeAgent', );
expect(beforeAgentLog).toBeDefined(); expect(beforeAgentLog?.hookCall.stdout).toContain('injected context'); expect(beforeAgentLog?.hookCall.stdout).toContain('"decision":"allow"'); expect(beforeAgentLog?.hookCall.stdout).toContain( 'SYSTEM INSTRUCTION: This is injected context.', ); }); });
describe('AfterAgent Hooks', () => { it('should receive prompt and response in AfterAgent hook', async () => { await rig.setup('should receive prompt and response in AfterAgent hook', { fakeResponsesPath: join( import.meta.dirname, 'hooks-agent-flow.responses', ), });
const hookScript = ` const fs = require('fs'); try { const input = fs.readFileSync(0, 'utf-8'); console.error('DEBUG: AfterAgent hook input received'); process.stdout.write("Received Input: " + input); } catch (err) { console.error('Hook Failed:', err); process.exit(1); } `;
const scriptPath = rig.createScript('after_agent_verify.cjs', hookScript);
rig.setup('should receive prompt and response in AfterAgent hook', { settings: { hooksConfig: { enabled: true, }, hooks: { AfterAgent: [ { hooks: [ { type: 'command', command: normalizePath(`node "${scriptPath}"`)!, timeout: 5000, }, ], }, ], }, }, });
await rig.run({ args: 'Hello validation' });
const hookTelemetryFound = await rig.waitForTelemetryEvent('hook_call'); expect(hookTelemetryFound).toBeTruthy();
const hookLogs = rig.readHookLogs(); const afterAgentLog = hookLogs.find( (log) => log.hookCall.hook_event_name === 'AfterAgent', );
expect(afterAgentLog).toBeDefined(); // Verify the hook stdout contains the input we echoed which proves the // hook received the prompt and response expect(afterAgentLog?.hookCall.stdout).toContain('Received Input'); expect(afterAgentLog?.hookCall.stdout).toContain('Hello validation'); // The fake response contains "Hello World" expect(afterAgentLog?.hookCall.stdout).toContain('Hello World'); });
it('should process clearContext in AfterAgent hook output', async () => { rig.setup('should process clearContext in AfterAgent hook output', { fakeResponsesPath: join( import.meta.dirname, 'hooks-system.after-agent.responses', ), });
// BeforeModel hook to track message counts across LLM calls const messageCountFile = join(rig.testDir!, 'message-counts.json'); const escapedPath = JSON.stringify(messageCountFile); const beforeModelScript = ` const fs = require('fs'); const input = JSON.parse(fs.readFileSync(0, 'utf-8')); const messageCount = input.llm_request?.contents?.length || 0; let counts = []; try { counts = JSON.parse(fs.readFileSync(${escapedPath}, 'utf-8')); } catch (e) {} counts.push(messageCount); fs.writeFileSync(${escapedPath}, JSON.stringify(counts)); console.log(JSON.stringify({ decision: 'allow' })); `; const beforeModelScriptPath = rig.createScript( 'before_model_counter.cjs', beforeModelScript, );
const afterAgentScript = ` const fs = require('fs'); const input = JSON.parse(fs.readFileSync(0, 'utf-8')); if (input.stop_hook_active) { // Retry turn: allow execution to proceed (breaks the loop) console.log(JSON.stringify({ decision: 'allow' })); } else { // First call: block and clear context to trigger the retry console.log(JSON.stringify({ decision: 'block', reason: 'Security policy triggered', hookSpecificOutput: { hookEventName: 'AfterAgent', clearContext: true } })); } `; const afterAgentScriptPath = rig.createScript( 'after_agent_clear.cjs', afterAgentScript, );
rig.setup('should process clearContext in AfterAgent hook output', { settings: { hooksConfig: { enabled: true, }, hooks: { BeforeModel: [ { hooks: [ { type: 'command', command: normalizePath(`node "${beforeModelScriptPath}"`)!, timeout: 5000, }, ], }, ], AfterAgent: [ { hooks: [ { type: 'command', command: normalizePath(`node "${afterAgentScriptPath}"`)!, timeout: 5000, }, ], }, ], }, }, });
const result = await rig.run({ args: 'Hello test' });
const hookTelemetryFound = await rig.waitForTelemetryEvent('hook_call'); expect(hookTelemetryFound).toBeTruthy();
const hookLogs = rig.readHookLogs(); const afterAgentLog = hookLogs.find( (log) => log.hookCall.hook_event_name === 'AfterAgent', );
expect(afterAgentLog).toBeDefined(); expect(afterAgentLog?.hookCall.stdout).toContain('clearContext'); expect(afterAgentLog?.hookCall.stdout).toContain('true'); expect(result).toContain('Security policy triggered');
// Verify context was cleared: second call should not have more messages than first const countsRaw = rig.readFile('message-counts.json'); const counts = JSON.parse(countsRaw) as number[]; expect(counts.length).toBeGreaterThanOrEqual(2); expect(counts[1]).toBeLessThanOrEqual(counts[0]); }); });
describe('Multi-step Loops', () => { it('should fire BeforeAgent and AfterAgent exactly once per turn despite tool calls', async () => { await rig.setup( 'should fire BeforeAgent and AfterAgent exactly once per turn despite tool calls', { fakeResponsesPath: join( import.meta.dirname, 'hooks-agent-flow-multistep.responses', ), }, );
// Create script files for hooks const baPath = rig.createScript( 'ba_fired.cjs', "console.log('BeforeAgent Fired');", ); const aaPath = rig.createScript( 'aa_fired.cjs', "console.log('AfterAgent Fired');", );
await rig.setup( 'should fire BeforeAgent and AfterAgent exactly once per turn despite tool calls', { settings: { hooksConfig: { enabled: true, }, hooks: { BeforeAgent: [ { hooks: [ { type: 'command', command: normalizePath(`node "${baPath}"`)!, timeout: 5000, }, ], }, ], AfterAgent: [ { hooks: [ { type: 'command', command: normalizePath(`node "${aaPath}"`)!, timeout: 5000, }, ], }, ], }, }, }, );
await rig.run({ args: 'Do a multi-step task' });
const hookLogs = rig.readHookLogs(); const beforeAgentLogs = hookLogs.filter( (log) => log.hookCall.hook_event_name === 'BeforeAgent', ); const afterAgentLogs = hookLogs.filter( (log) => log.hookCall.hook_event_name === 'AfterAgent', );
expect(beforeAgentLogs).toHaveLength(1);
expect(afterAgentLogs).toHaveLength(1);
const afterAgentLog = afterAgentLogs[0]; expect(afterAgentLog).toBeDefined(); expect(afterAgentLog?.hookCall.stdout).toContain('AfterAgent Fired'); }); });});123{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"Hi there!"}],"role":"model"},"finishReason":"STOP","index":0}]}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"Clarification: I am a bot."}],"role":"model"},"finishReason":"STOP","index":0}]}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"Security policy triggered"}],"role":"model"},"finishReason":"STOP","index":0}]}]}1{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"**Addressing the Inquiry**\n\nI've grasped the core of the user's question and identified that no tools are needed. My focus is now on crafting a straightforward, direct response that fully addresses their query without any unnecessary complexity. The goal is to provide a clear and concise answer.\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12777,"totalTokenCount":12802,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12777}],"thoughtsTokenCount":25}},{"candidates":[{"content":{"parts":[{"text":"4","thoughtSignature":"CiQBcsjafBFqw6veocEvtOGGuQcsyHdcNrXDIn19n9ImwBBwcYQKdgFyyNp8g7o8Ji++OXoqml4gbLPIB2DQbXcaRQfRuYefF8RxMEpzJSITZBlT1VpJQoeYmQcb9c8dg/POmo5d3ZcuLbpVJpbjMIV1SoUI4KEn3zqz7a8BFuyq3zY4VEliRWMZO21JMd8qp59M9m64hX7W1YPyzu8KPwFyyNp8aNCD7P1NJDG3csQkiMW/0jWdPkh+7+XxT7i3ku/lYH4yTEShdicPcmnzoPGhEWTUDr/4Lx+A0DnVGQ=="}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12777,"totalTokenCount":12802,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12777}],"thoughtsTokenCount":25}}]}12{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"**Analyzing File Access**\n\nI've realized the `read_file` tool is perfect for accessing the contents of `test-file.txt`. My next step is to call this tool and set the `file_path` parameter to `test-file.txt`.\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12785,"totalTokenCount":12841,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12785}],"thoughtsTokenCount":56}},{"candidates":[{"content":{"parts":[{"functionCall":{"name":"read_file","args":{"file_path":"test-file.txt"}},"thoughtSignature":"CiQBcsjafE9D7iAF+V3wpXP81/VmxiMeSFA6afML/lAB76U6QFQKXgFyyNp8i/vhxpkTQ5Cq81QTeEJDDMaYihzSTFMqO4Vj0+CLNtoy+SC/LmqA+WaXh4tm6UCNFTzB2fpVW13YOU1oVYhLpVpeck746YExu1MOSTAq7AC9Yz8ZoelXdecKdwFyyNp8q0PejiY9K1osdOJ02tOHAzAb8ZCSFHtHamEPxRB93krGMNvuIYC1jM1JnC/fzpH8gYV+0/xkoPJMHpF/aSzWq4kZ/j5cUhMYaqKJTulY8ZZGfawnXG7z0spmmr06gwfgILa+HK++xQhhTphMQCobX5hyCjUBcsjafHY6eJfVNitYmfruLV1mnoYnNViHuAOOOni9jIz4VMIjLbClKkb2rpVfHIjx+vZSHA=="}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12785,"candidatesTokenCount":20,"totalTokenCount":12861,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12785}],"thoughtsTokenCount":56}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"This"}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12889,"candidatesTokenCount":1,"totalTokenCount":12890,"cachedContentTokenCount":12206,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12889}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":12206}]}},{"candidates":[{"content":{"parts":[{"text":" is test content"}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12889,"candidatesTokenCount":4,"totalTokenCount":12893,"cachedContentTokenCount":12206,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12889}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":12206}]}}]}1234{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"**Formulating the Write Operation**\n\nOkay, I'm now clear on the user's intent: they want a file called `approved.txt`, containing the words \"Approved content.\" I've decided to leverage the `write_file` tool. The specific parameter assignments seem straightforward; `file_path` will be \"approved.txt\", and the file's `content` will precisely mirror the desired output string.\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12778,"totalTokenCount":12838,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12778}],"thoughtsTokenCount":60}},{"candidates":[{"content":{"parts":[{"functionCall":{"name":"write_file","args":{"content":"Approved content","file_path":"approved.txt"}},"thoughtSignature":"CiQBcsjafF4NswdygCBTU7cA/yXVRcUI3XHwV+E8BDg/hRr1MaoKZQFyyNp8HRY1qEvivtg0LpYPo1022IfTY3QIeigqGvSoRVospxT5MBggc9nRbwH2vrdhZ772IdqOCrpjNHs3wc+h0AF4JzjlBet6+yC2m7TdenVOkzVAtqnNDMQAIS1gDZyKs8w/CngBcsjafOeuyDQtxuK7JCafKjtfvPvoKOkVxzDetQtHesBkPtv1Xng9dkP77jLH44hn9rrg7yA+za6vssiFZUjC/FU25pCWQgIhM+K7nt3wbAgoOZRqra2gRr3od2D3osV/UpYhy8MoloykqrWvHDOzT/0KScpHarwKXQFyyNp8qabyDYlfElywQBjqQT4f6My7+Ln9AbKZQz4NaEe90ESg4jr4jjANxyd/WKzRheaBq7BYxTHQSeShgQbVjk2D0tZO4hAN+CToMtQwJl95Ss4ZEov6gAwMNA=="}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12778,"candidatesTokenCount":24,"totalTokenCount":12862,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12778}],"thoughtsTokenCount":60}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12939,"totalTokenCount":12939,"cachedContentTokenCount":12203,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12939}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":12203}]}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12939,"totalTokenCount":12939,"cachedContentTokenCount":12203,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12939}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":12203}]}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"**Confirming File Creation**\n\nI've successfully created the file `approved.txt`, and I've verified that it contains the intended content, \"Approved content\". Moving on.\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12887,"totalTokenCount":12932,"cachedContentTokenCount":12198,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12887}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":12198}],"thoughtsTokenCount":45}},{"candidates":[{"content":{"parts":[{"text":"**Assessing File Contents**\n\nI'm now checking the content of `approved.txt`. I used `cat` to display its contents, and it confirms the initial content of \"Approved content\" is present. My next step will be based on this verification.\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12887,"totalTokenCount":12946,"cachedContentTokenCount":12198,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12887}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":12198}],"thoughtsTokenCount":59}},{"candidates":[{"content":{"parts":[{"text":"I have created the file. What would you like me to do next?","thoughtSignature":"CiQBcsjafEAq9BWRwBqUousKwXME0A2Wh1tJI5cJC9ROpr9Cix8KagFyyNp81VagWC/YxtY8zCAiThU3BHMVh5wZIsGIWv1NNIXqACLQLoSeLhWEneb6CBkKdbKBugy6g9+jP5phYt+Vz5oYuO1Op2kM1qWjFmEQyr71TUISNtZ9zrOHNQKKW7K9ukUi0paw85YKoAEBcsjafF6QLINjBWwQPZh6EPVNGk4wojTKglNp7xy5vclYBbq58A6A8AtZUHKYA2cV32SLb2TGcPnkE4iKunvPf6sZy9Uc7gKA+x/OgSl7i5m0wSpMOh9fLpGt4CNtieigpxHkNAdxdZ5qzGvCkBFWYhaZAWGbj7+1YibIKJFNjX9yEz1T5dOQmVmceu80dFyz+fwl7RiOXSGR5xK4J7DeClYBcsjafPUccUubdSVLFmRohU4bBtQzLvXxw25mqm5TKANLKINQoloZ+xfXzfe8xw/WZL/mg30AqQErBXPNnLk5vIWLK7suuFAZ7oXdisTCj3MRa1HQmQ=="}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12887,"candidatesTokenCount":13,"totalTokenCount":12959,"cachedContentTokenCount":12198,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12887}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":12198}],"thoughtsTokenCount":59}}]}1{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"**Initiating String Output**\n\nI'm now fully focused on directly outputting the specified string. The process has been simplified to its core objective, eliminating extraneous steps. All systems are go for immediate execution of the requested string output.\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12419,"totalTokenCount":12439,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12419}],"thoughtsTokenCount":20}},{"candidates":[{"content":{"parts":[{"text":"The security hook modified this request successfully.","thoughtSignature":"CiQBcsjafAsmW87n4ndCW3YiNIqK6jp0zaTwTjz12vWiwbCFNAUKdQFyyNp808SX5BqCBNZt+dlgsPf74u9W6ofevKGwkTTHQZWJEQiJR2j4uRfESTazuawuWfzKfNJq5Zml6fokNR9jzmQM+Jf4FHw95Jd4lneap+YGO9x5nZMNDI1cHRx0vs4BYW9GWY7lBIM8xKtaEkPrwqc88goiAXLI2nx5o6VrBpXs6jzf5maZIauSYw42zlnkqdDEMI20rg=="}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12419,"candidatesTokenCount":7,"totalTokenCount":12446,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12419}],"thoughtsTokenCount":20}}]}1{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"**Initializing File Creation**\n\nI'm starting to think about how to make a new file called `test.txt`. My plan is to use a `write_file` tool. I'll need to specify the location and what the file should contain. For now, it will be empty.\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":13216,"totalTokenCount":13269,"promptTokensDetails":[{"modality":"TEXT","tokenCount":13216}],"thoughtsTokenCount":53}},{"candidates":[{"content":{"parts":[{"functionCall":{"name":"write_file","args":{"file_path":"test.txt","content":""}},"thoughtSignature":"CiQBcsjafJ20Qbx0YvING6aZ0wYoGWJh3eqornOG4E4AfBLiVsQKXwFyyNp8UlwYs/pv9IRQQGhDlrmlOJF2hfQijryyUYLI+qjDYTpZ6KKIfZF4+vS0soL2BJ3eTXA6gaadFEfNQem3WQVeQoKLFoW4Hv4mbasXqQc0K3p15DuSAtZZENTbCnsBcsjafGK+BJyF/Npnd7gyU0TL5PXePT0nuDFjhJDxlSRUJHDP315TewD3PUYsXd10oWsfhy4B5AngyUiBPUoajdsxg8WxaxnOZYqcp8EIuwtGZrCTev6IihT5nE5jj7u0P9vtnCmkAc6p+4O7Q7Jku1uVGqeJChgzI4YKSAFyyNp8EXSdbttV4xzX+NLKkc276L8Y63tnKU6/Y7fc9/58tU29DSdrgwfe9qmvwtTsO0piFXSLazqHJt8h2bgR7A7GnKDiIA=="}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":13216,"candidatesTokenCount":21,"totalTokenCount":13290,"promptTokensDetails":[{"modality":"TEXT","tokenCount":13216}],"thoughtsTokenCount":53}},{"candidates":[{"content":{"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":13216,"candidatesTokenCount":21,"totalTokenCount":13290,"promptTokensDetails":[{"modality":"TEXT","tokenCount":13216}],"thoughtsTokenCount":53}}]}1{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"**Devising a Greeting Phrase**\n\nI've been occupied by the constraint of constructing a five-word salutation. My goal is to make it natural and concise. I'm exploring various combinations to meet the specified word count precisely.\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12587,"totalTokenCount":12612,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12587}],"thoughtsTokenCount":25}},{"candidates":[{"content":{"parts":[{"text":"Hello! How can I help you?","thoughtSignature":"CiQBcsjafHso9FUsdYOCTv1xOLlW4MnjbeYnUUBocz0KNgHSzOcKZAFyyNp8XuI6j2afRczgPL8v1dxfVwAJ+5XDKhWKIYf1/8TKGVHh7xXnPfdYBdQ07Ohe7OZXr92xL/IC7B1U2SHDuAOozC0CCW7aiDysu6Hbo6jzYfW5epKht4QjdxYgcKHySrkKMQFyyNp8jXWlHmox53O/CJPXXz2FAmw+ubHKBpYgRezBpA+byyEY2RbVYlZlEMSNkhs="}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12587,"candidatesTokenCount":7,"totalTokenCount":12619,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12587}],"thoughtsTokenCount":25}}]}12{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"write_file","args":{"content":"original content","file_path":"original.txt"}}}],"role":"model"},"finishReason":"STOP","index":0}]}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"I have created the file."}],"role":"model"},"finishReason":"STOP","index":0}]}]}12{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"**Defining File Creation**\n\nI'm thinking about the user's intent to generate a file named \"input-test.txt\" with the content \" test\". I've determined that the `write_file` tool is suitable. I've parsed `file_path` as \"input-test.txt\" and `content` as \" test\". This should accomplish the user's need.\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12778,"totalTokenCount":12840,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12778}],"thoughtsTokenCount":62}},{"candidates":[{"content":{"parts":[{"functionCall":{"name":"write_file","args":{"file_path":"input-test.txt","content":"test"}},"thoughtSignature":"CiQBcsjafCO/Ifs3Lj/Gtzy2ylSYoGB3GXjJby4F3R8FxWp+hP0KZwFyyNp8oD7KvcSYXDimGOiqAdxtdOJpc2tFJbHm2Jw7ahiuKLtoKZWE+1bBZEWVKxC0dCQIeIcxZ0SaLn7tDbfc2qPzhyUA46d/T1+e314SFLWW1asIOBkQ4T0sFDAFPZ4m9bFm3UkKbAFyyNp8EAnclI0wYCGwpg0AOOV52F5J9Hc2EeaXkGsc6hCnba7aNhPucWYIn2Da8FK2IJAWUWaNvGNGoNUZETaG+iL9+6KRJgN3Ql/wQzQ2pHUvTGHC3RkfMGTQ+YCQKvlOReilps5lDmMnhQpTAXLI2nzcl9Aqd0Nb/w934w+tqz1Jth7GlQVMYktHOl7Hgkoykfh3NzM67SEAilxjowfBL6MY7UBUP3YGwi1CXVVa4d0wHnMD9BJYp2w8ztZch8I="}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12778,"candidatesTokenCount":25,"totalTokenCount":12865,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12778}],"thoughtsTokenCount":62}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"**File Creation Achieved**\n\nI've successfully created the file as requested. Now, I'm ready to move on to the next instruction whenever it arrives. I am now awaiting the next task.\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12940,"totalTokenCount":12965,"cachedContentTokenCount":12203,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12940}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":12203}],"thoughtsTokenCount":25}},{"candidates":[{"content":{"parts":[{"text":"Done.","thoughtSignature":"CiQBcsjafEwfH5zTnAjEjloMcDDflS/MmoH03HXVl8HoQ04vmVIKcQFyyNp8/6HrBz8vokXB1Ms1zW51p32T3Ni3HEbgSFPHMGZt9LHFtLkLzuFrxym66z1Tcb5tqj+7jAdpM/dIUb6ecrKj9FWqMB+QR4BSxdAiJSiL8Rp+Pc5ckCtT1nrv4C5w3/fhCNE4WvZzeyGPt+PACjsBcsjafNWzUJcHxgKp6MYWQ8RW0QrGerM51nkgXHBafxY5KwTznX4B/ETccGnXX3zSciaJiZR1FfudVw=="}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12940,"candidatesTokenCount":1,"totalTokenCount":12966,"cachedContentTokenCount":12203,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12940}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":12203}],"thoughtsTokenCount":25}}]}1234{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"**Formulating a Plan**\n\nOkay, I've outlined the initial steps: I'll use the `write_file` tool to make a file named `multi-event-test.txt` containing the text \"testing multiple events\". After that, I'll need to remember to reply with the phrase as requested. It seems straightforward so far.\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12622,"totalTokenCount":12692,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12622}],"thoughtsTokenCount":70}},{"candidates":[{"content":{"parts":[{"text":"**Confirming the Procedure**\n\nI've solidified the steps. First, I'll create `multi-event-test.txt` using the `write_file` tool with the required content. Following that, my response will be \"BeforeAgent: User request processed.\" This ensures I fulfill both parts of the request.\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12622,"totalTokenCount":12713,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12622}],"thoughtsTokenCount":91}},{"candidates":[{"content":{"parts":[{"functionCall":{"name":"write_file","args":{"file_path":"multi-event-test.txt","content":"testing multiple events"}},"thoughtSignature":"CiQBcsjafIqcYtNLIeBwJi3k5k8jho3QiWM+51Kw5vTQ7/V4qVQKZgFyyNp8mIIB0+Mvwhvo2fACDpTWpRYeOFPGrjZrc+N05S0WGEHzE4Dv9peHKdvZkjGNW+HyYHXoRpd5c/ScdhPxQoVZmZ9K7sRjVxv/nWVDoKnHlSsn94nJ8acjLnj1oqt9cHni0ApyAXLI2nwj5WuLHr+UFIxnqRKCUJboLo6bQMkqR1TsqXbjsgHp3zNQYT+xzbse4PKPLJV48FN6cL9MrrZ81E7k7AVo1cKyrC7ky7tdRH6gYHewIqgQWBIUgMKhLkePH/fYZ6fS7SMrf4Q6DFGHh6pIAAdRCooBAXLI2nxpudEZr+5jZAaAcCMIdij5oZq3s0xsQv/7iWVh8IossRuR0J4eMMSN8fV6+fjbSQ6YtJQfrxsm3a6gVIkJNno2b2PRZestS/0Z7DvPDGE6r1sGchvbcz8EW7Z/pvJvPBRFWlMTJ1eqY9vuyuNYMKeWlyt+5V9y2GUbcLWvcNDZSC43vQEKCo0BAXLI2nxP4INgBaSHInyFrG1/SEP0SUimKvP69FkcIBxx60x3iKqdtb2flLIhoOr/QuesASlflRfzNo3J5LOudrjZzNlRfVRqOZIyOVxZlviXtO7+w/oPCV61Sby6xPTGtFsWlt6GxEGF7iYLfvi4KWN9q/W9tlqEqUrpl/WMwS/4pYBi1xPcvXZNlJ6g"}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12622,"candidatesTokenCount":28,"totalTokenCount":12741,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12622}],"thoughtsTokenCount":91}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"\n"}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12836,"totalTokenCount":12836,"cachedContentTokenCount":12204,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12836}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":12204}]}},{"candidates":[{"content":{"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12836,"totalTokenCount":12836,"cachedContentTokenCount":12204,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12836}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":12204}]}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"\n"}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12836,"totalTokenCount":12836,"cachedContentTokenCount":12204,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12836}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":12204}]}},{"candidates":[{"content":{"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12836,"totalTokenCount":12836,"cachedContentTokenCount":12204,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12836}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":12204}]}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"**Echoing User Commands**\n\nI'm now tasked with echoing a specific phrase following a particular signal, but it's becoming complex. The user wants me to repeat \"BeforeAgent: User request processed\" when prompted. It appears I need to retain context from the previous turn, the user's initial request to create a file, to correctly respond now.\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12759,"totalTokenCount":12827,"cachedContentTokenCount":12199,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12759}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":12199}],"thoughtsTokenCount":68}},{"candidates":[{"content":{"parts":[{"text":"**Responding Precisely to Prompt**\n\nI've determined I need to repeat the phrase \"BeforeAgent: User request processed,\" even though the overall context and turn history are complex. The user has given several prompts, but has now provided a more direct command, which I believe is to follow up on the previous request. I am taking care to match the specific instructions the user provided.\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12759,"totalTokenCount":12982,"cachedContentTokenCount":12199,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12759}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":12199}],"thoughtsTokenCount":223}},{"candidates":[{"content":{"parts":[{"text":"BeforeAgent: User request processed","thoughtSignature":"CiQBcsjafAntJrb1JBgpnZaCNeYhOJXtbH6dKTeM1llglCdoOvUKYwFyyNp8PUj5sihYyITQJhdz4MqEeftyuUc4G+iTprve11gPN04eK9Y1Wi/wyln4RjRgroIrV5kByKzdGhECoyCeInpiILGhY0peIM7dZOKFdIOL7xAR9pmn4wMreqyH7l5WSAqJAQFyyNp8Cugemkt4YZWkIwEJYmUukLFx4d5EwP/9k/e4OH/svpM+uyuN3n1KVN3bFgRV5yuF0HnDLl+P7WVSSxMmWvXO2f7A1HALg+gCvZw9IV7Btgg1qp81dDoNcVkzSbTBtT4UrlJ5R6sclvHZOLUtKGwBEQ6zRonBugAgj9RV4BT1AJNOgdSsCokBAXLI2nyDGU1Iq30QVbqhgEwFa5sB6uPC+35BV8ZKGwK+YglO9rqXMrkXM+GcQi2hVIsOFXBYGTS6E2/mQfFbIKDytrb1JgP3q5xVd/bE23M2Nnf+q5TLbRpLAPmyfg0AGwhN0L7d5W6b/3ydqEPeA1/Vw/cnBzz5ND1LOTOX6BFqEs33/WHj7HIKpAEBcsjafEsn8//cZMWUQcSAucBQauojv/f7h11nbeMrZK84nEotR30BgMIWYiiWM6sGDy/4MzHwr+z2YdAz4PSgRvEf7DPxHps2nvZfAdtskgtdPl2JD81WpokSnJvCqU+cOuz+Nh3+fIiZ6vEsVpi/5cwEiGT0g3Z3I2ubyzv58oH8YnVQlKT3MsKRGb5//aXZJY57jNrexgDPzYAQsBgSuGBmqwqaAQFyyNp8sSIYw3It6GpZqC+oxJCC26pt4RxhG8rDZ3zuoADYlOpoUdSzbNuDB+iVHeen5OoCEAaH0GrFV4iZxgu40wu4ZD/VMfHi/Vm7vku23EUV/94U8mT+VEwPfd2gqv+3xPZ9MEHjOOox1Xq1984w2cA6u0Qn7wWHXeOGFVGSOHtdJtQ7ToNT8VEecblAVq8lm42sSccXQEEKmAEBcsjafONCvBhW2s8Bset20YFdbeSHelnILFDxXlCoYla5nP5UjGk4vpXu2+7RCFtKXfoyYEVEkmiGBRsmwJ82Q1nMkGkXMhuTdNhu4aCwI5m+STGxx26vkp9bcqGwMDHBotZL63PSrJacRoW8zfpDXD1PABLeTIfh5jgipQdgltyjlbc+3qfIfjBYNRSkE8ByErSz5rT7SwqSAQFyyNp8W2kut1PSJISxM7YJtbRdFqPBTikGDM6F/3l6ba6LpeRBfHdtueLChqFpwLH41VdIPQ7lRZflOq3KaZz+TQ11eDnYQbiaIdGOPgHJ/HH/0iQv2hnoOY5vg3gubFWFuZh9Bfun2VCYUI39tIxGC46TZWfgCdiP/O9CFOlpDfidPiz5ZS/4LhG9FA4Q85OuCpEBAXLI2nzpoEUA6jCZopeNTRA2uZ1r0DMm5cWVVXtFO4CoRS+19BbADNBRyNrR5qcf7bUflJBvMRVxx3mtmgK9aE5VmKYxK2Dqg15l9RUxjtqspC3VVmszVd6lOkf1BBQ/VtWDulqRetKE2u62Is9NNGuK9HsLzIBLRRc8QoML41WffuXQ+uxwyXpjx2USC44MGAqIAQFyyNp8gN3lOyHyk674W3Pyv+Egw1ZDUQK4xpvAfgnK+y53gclMGJ2IjOSvg4j0f1WO1OGqY2TBUFS7w21PXasvCkfxpqeStEb+U7Vm0r63LzXdGdug5/b1Ap6Phn4/vAYmfaKISKG4+QpjI+ehgEJzsIee2rgqOaePTP18fq8T7EDbF/B/iscKNQFyyNp8DWt2a8OetaCc5E/KsntbbOcNc7yikPZBdUezphrqIH4ztpicsHvEicYF002qWHoY"}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12759,"candidatesTokenCount":4,"totalTokenCount":12986,"cachedContentTokenCount":12199,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12759}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":12199}],"thoughtsTokenCount":223}}]}1{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"**Executing the Command**\n\nI've got the command, \"echo test,\" ready to go. My focus is entirely on calling the `run_shell_command` tool now. The user's input is processed, and the next step is straightforward: using the tool to execute the supplied command.\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12751,"totalTokenCount":12801,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12751}],"thoughtsTokenCount":50}},{"candidates":[{"content":{"parts":[{"functionCall":{"name":"run_shell_command","args":{"command":"echo test","description":"Running the command 'echo test'"}},"thoughtSignature":"CiQBcsjafL1lDlnUGmt38n1/gjwecXzy9S3qEW5sYMEno5Mr7LEKZgFyyNp8jMABmMAatt49FTdh7UiM62SI1GnjcyG+kV7xzcD73uMKHST/0D0vKP7x1equv5d6YiXnOslhVnnHotYPtVl0/kI/0unBZRdMzkBNrJXKUoSWXJXxNpV6JhJav3Uh9h1sPQqOAQFyyNp8PFeESLk0J5cPFP0EA7a13iA/rXTiKoHnjSCzDV9ALcXM78xv10/V028ZtDeQslYfT82q4++W8AlJwTQRTIrdscu2y+nCS8jnQizYN1V1yR42eMzuBU3txXcqEV8bmP6GGOe58vrqyS2zdnJKCgMntMB/niwlJlr5frhDestSOJk62tVDWKFzOiAKOAFyyNp81FtGXQTX+OSio/2PbzpCCuaQFqpEgCZpkaXXyvmXYDAI1qCq1tA+m/e5ozWdm8zTGuyb"}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12751,"candidatesTokenCount":28,"totalTokenCount":12829,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12751}],"thoughtsTokenCount":50}}]}1{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"**Seeking Task Clarity**\n\nI'm currently focused on identifying the precise task. My initial assessment indicates the user is seeking assistance, but the specific requirements remain undefined. I will directly solicit a detailed task description from the user to clarify this.\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12604,"totalTokenCount":12633,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12604}],"thoughtsTokenCount":29}},{"candidates":[{"content":{"parts":[{"text":"Hello! I'm ready to help. Please describe the task you'd like me to assist you with.","thoughtSignature":"CiQBcsjafM2CL00L595T19DK8M8zP5p9/tbFPPwdM2S6669z2FgKYQFyyNp8Ya0YVCtft9Asr/45XOCfNdPWbwZt8SvIeX3IxYzOFcOK14+DnoDIuTIrmRQBeUvdxD59QmEWx+/OaSxj9564L0IU703C1JX20buEtYhkRM4LhK0G4LG/z6IJauEKSQFyyNp8n784BnEcDTQGfZ8/s3pl/TNaNzjQx0o8wYCYZH1qsRbVa3YJAvRGrVXL6y9ka10w0lhEsrQ8vOiw6ilZKirA5DjLz4U="}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12604,"candidatesTokenCount":22,"totalTokenCount":12655,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12604}],"thoughtsTokenCount":29}}]}1{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"**Greeting the User**\n\nI've registered the user's greeting. I'm primed to respond with a friendly welcome and signal my availability to assist. My focus now is drafting a suitable response.\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12761,"totalTokenCount":12787,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12761}],"thoughtsTokenCount":26}},{"candidates":[{"content":{"parts":[{"text":"Hello! I'm ready to help. What can I do for you?","thoughtSignature":"CikBcsjafBz/0rqJuIv9woxRvivjZyAqBjpoJhOTSPfcbMWCawTfcyKImQpxAXLI2nxyuBo6dqZmTxkH7XxPxjq7mNoacRa48wc/eT5caK/4tu0Y9fJ1ScpJZb+tCNzrqTNwVXa98ppjB2O/X4eejJN+hUr3LCalDFRdRLO17PFUI5qgYSbSgIGzhbnQASgzOArvvqzDPPgqXWVIDj8KMQFyyNp8ayfqBNRkBykRSTDtzOKVGkjLW1dXWamLB4ojeEVHSOgne4vlYaKs44pitsg="}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12761,"candidatesTokenCount":15,"totalTokenCount":12802,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12761}],"thoughtsTokenCount":26}}]}1{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"**Initiating a Dialogue**\n\nI've successfully received and understood the user's initial request. My next move will be to output a simple \"Hello\" as a greeting, fulfilling the basic instruction I was given. This constitutes the first step in the interaction, and I'm ready to move forward based on the user's subsequent input.\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12588,"totalTokenCount":12607,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12588}],"thoughtsTokenCount":19}},{"candidates":[{"content":{"parts":[{"text":"Hello","thoughtSignature":"CikBcsjafB9jXawgyqQ5mpEJ4ihpLD/B2i8GR75sod00ZF3TCbrLHS9YjgpeAXLI2nx1fmJO2VIiwBpF+vLBPhYE/B2992PVW6XM20cEYx4g0leDNs6BIhzEipm6RYOxzgz8KxH9+ZkCnd8bVZr59lbDCgqSCSB6IKA+csXHKsF9g3UMRAtoSBwiBw=="}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12588,"totalTokenCount":12607,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12588}],"thoughtsTokenCount":19}}]}12{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"functionCall":{"name":"read_file","args":{"file_path":"original.txt"}}}],"role":"model"},"finishReason":"STOP","index":0}]}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"Tail call completed successfully."}],"role":"model"},"finishReason":"STOP","index":0}]}]}12{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"**Initializing File Creation**\n\nI've decided on the `write_file` tool to create the telemetry file. I'll pass \"telemetry-test.txt\" as the file path, and an empty string for the content, as the user didn't specify anything to include. This is the initial setup; the file should now exist.\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":12779,"totalTokenCount":12850,"cachedContentTokenCount":12204,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12779}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":12204}],"thoughtsTokenCount":71}},{"candidates":[{"content":{"parts":[{"functionCall":{"name":"write_file","args":{"content":"","file_path":"telemetry-test.txt"}},"thoughtSignature":"CiQBcsjafG+JDSqtKOK+ZvSjZQZmS91c1Gz0YyTiirI2u5+rhEIKZAFyyNp8DNXb+xHILTC+FVlEifqEHdrmfFNBLKojci1UIBhcZpQ4UXCMkxUXYKO34IjTlyLgSsjVbbXWEFXatb/z/RtTDcf51uc3YOEwlDScGempkJxfFgcPfIiD7bhuHBqdQfUKfAFyyNp8wZ71h+QjdfVw12PwDXWgGZ0Xed1GuyJXuqAwpWnwxDIvsDaPwDFYyLR1XDiIZZk4AvFCGt6HGMSLRuPh4K3i9CVnDc5hcjyvMIde0idAFMrgs2Mq5SARfCPrWkqyq2f0Q0WonUl2n7yr/sDQ78rx2E6qXyUJ8XMKfAFyyNp8DdTYLttyI0jknqAeZDxdFmHtpJUI8UKP5YHzpQc8Qn80OJcwhZSRH4HRKCqoC7Sukq/A5vJ5T468WqgjOoLlPLq02bYRTf/q6LC1ogEhdLHrcFv2jDeCdXJJ8NHv3O4DZAUAk1W5Gd0428zMFOxH3AgkWwEGuow="}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12779,"candidatesTokenCount":24,"totalTokenCount":12874,"cachedContentTokenCount":12204,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12779}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":12204}],"thoughtsTokenCount":71}}]}{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"OK."}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":12951,"candidatesTokenCount":2,"totalTokenCount":12953,"cachedContentTokenCount":12202,"promptTokensDetails":[{"modality":"TEXT","tokenCount":12951}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":12202}]}}]}docs/CONTRIBUTING.mdAdded+571
docs/behavioral-evals.mdAdded+185
docs/index.mdAdded+139
docs/integration-tests.mdAdded+293
docs/issue-and-pr-automation.mdAdded+203
docs/local-development.mdAdded+182
docs/npm.mdAdded+62
docs/redirects.jsonAdded+21
docs/release-confidence.mdAdded+168
docs/releases.mdAdded+550
docs/sidebar.jsonAdded+298
integration-tests/acp-env-auth.test.tsAdded+163
integration-tests/acp-telemetry.test.tsAdded+116
integration-tests/api-resilience.responsesAdded+1
integration-tests/api-resilience.test.tsAdded+50
integration-tests/browser-agent-localhost.multistep.responsesAdded+9
integration-tests/browser-agent-localhost.navigate.responsesAdded+5
integration-tests/browser-agent.cleanup.responsesAdded+5
integration-tests/browser-agent.confirmation.responsesAdded+1
integration-tests/browser-policy.responsesAdded+5
integration-tests/browser-policy.test.tsAdded+240
integration-tests/checkpointing.test.tsAdded+155
integration-tests/concurrency-limit.responsesAdded+12
integration-tests/context-compress-interactive.compress-empty.responsesAdded
integration-tests/context-compress-interactive.compress-failure.responsesAdded+3
integration-tests/context-fidelity.test.tsAdded+287
integration-tests/extensions-install.test.tsAdded+62
integration-tests/extensions-reload.test.tsAdded+151
integration-tests/file-system-interactive.test.tsAdded+67
integration-tests/flicker-detector.max-height.responsesAdded+3
integration-tests/globalSetup.tsAdded+155
integration-tests/google_web_search.test.tsAdded+95
integration-tests/hooks-agent-flow-multistep.responsesAdded+2
integration-tests/hooks-agent-flow.test.tsAdded+338
integration-tests/hooks-system.after-agent.responsesAdded+3
integration-tests/hooks-system.after-model.responsesAdded+1
integration-tests/hooks-system.after-tool-context.responsesAdded+2
integration-tests/hooks-system.allow-tool.responsesAdded+4
integration-tests/hooks-system.before-model.responsesAdded+1
integration-tests/hooks-system.before-tool-stop.responsesAdded+1
integration-tests/hooks-system.compress-auto.responsesAdded+1
integration-tests/hooks-system.input-modification.responsesAdded+2
integration-tests/hooks-system.input-validation.responsesAdded+2
integration-tests/hooks-system.multiple-events.responsesAdded+4
integration-tests/hooks-system.notification.responsesAdded+1
integration-tests/hooks-system.sequential-execution.responsesAdded+1
integration-tests/hooks-system.session-clear.responsesAdded+1
integration-tests/hooks-system.session-startup.responsesAdded+1
integration-tests/hooks-system.tail-tool-call.responsesAdded+2
integration-tests/hooks-system.telemetry.responsesAdded+2