mirror of
https://github.com/google-gemini/gemini-cli.git
synced 2026-08-10 00:47:16 -07:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ac818594b9 | |||
| 3cf18c822f | |||
| ac42fb0a24 | |||
| f47d6c6f7a | |||
| d55e366f6a | |||
| dc859e8e48 | |||
| 4bb7e93c45 | |||
| 55a31ef909 | |||
| 3499c84f7b |
@@ -18,6 +18,23 @@ on GitHub.
|
||||
| [Preview](preview.md) | Experimental features ready for early feedback. |
|
||||
| [Stable](latest.md) | Stable, recommended for general use. |
|
||||
|
||||
## Announcements: v0.53.0 - 2026-07-28
|
||||
|
||||
- **Caretaker Triage Orchestration:** Implemented an LLM triage orchestrator and
|
||||
container build setup
|
||||
([#28345](https://github.com/google-gemini/gemini-cli/pull/28345) by
|
||||
@chadd28).
|
||||
- **Eval Coverage Reporting:** Introduced a new command for generating
|
||||
evaluation coverage reports
|
||||
([#28169](https://github.com/google-gemini/gemini-cli/pull/28169) by @ved015).
|
||||
- **Security & Loop Mitigations:** Enforced workspace trust and task isolation
|
||||
in the A2A server, aligned macOS Seatbelt profiles with the deny-default
|
||||
model, and mitigated infinite ReAct/prompt injection loops
|
||||
([#28470](https://github.com/google-gemini/gemini-cli/pull/28470) by
|
||||
@luisfelipe-alt,
|
||||
[#28424](https://github.com/google-gemini/gemini-cli/pull/28424) by
|
||||
@ompatel-aiml).
|
||||
|
||||
## Announcements: v0.52.0 - 2026-07-22
|
||||
|
||||
- **Caretaker Triage & Egress Services:** Implemented the core triage worker
|
||||
|
||||
+31
-52
@@ -1,6 +1,6 @@
|
||||
# Latest stable release: v0.52.0
|
||||
# Latest stable release: v0.53.0
|
||||
|
||||
Released: July 22, 2026
|
||||
Released: July 28, 2026
|
||||
|
||||
For most users, our latest stable release is the recommended release. Install
|
||||
the latest stable version with:
|
||||
@@ -11,59 +11,38 @@ npm install -g @google/gemini-cli
|
||||
|
||||
## Highlights
|
||||
|
||||
- **Caretaker Services:** Introduced a new caretaker triage worker including
|
||||
core foundational modules, main worker execution loops, egress action
|
||||
publishers, and octokit GitHub Action handlers.
|
||||
- **Robust File Editing:** Core tools like `write_file` and `replace` now bypass
|
||||
LLM corrections for JSON and IPYNB files to ensure accurate and direct file
|
||||
modifications.
|
||||
- **Plan Mode Improvements:** Simplified plan mode write policies to natively
|
||||
support writing to relative paths, enhancing project directory navigation.
|
||||
- **Enhanced Account Visibility:** Improved clear user-facing messages when the
|
||||
user account does not have a Code Assist tier, and enriched shared project
|
||||
quota limit errors with setup instructions.
|
||||
- **Caretaker Triage Orchestrator:** Implemented an LLM triage orchestrator and
|
||||
container build setup to manage automated caretakers.
|
||||
- **Eval Coverage Reporting:** Introduced a new command for generating
|
||||
evaluation coverage reports to track agent decision logic and testing.
|
||||
- **Security and Sandboxing:** Aligned macOS permissive Seatbelt profiles with
|
||||
the deny-default model, and enforced workspace trust with task isolation in
|
||||
the A2A server.
|
||||
- **Robust Conversation Loops:** Coalesced consecutive message roles and grouped
|
||||
cancelled tool responses to avoid Bad Request errors, and mitigated infinite
|
||||
ReAct loops and prompt injection vulnerabilities.
|
||||
|
||||
## What's Changed
|
||||
|
||||
- Refactor: exclude transient CI configuration files from workspace context by
|
||||
@DavidAPierce in
|
||||
[#28216](https://github.com/google-gemini/gemini-cli/pull/28216)
|
||||
- feat(caretaker-triage): add triage worker core foundational modules by
|
||||
@chadd28 in [#28163](https://github.com/google-gemini/gemini-cli/pull/28163)
|
||||
- feat(caretaker-egress): implement octokit github action handler for egress
|
||||
service by @chadd28 in
|
||||
[#28303](https://github.com/google-gemini/gemini-cli/pull/28303)
|
||||
- chore(release): bump version to 0.52.0-nightly.20260707.g27a3da3e8 by
|
||||
@gemini-cli-robot in
|
||||
[#28323](https://github.com/google-gemini/gemini-cli/pull/28323)
|
||||
- Changelog for v0.51.0-preview.0 by @gemini-cli-robot in
|
||||
[#28320](https://github.com/google-gemini/gemini-cli/pull/28320)
|
||||
- Changelog for v0.50.0 by @gemini-cli-robot in
|
||||
[#28322](https://github.com/google-gemini/gemini-cli/pull/28322)
|
||||
- fix(core-tools): bypass LLM correction for JSON and IPYNB files in write_file
|
||||
and replace by @amelidev in
|
||||
[#28223](https://github.com/google-gemini/gemini-cli/pull/28223)
|
||||
- fix(core): use unambiguous previous intent label in fallback summary by
|
||||
@amelidev in [#28343](https://github.com/google-gemini/gemini-cli/pull/28343)
|
||||
- feat(caretaker-triage): implement main worker execution loop and egress action
|
||||
publisher by @chadd28 in
|
||||
[#28306](https://github.com/google-gemini/gemini-cli/pull/28306)
|
||||
- fix(privacy): show a clear message when the account has no Code Assist tier by
|
||||
@ompatel-aiml in
|
||||
[#28304](https://github.com/google-gemini/gemini-cli/pull/28304)
|
||||
- fix(core): enrich shared project quota limit errors with setup hint by
|
||||
@amelidev in [#28391](https://github.com/google-gemini/gemini-cli/pull/28391)
|
||||
- fix(a2a-server): ensure task cancellation aborts execution loop by
|
||||
- fix(core,a2a): group cancelled tool responses and coalesce consecutive roles
|
||||
to prevent 400 Bad Request by @luisfelipe-alt in
|
||||
[#28407](https://github.com/google-gemini/gemini-cli/pull/28407)
|
||||
- feat(caretaker-triage): implement LLM triage orchestrator and container build
|
||||
by @chadd28 in
|
||||
[#28345](https://github.com/google-gemini/gemini-cli/pull/28345)
|
||||
- refactor(cli): align macOS permissive Seatbelt profiles with deny-default
|
||||
model by @ompatel-aiml in
|
||||
[#28424](https://github.com/google-gemini/gemini-cli/pull/28424)
|
||||
- fix(core): mitigate infinite ReAct loops and prompt injection loops by
|
||||
@amelidev in [#28429](https://github.com/google-gemini/gemini-cli/pull/28429)
|
||||
- fix(a2a-server): enforce workspace trust and task isolation to prevent RCE by
|
||||
@luisfelipe-alt in
|
||||
[#28316](https://github.com/google-gemini/gemini-cli/pull/28316)
|
||||
- fix(core): simplify plan mode write policy to support relative paths by
|
||||
@DavidAPierce in
|
||||
[#28398](https://github.com/google-gemini/gemini-cli/pull/28398)
|
||||
- feat(core): Bump node google-auth-library version to 10.9.0 by @jerrylin3321
|
||||
in [#28385](https://github.com/google-gemini/gemini-cli/pull/28385)
|
||||
- chore/release: bump version to 0.52.0-nightly.20260715.gfa975395b by
|
||||
@gemini-cli-robot in
|
||||
[#28402](https://github.com/google-gemini/gemini-cli/pull/28402)
|
||||
[#28470](https://github.com/google-gemini/gemini-cli/pull/28470)
|
||||
- fix(core): sequentially verify cached credentials and restore
|
||||
GOOGLE_APPLICATION_CREDENTIALS fallback by @luisfelipe-alt in
|
||||
[#28472](https://github.com/google-gemini/gemini-cli/pull/28472)
|
||||
- feat(evals): add eval coverage report command by @ved015 in
|
||||
[#28169](https://github.com/google-gemini/gemini-cli/pull/28169)
|
||||
|
||||
**Full Changelog**:
|
||||
https://github.com/google-gemini/gemini-cli/compare/v0.51.0...v0.52.0
|
||||
https://github.com/google-gemini/gemini-cli/compare/v0.52.0...v0.53.0
|
||||
|
||||
+52
-35
@@ -1,6 +1,6 @@
|
||||
# Preview release: v0.53.0-preview.0
|
||||
# Preview release: v0.54.0-preview.0
|
||||
|
||||
Released: July 22, 2026
|
||||
Released: July 28, 2026
|
||||
|
||||
Our preview release includes the latest, new, and experimental features. This
|
||||
release may not be as stable as our [latest weekly release](latest.md).
|
||||
@@ -13,42 +13,59 @@ npm install -g @google/gemini-cli@preview
|
||||
|
||||
## Highlights
|
||||
|
||||
- **Caretaker LLM Triage Orchestrator**: Implemented the LLM triage orchestrator
|
||||
and container build configuration to support caretaker triage workflows.
|
||||
- **Enhanced Workspace Trust & Sandbox Hardening**: Aligned macOS permissive
|
||||
Seatbelt profiles with the deny-default model and enforced workspace trust and
|
||||
task isolation in the Agent-to-Agent (A2A) server to prevent remote code
|
||||
execution (RCE).
|
||||
- **Core Robustness & API Protections**: Mitigated infinite ReAct and prompt
|
||||
injection loops, and prevented 400 Bad Request errors by grouping cancelled
|
||||
tool responses and coalescing consecutive roles.
|
||||
- **Robust Credentials & Fallbacks**: Restored the
|
||||
`GOOGLE_APPLICATION_CREDENTIALS` environment variable fallback and
|
||||
sequentially verified cached credentials.
|
||||
- **Evaluation Coverage Reporting**: Added a new command to generate
|
||||
comprehensive eval coverage reports.
|
||||
- **Antigravity Agent & PR Generator:** Integrated the Antigravity agent runner,
|
||||
Firestore dual-locking for concurrency, prompt templates, and ingestion
|
||||
testing utilities.
|
||||
- **Caretaker Triage & Issue Management:** Enhanced the issue triage workflow by
|
||||
automatically posting a comment before closing issues, and sanitizing and
|
||||
wrapping issue titles in `untrusted_context`.
|
||||
- **Core API & Session Stability:** Enforced HTTPS for
|
||||
GoogleCredentialsAuthProvider to prevent cleartext leakage, rotated session
|
||||
IDs on model fallback to prevent stateful API errors, and refined chat history
|
||||
by filtering out thought parts when context management is disabled.
|
||||
|
||||
## What's Changed
|
||||
|
||||
- fix(core,a2a): group cancelled tool responses and coalesce consecutive roles
|
||||
to prevent 400 Bad Request by @luisfelipe-alt in
|
||||
[#28407](https://github.com/google-gemini/gemini-cli/pull/28407)
|
||||
- feat(caretaker-triage): implement LLM triage orchestrator and container build
|
||||
by @chadd28 in
|
||||
[#28345](https://github.com/google-gemini/gemini-cli/pull/28345)
|
||||
- refactor(cli): align macOS permissive Seatbelt profiles with deny-default
|
||||
model by @ompatel-aiml in
|
||||
[#28424](https://github.com/google-gemini/gemini-cli/pull/28424)
|
||||
- fix(core): mitigate infinite ReAct loops and prompt injection loops by
|
||||
@amelidev in [#28429](https://github.com/google-gemini/gemini-cli/pull/28429)
|
||||
- fix(a2a-server): enforce workspace trust and task isolation to prevent RCE by
|
||||
- Changelog for v0.53.0-preview.0 by @gemini-cli-robot in
|
||||
[#28507](https://github.com/google-gemini/gemini-cli/pull/28507)
|
||||
- Changelog for v0.52.0 by @gemini-cli-robot in
|
||||
[#28508](https://github.com/google-gemini/gemini-cli/pull/28508)
|
||||
- chore(release): bump version to 0.54.0-nightly.20260722.gf743ab579 by
|
||||
@gemini-cli-robot in
|
||||
[#28510](https://github.com/google-gemini/gemini-cli/pull/28510)
|
||||
- fix(caretaker): sanitize and wrap issue title in untrusted_context by @chadd28
|
||||
in [#28352](https://github.com/google-gemini/gemini-cli/pull/28352)
|
||||
- chore(caretaker): update vitest to v3.2.4 and add package-lock.json files by
|
||||
@chadd28 in [#28409](https://github.com/google-gemini/gemini-cli/pull/28409)
|
||||
- fix(core): rotate session ID on model fallback to prevent stateful API errors
|
||||
by @amelidev in
|
||||
[#28469](https://github.com/google-gemini/gemini-cli/pull/28469)
|
||||
- feat(caretaker-triage): post comment before auto-closing issues by @chadd28 in
|
||||
[#28411](https://github.com/google-gemini/gemini-cli/pull/28411)
|
||||
- fix(core): enforce HTTPS for GoogleCredentialsAuthProvider to prevent
|
||||
cleartext leakage by @amelidev in
|
||||
[#28517](https://github.com/google-gemini/gemini-cli/pull/28517)
|
||||
- fix(core): filter out thought parts from getHistoryTurns when context
|
||||
management is disabled by @DavidAPierce in
|
||||
[#28509](https://github.com/google-gemini/gemini-cli/pull/28509)
|
||||
- fix(a2a-server): normalize CRLF line endings to LF in getProposedContent by
|
||||
@luisfelipe-alt in
|
||||
[#28470](https://github.com/google-gemini/gemini-cli/pull/28470)
|
||||
- fix(core): sequentially verify cached credentials and restore
|
||||
GOOGLE_APPLICATION_CREDENTIALS fallback by @luisfelipe-alt in
|
||||
[#28472](https://github.com/google-gemini/gemini-cli/pull/28472)
|
||||
- feat(evals): add eval coverage report command by @ved015 in
|
||||
[#28169](https://github.com/google-gemini/gemini-cli/pull/28169)
|
||||
[#28531](https://github.com/google-gemini/gemini-cli/pull/28531)
|
||||
- fix(core): enforce explicit tag length and validation in file keychain by
|
||||
@luisfelipe-alt in
|
||||
[#28523](https://github.com/google-gemini/gemini-cli/pull/28523)
|
||||
- chore/release: bump version to 0.54.0-nightly.20260728.gbef611950 by
|
||||
@gemini-cli-robot in
|
||||
[#28552](https://github.com/google-gemini/gemini-cli/pull/28552)
|
||||
- feat(pr-generator-db): implement Firestore concurrency dual-locking and test
|
||||
ingestion utilities by @joneba-google in
|
||||
[#28432](https://github.com/google-gemini/gemini-cli/pull/28432)
|
||||
- feat(pr-generator-agent): implement Antigravity agent runner and prompt
|
||||
templates … by @joneba-google in
|
||||
[#28434](https://github.com/google-gemini/gemini-cli/pull/28434)
|
||||
- fix(core): skip merged function-response turns when finding the active loop by
|
||||
@adamfweidman in
|
||||
[#28565](https://github.com/google-gemini/gemini-cli/pull/28565)
|
||||
|
||||
**Full Changelog**:
|
||||
https://github.com/google-gemini/gemini-cli/compare/v0.52.0-preview.0...v0.53.0-preview.0
|
||||
https://github.com/google-gemini/gemini-cli/compare/v0.53.0-preview.0...v0.54.0-preview.0
|
||||
|
||||
Generated
+9
-9
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@google/gemini-cli",
|
||||
"version": "0.54.0-nightly.20260728.gbef611950",
|
||||
"version": "0.55.0-nightly.20260729.g3499c84f7",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@google/gemini-cli",
|
||||
"version": "0.54.0-nightly.20260728.gbef611950",
|
||||
"version": "0.55.0-nightly.20260729.g3499c84f7",
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
@@ -17782,7 +17782,7 @@
|
||||
},
|
||||
"packages/a2a-server": {
|
||||
"name": "@google/gemini-cli-a2a-server",
|
||||
"version": "0.54.0-nightly.20260728.gbef611950",
|
||||
"version": "0.55.0-nightly.20260729.g3499c84f7",
|
||||
"dependencies": {
|
||||
"@a2a-js/sdk": "0.3.11",
|
||||
"@google-cloud/storage": "7.19.0",
|
||||
@@ -18242,7 +18242,7 @@
|
||||
},
|
||||
"packages/cli": {
|
||||
"name": "@google/gemini-cli",
|
||||
"version": "0.54.0-nightly.20260728.gbef611950",
|
||||
"version": "0.55.0-nightly.20260729.g3499c84f7",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "0.16.1",
|
||||
@@ -18458,7 +18458,7 @@
|
||||
},
|
||||
"packages/core": {
|
||||
"name": "@google/gemini-cli-core",
|
||||
"version": "0.54.0-nightly.20260728.gbef611950",
|
||||
"version": "0.55.0-nightly.20260729.g3499c84f7",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@a2a-js/sdk": "0.3.11",
|
||||
@@ -19131,7 +19131,7 @@
|
||||
},
|
||||
"packages/devtools": {
|
||||
"name": "@google/gemini-cli-devtools",
|
||||
"version": "0.54.0-nightly.20260728.gbef611950",
|
||||
"version": "0.55.0-nightly.20260729.g3499c84f7",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"ws": "8.16.0"
|
||||
@@ -19167,7 +19167,7 @@
|
||||
},
|
||||
"packages/sdk": {
|
||||
"name": "@google/gemini-cli-sdk",
|
||||
"version": "0.54.0-nightly.20260728.gbef611950",
|
||||
"version": "0.55.0-nightly.20260729.g3499c84f7",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@google/gemini-cli-core": "file:../core",
|
||||
@@ -19506,7 +19506,7 @@
|
||||
},
|
||||
"packages/test-utils": {
|
||||
"name": "@google/gemini-cli-test-utils",
|
||||
"version": "0.54.0-nightly.20260728.gbef611950",
|
||||
"version": "0.55.0-nightly.20260729.g3499c84f7",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@google/gemini-cli-core": "file:../core",
|
||||
@@ -19524,7 +19524,7 @@
|
||||
},
|
||||
"packages/vscode-ide-companion": {
|
||||
"name": "gemini-cli-vscode-ide-companion",
|
||||
"version": "0.54.0-nightly.20260728.gbef611950",
|
||||
"version": "0.55.0-nightly.20260729.g3499c84f7",
|
||||
"license": "LICENSE",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "1.23.0",
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@google/gemini-cli",
|
||||
"version": "0.54.0-nightly.20260728.gbef611950",
|
||||
"version": "0.55.0-nightly.20260729.g3499c84f7",
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
},
|
||||
@@ -14,7 +14,7 @@
|
||||
"url": "git+https://github.com/google-gemini/gemini-cli.git"
|
||||
},
|
||||
"config": {
|
||||
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.54.0-nightly.20260728.gbef611950"
|
||||
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.55.0-nightly.20260729.g3499c84f7"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "cross-env NODE_ENV=development node scripts/start.js",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@google/gemini-cli-a2a-server",
|
||||
"version": "0.54.0-nightly.20260728.gbef611950",
|
||||
"version": "0.55.0-nightly.20260729.g3499c84f7",
|
||||
"description": "Gemini CLI A2A Server",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@google/gemini-cli",
|
||||
"version": "0.54.0-nightly.20260728.gbef611950",
|
||||
"version": "0.55.0-nightly.20260729.g3499c84f7",
|
||||
"description": "Gemini CLI",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
@@ -27,7 +27,7 @@
|
||||
"dist"
|
||||
],
|
||||
"config": {
|
||||
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.54.0-nightly.20260728.gbef611950"
|
||||
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.55.0-nightly.20260729.g3499c84f7"
|
||||
},
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "0.16.1",
|
||||
|
||||
@@ -319,6 +319,41 @@ describe('Session', () => {
|
||||
expect(result).toMatchObject({ stopReason: 'end_turn' });
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ type: 'MAX_TOKENS_EXCEEDED', reason: 'MAX_TOKENS' },
|
||||
{ type: 'SAFETY_BLOCKED', reason: 'SAFETY' },
|
||||
{ type: 'RECITATION_BLOCKED', reason: 'RECITATION' },
|
||||
{ type: 'OTHER_BLOCKED', reason: 'OTHER' },
|
||||
{ type: 'THINKING_ONLY_RESPONSE', reason: 'STOP' },
|
||||
])(
|
||||
'should gracefully handle InvalidStreamError with type $type in ACP session',
|
||||
async ({ type, reason }) => {
|
||||
const error = new InvalidStreamError(
|
||||
`Stream failed with ${reason}`,
|
||||
type as InvalidStreamError['type'],
|
||||
);
|
||||
mockSendMessageStream.mockImplementation(() => {
|
||||
async function* errorGen(): AsyncGenerator<
|
||||
ServerGeminiStreamEvent,
|
||||
void,
|
||||
unknown
|
||||
> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
yield* [] as any;
|
||||
throw error;
|
||||
}
|
||||
return errorGen();
|
||||
});
|
||||
|
||||
const result = await session.prompt({
|
||||
sessionId: 'session-1',
|
||||
prompt: [{ type: 'text', text: 'Hi' }],
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({ stopReason: 'end_turn' });
|
||||
},
|
||||
);
|
||||
|
||||
it('should handle /memory command', async () => {
|
||||
const handleCommandSpy = vi
|
||||
.spyOn(
|
||||
|
||||
@@ -510,7 +510,12 @@ export class Session {
|
||||
(error.type === 'NO_RESPONSE_TEXT' ||
|
||||
error.type === 'NO_FINISH_REASON' ||
|
||||
error.type === 'MALFORMED_FUNCTION_CALL' ||
|
||||
error.type === 'UNEXPECTED_TOOL_CALL'))
|
||||
error.type === 'UNEXPECTED_TOOL_CALL' ||
|
||||
error.type === 'MAX_TOKENS_EXCEEDED' ||
|
||||
error.type === 'SAFETY_BLOCKED' ||
|
||||
error.type === 'RECITATION_BLOCKED' ||
|
||||
error.type === 'OTHER_BLOCKED' ||
|
||||
error.type === 'THINKING_ONLY_RESPONSE'))
|
||||
) {
|
||||
// The stream ended with an empty response or malformed tool call.
|
||||
// Treat this as a graceful end to the model's turn rather than a crash.
|
||||
|
||||
@@ -103,7 +103,10 @@ vi.mock('../utils.js', () => ({
|
||||
|
||||
describe('extensions install command', () => {
|
||||
it('should fail if no source is provided', () => {
|
||||
const validationParser = yargs([]).command(installCommand).fail(false);
|
||||
const validationParser = yargs([])
|
||||
.locale('en')
|
||||
.command(installCommand)
|
||||
.fail(false);
|
||||
expect(() => validationParser.parse('install')).toThrow(
|
||||
'Not enough non-option arguments: got 0, need at least 1',
|
||||
);
|
||||
|
||||
@@ -27,7 +27,10 @@ vi.mock('../utils.js', () => ({
|
||||
|
||||
describe('extensions validate command', () => {
|
||||
it('should fail if no path is provided', () => {
|
||||
const validationParser = yargs([]).command(validateCommand).fail(false);
|
||||
const validationParser = yargs([])
|
||||
.locale('en')
|
||||
.command(validateCommand)
|
||||
.fail(false);
|
||||
expect(() => validationParser.parse('validate')).toThrow(
|
||||
'Not enough non-option arguments: got 0, need at least 1',
|
||||
);
|
||||
|
||||
@@ -17,7 +17,7 @@ describe('mcp command', () => {
|
||||
});
|
||||
|
||||
it('should show help when no subcommand is provided', async () => {
|
||||
const yargsInstance = yargs();
|
||||
const yargsInstance = yargs().locale('en');
|
||||
(mcpCommand.builder as (y: Argv) => Argv)(yargsInstance);
|
||||
|
||||
const parser = yargsInstance.command(mcpCommand).help();
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
CoreEvent,
|
||||
CoreToolCallStatus,
|
||||
JsonStreamEventType,
|
||||
TRUE_EMPTY_RESPONSE_MESSAGE,
|
||||
} from '@google/gemini-cli-core';
|
||||
import type { Part } from '@google/genai';
|
||||
import { runNonInteractive } from './nonInteractiveCli.js';
|
||||
@@ -78,6 +79,7 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => {
|
||||
ChatRecordingService: MockChatRecordingService,
|
||||
uiTelemetryService: {
|
||||
getMetrics: vi.fn(),
|
||||
recordSemanticValidationError: vi.fn(),
|
||||
},
|
||||
coreEvents: mockCoreEvents,
|
||||
createWorkingStdio: vi.fn(() => ({
|
||||
@@ -110,6 +112,7 @@ describe('runNonInteractive', () => {
|
||||
sendMessageStream: Mock;
|
||||
resumeChat: Mock;
|
||||
getChatRecordingService: Mock;
|
||||
getCurrentSequenceModel: Mock;
|
||||
};
|
||||
const MOCK_SESSION_METRICS: SessionMetrics = {
|
||||
models: {},
|
||||
@@ -165,6 +168,7 @@ describe('runNonInteractive', () => {
|
||||
recordMessageTokens: vi.fn(),
|
||||
recordToolCalls: vi.fn(),
|
||||
})),
|
||||
getCurrentSequenceModel: vi.fn().mockReturnValue('gemini-2.5-flash'),
|
||||
};
|
||||
|
||||
mockConfig = {
|
||||
@@ -193,6 +197,7 @@ describe('runNonInteractive', () => {
|
||||
getRawOutput: vi.fn().mockReturnValue(false),
|
||||
getAcceptRawOutputRisk: vi.fn().mockReturnValue(false),
|
||||
getAgentSessionNoninteractiveEnabled: vi.fn().mockReturnValue(false),
|
||||
getUsageStatisticsEnabled: vi.fn().mockReturnValue(false),
|
||||
} as unknown as Config;
|
||||
|
||||
mockSettings = {
|
||||
@@ -1820,7 +1825,6 @@ describe('runNonInteractive', () => {
|
||||
};
|
||||
// @ts-expect-error - Mocking internal structure
|
||||
mockGeminiClient.getChat = vi.fn().mockReturnValue(mockChat);
|
||||
// @ts-expect-error - Mocking internal structure
|
||||
mockGeminiClient.getCurrentSequenceModel = vi
|
||||
.fn()
|
||||
.mockReturnValue('model-1');
|
||||
@@ -2298,7 +2302,13 @@ describe('runNonInteractive', () => {
|
||||
|
||||
it('should handle InvalidStream event gracefully in TEXT mode', async () => {
|
||||
const events: ServerGeminiStreamEvent[] = [
|
||||
{ type: GeminiEventType.InvalidStream },
|
||||
{
|
||||
type: GeminiEventType.InvalidStream,
|
||||
value: {
|
||||
type: 'NO_RESPONSE_TEXT',
|
||||
message: 'Empty response',
|
||||
},
|
||||
},
|
||||
];
|
||||
mockGeminiClient.sendMessageStream.mockReturnValue(
|
||||
createStreamFromEvents(events),
|
||||
@@ -2312,7 +2322,7 @@ describe('runNonInteractive', () => {
|
||||
});
|
||||
|
||||
expect(processStderrSpy).toHaveBeenCalledWith(
|
||||
'[ERROR] Invalid stream: The model returned an empty response or malformed tool call.\n',
|
||||
`[ERROR] ${TRUE_EMPTY_RESPONSE_MESSAGE}\n`,
|
||||
);
|
||||
expect(mockGeminiClient.sendMessageStream).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
@@ -2325,7 +2335,13 @@ describe('runNonInteractive', () => {
|
||||
OutputFormat.STREAM_JSON,
|
||||
);
|
||||
const events: ServerGeminiStreamEvent[] = [
|
||||
{ type: GeminiEventType.InvalidStream },
|
||||
{
|
||||
type: GeminiEventType.InvalidStream,
|
||||
value: {
|
||||
type: 'NO_RESPONSE_TEXT',
|
||||
message: 'Empty response',
|
||||
},
|
||||
},
|
||||
];
|
||||
mockGeminiClient.sendMessageStream.mockReturnValue(
|
||||
createStreamFromEvents(events),
|
||||
@@ -2341,9 +2357,7 @@ describe('runNonInteractive', () => {
|
||||
const output = getWrittenOutput();
|
||||
expect(output).toContain('"type":"error"');
|
||||
expect(output).toContain('"severity":"error"');
|
||||
expect(output).toContain(
|
||||
'Invalid stream: The model returned an empty response or malformed tool call.',
|
||||
);
|
||||
expect(output).toContain(TRUE_EMPTY_RESPONSE_MESSAGE);
|
||||
expect(mockGeminiClient.sendMessageStream).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
@@ -2355,7 +2369,13 @@ describe('runNonInteractive', () => {
|
||||
OutputFormat.JSON,
|
||||
);
|
||||
const events: ServerGeminiStreamEvent[] = [
|
||||
{ type: GeminiEventType.InvalidStream },
|
||||
{
|
||||
type: GeminiEventType.InvalidStream,
|
||||
value: {
|
||||
type: 'NO_RESPONSE_TEXT',
|
||||
message: 'Empty response',
|
||||
},
|
||||
},
|
||||
];
|
||||
mockGeminiClient.sendMessageStream.mockReturnValue(
|
||||
createStreamFromEvents(events),
|
||||
@@ -2371,8 +2391,33 @@ describe('runNonInteractive', () => {
|
||||
const output = getWrittenOutput();
|
||||
expect(output).toContain('"error": {');
|
||||
expect(output).toContain('"type": "INVALID_STREAM"');
|
||||
expect(output).toContain(
|
||||
'Invalid stream: The model returned an empty response or malformed tool call.',
|
||||
expect(output).toContain(TRUE_EMPTY_RESPONSE_MESSAGE);
|
||||
expect(mockGeminiClient.sendMessageStream).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should handle non-NO_RESPONSE_TEXT InvalidStream event gracefully and use message from eventValue', async () => {
|
||||
const events: ServerGeminiStreamEvent[] = [
|
||||
{
|
||||
type: GeminiEventType.InvalidStream,
|
||||
value: {
|
||||
type: 'MALFORMED_FUNCTION_CALL',
|
||||
message: 'Custom malformed function call message',
|
||||
},
|
||||
},
|
||||
];
|
||||
mockGeminiClient.sendMessageStream.mockReturnValue(
|
||||
createStreamFromEvents(events),
|
||||
);
|
||||
|
||||
await runNonInteractive({
|
||||
config: mockConfig,
|
||||
settings: mockSettings,
|
||||
input: 'test invalid stream malformed',
|
||||
prompt_id: 'prompt-id-invalid-malformed',
|
||||
});
|
||||
|
||||
expect(processStderrSpy).toHaveBeenCalledWith(
|
||||
'[ERROR] Custom malformed function call message\n',
|
||||
);
|
||||
expect(mockGeminiClient.sendMessageStream).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
@@ -30,6 +30,12 @@ import {
|
||||
ToolErrorType,
|
||||
Scheduler,
|
||||
ROOT_SCHEDULER_ID,
|
||||
THINKING_ONLY_COMPRESS_SUGGESTION,
|
||||
MAX_TOKENS_EXCEEDED_SUGGESTION,
|
||||
SAFETY_BLOCKED_MESSAGE,
|
||||
RECITATION_BLOCKED_MESSAGE,
|
||||
OTHER_BLOCKED_MESSAGE,
|
||||
TRUE_EMPTY_RESPONSE_MESSAGE,
|
||||
} from '@google/gemini-cli-core';
|
||||
|
||||
import type { Content, Part } from '@google/genai';
|
||||
@@ -433,8 +439,31 @@ export async function runNonInteractive(
|
||||
}
|
||||
warnings.push(blockMessage);
|
||||
} else if (event.type === GeminiEventType.InvalidStream) {
|
||||
invalidStreamError =
|
||||
'Invalid stream: The model returned an empty response or malformed tool call.';
|
||||
const eventValue = event.value;
|
||||
if (eventValue?.type === 'NO_RESPONSE_TEXT') {
|
||||
invalidStreamError = TRUE_EMPTY_RESPONSE_MESSAGE;
|
||||
} else if (eventValue?.type === 'THINKING_ONLY_RESPONSE') {
|
||||
invalidStreamError = THINKING_ONLY_COMPRESS_SUGGESTION;
|
||||
} else if (eventValue?.type === 'MAX_TOKENS_EXCEEDED') {
|
||||
invalidStreamError = MAX_TOKENS_EXCEEDED_SUGGESTION;
|
||||
} else if (eventValue?.type === 'SAFETY_BLOCKED') {
|
||||
invalidStreamError = SAFETY_BLOCKED_MESSAGE;
|
||||
} else if (eventValue?.type === 'RECITATION_BLOCKED') {
|
||||
invalidStreamError = RECITATION_BLOCKED_MESSAGE;
|
||||
} else if (eventValue?.type === 'OTHER_BLOCKED') {
|
||||
invalidStreamError = OTHER_BLOCKED_MESSAGE;
|
||||
} else {
|
||||
invalidStreamError =
|
||||
eventValue?.message?.trim() ||
|
||||
'Invalid stream: The model returned an empty response or malformed tool call.';
|
||||
}
|
||||
|
||||
// Log semantic error telemetry without double-counting requests
|
||||
uiTelemetryService.recordSemanticValidationError(
|
||||
geminiClient.getCurrentSequenceModel() ?? config.getModel(),
|
||||
eventValue?.type || 'INVALID_STREAM',
|
||||
);
|
||||
|
||||
if (streamFormatter) {
|
||||
streamFormatter.emitEvent({
|
||||
type: JsonStreamEventType.ERROR,
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
CoreEvent,
|
||||
CoreToolCallStatus,
|
||||
JsonStreamEventType,
|
||||
TRUE_EMPTY_RESPONSE_MESSAGE,
|
||||
} from '@google/gemini-cli-core';
|
||||
import type { Part } from '@google/genai';
|
||||
import { runNonInteractive } from './nonInteractiveCliAgentSession.js';
|
||||
@@ -78,6 +79,7 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => {
|
||||
ChatRecordingService: MockChatRecordingService,
|
||||
uiTelemetryService: {
|
||||
getMetrics: vi.fn(),
|
||||
recordSemanticValidationError: vi.fn(),
|
||||
},
|
||||
LegacyAgentSession: original.LegacyAgentSession,
|
||||
geminiPartsToContentParts: original.geminiPartsToContentParts,
|
||||
@@ -199,6 +201,7 @@ describe('runNonInteractive', () => {
|
||||
getRawOutput: vi.fn().mockReturnValue(false),
|
||||
getAcceptRawOutputRisk: vi.fn().mockReturnValue(false),
|
||||
getAgentSessionNoninteractiveEnabled: vi.fn().mockReturnValue(false),
|
||||
getUsageStatisticsEnabled: vi.fn().mockReturnValue(false),
|
||||
} as unknown as Config;
|
||||
|
||||
mockSettings = {
|
||||
@@ -2457,6 +2460,126 @@ describe('runNonInteractive', () => {
|
||||
const output = JSON.parse(getWrittenOutput());
|
||||
expect(output.warnings).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle InvalidStream event gracefully in TEXT mode', async () => {
|
||||
const events: ServerGeminiStreamEvent[] = [
|
||||
{
|
||||
type: GeminiEventType.InvalidStream,
|
||||
value: {
|
||||
type: 'NO_RESPONSE_TEXT',
|
||||
message: 'Empty response',
|
||||
},
|
||||
},
|
||||
];
|
||||
mockGeminiClient.sendMessageStream.mockReturnValue(
|
||||
createStreamFromEvents(events),
|
||||
);
|
||||
|
||||
await runNonInteractive({
|
||||
config: mockConfig,
|
||||
settings: mockSettings,
|
||||
input: 'test invalid stream',
|
||||
prompt_id: 'prompt-id-invalid',
|
||||
});
|
||||
|
||||
expect(processStderrSpy).toHaveBeenCalledWith(
|
||||
`[ERROR] ${TRUE_EMPTY_RESPONSE_MESSAGE}\n`,
|
||||
);
|
||||
expect(mockGeminiClient.sendMessageStream).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should handle InvalidStream event gracefully in STREAM_JSON mode', async () => {
|
||||
vi.spyOn(uiTelemetryService, 'getMetrics').mockReturnValue(
|
||||
MOCK_SESSION_METRICS,
|
||||
);
|
||||
vi.spyOn(mockConfig, 'getOutputFormat').mockReturnValue(
|
||||
OutputFormat.STREAM_JSON,
|
||||
);
|
||||
const events: ServerGeminiStreamEvent[] = [
|
||||
{
|
||||
type: GeminiEventType.InvalidStream,
|
||||
value: {
|
||||
type: 'NO_RESPONSE_TEXT',
|
||||
message: 'Empty response',
|
||||
},
|
||||
},
|
||||
];
|
||||
mockGeminiClient.sendMessageStream.mockReturnValue(
|
||||
createStreamFromEvents(events),
|
||||
);
|
||||
|
||||
await runNonInteractive({
|
||||
config: mockConfig,
|
||||
settings: mockSettings,
|
||||
input: 'test invalid stream',
|
||||
prompt_id: 'prompt-id-invalid',
|
||||
});
|
||||
|
||||
const output = getWrittenOutput();
|
||||
expect(output).toContain('"type":"error"');
|
||||
expect(output).toContain('"severity":"error"');
|
||||
expect(output).toContain(TRUE_EMPTY_RESPONSE_MESSAGE);
|
||||
expect(mockGeminiClient.sendMessageStream).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should handle InvalidStream event gracefully in JSON mode', async () => {
|
||||
vi.spyOn(uiTelemetryService, 'getMetrics').mockReturnValue(
|
||||
MOCK_SESSION_METRICS,
|
||||
);
|
||||
vi.spyOn(mockConfig, 'getOutputFormat').mockReturnValue(
|
||||
OutputFormat.JSON,
|
||||
);
|
||||
const events: ServerGeminiStreamEvent[] = [
|
||||
{
|
||||
type: GeminiEventType.InvalidStream,
|
||||
value: {
|
||||
type: 'NO_RESPONSE_TEXT',
|
||||
message: 'Empty response',
|
||||
},
|
||||
},
|
||||
];
|
||||
mockGeminiClient.sendMessageStream.mockReturnValue(
|
||||
createStreamFromEvents(events),
|
||||
);
|
||||
|
||||
await runNonInteractive({
|
||||
config: mockConfig,
|
||||
settings: mockSettings,
|
||||
input: 'test invalid stream',
|
||||
prompt_id: 'prompt-id-invalid',
|
||||
});
|
||||
|
||||
const output = getWrittenOutput();
|
||||
expect(output).toContain('"error": {');
|
||||
expect(output).toContain('"type": "INVALID_STREAM"');
|
||||
expect(output).toContain(TRUE_EMPTY_RESPONSE_MESSAGE);
|
||||
expect(mockGeminiClient.sendMessageStream).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should handle non-NO_RESPONSE_TEXT InvalidStream event gracefully and use message from eventValue', async () => {
|
||||
const events: ServerGeminiStreamEvent[] = [
|
||||
{
|
||||
type: GeminiEventType.InvalidStream,
|
||||
value: {
|
||||
type: 'MALFORMED_FUNCTION_CALL',
|
||||
message: 'Malformed call',
|
||||
},
|
||||
},
|
||||
];
|
||||
mockGeminiClient.sendMessageStream.mockReturnValue(
|
||||
createStreamFromEvents(events),
|
||||
);
|
||||
|
||||
await runNonInteractive({
|
||||
config: mockConfig,
|
||||
settings: mockSettings,
|
||||
input: 'test invalid stream',
|
||||
prompt_id: 'prompt-id-invalid',
|
||||
});
|
||||
|
||||
expect(processStderrSpy).toHaveBeenCalledWith('[ERROR] Malformed call\n');
|
||||
expect(mockGeminiClient.sendMessageStream).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Output Sanitization', () => {
|
||||
|
||||
@@ -39,6 +39,12 @@ import {
|
||||
geminiPartsToContentParts,
|
||||
displayContentToString,
|
||||
debugLogger,
|
||||
THINKING_ONLY_COMPRESS_SUGGESTION,
|
||||
MAX_TOKENS_EXCEEDED_SUGGESTION,
|
||||
SAFETY_BLOCKED_MESSAGE,
|
||||
RECITATION_BLOCKED_MESSAGE,
|
||||
OTHER_BLOCKED_MESSAGE,
|
||||
TRUE_EMPTY_RESPONSE_MESSAGE,
|
||||
} from '@google/gemini-cli-core';
|
||||
|
||||
import type { Part } from '@google/genai';
|
||||
@@ -332,14 +338,17 @@ export async function runNonInteractive({
|
||||
return text ? text : undefined;
|
||||
};
|
||||
|
||||
const emitFinalSuccessResult = (): void => {
|
||||
const emitFinalResult = (errorPayload?: {
|
||||
type: string;
|
||||
message: string;
|
||||
}): void => {
|
||||
if (streamFormatter) {
|
||||
const metrics = uiTelemetryService.getMetrics();
|
||||
const durationMs = Date.now() - startTime;
|
||||
streamFormatter.emitEvent({
|
||||
type: JsonStreamEventType.RESULT,
|
||||
timestamp: new Date().toISOString(),
|
||||
status: 'success',
|
||||
status: errorPayload ? 'error' : 'success',
|
||||
stats: streamFormatter.convertToStreamStats(metrics, durationMs),
|
||||
});
|
||||
} else if (config.getOutputFormat() === OutputFormat.JSON) {
|
||||
@@ -350,7 +359,7 @@ export async function runNonInteractive({
|
||||
config.getSessionId(),
|
||||
responseText,
|
||||
stats,
|
||||
undefined,
|
||||
errorPayload,
|
||||
warnings,
|
||||
),
|
||||
);
|
||||
@@ -545,6 +554,52 @@ export async function runNonInteractive({
|
||||
break;
|
||||
}
|
||||
case 'error': {
|
||||
if (event._meta?.['code'] === 'INVALID_STREAM') {
|
||||
const errorTypeVal = event._meta?.['errorType'];
|
||||
const errorType =
|
||||
typeof errorTypeVal === 'string' ? errorTypeVal : undefined;
|
||||
|
||||
let errorMessage = event.message;
|
||||
if (errorType === 'NO_RESPONSE_TEXT') {
|
||||
errorMessage = TRUE_EMPTY_RESPONSE_MESSAGE;
|
||||
} else if (errorType === 'THINKING_ONLY_RESPONSE') {
|
||||
errorMessage = THINKING_ONLY_COMPRESS_SUGGESTION;
|
||||
} else if (errorType === 'MAX_TOKENS_EXCEEDED') {
|
||||
errorMessage = MAX_TOKENS_EXCEEDED_SUGGESTION;
|
||||
} else if (errorType === 'SAFETY_BLOCKED') {
|
||||
errorMessage = SAFETY_BLOCKED_MESSAGE;
|
||||
} else if (errorType === 'RECITATION_BLOCKED') {
|
||||
errorMessage = RECITATION_BLOCKED_MESSAGE;
|
||||
} else if (errorType === 'OTHER_BLOCKED') {
|
||||
errorMessage = OTHER_BLOCKED_MESSAGE;
|
||||
}
|
||||
|
||||
if (streamFormatter) {
|
||||
streamFormatter.emitEvent({
|
||||
type: JsonStreamEventType.ERROR,
|
||||
timestamp: new Date().toISOString(),
|
||||
severity: 'error',
|
||||
message: errorMessage,
|
||||
});
|
||||
} else if (config.getOutputFormat() === OutputFormat.TEXT) {
|
||||
process.stderr.write(`[ERROR] ${errorMessage}\n`);
|
||||
}
|
||||
|
||||
// Log semantic error telemetry without double-counting requests
|
||||
uiTelemetryService.recordSemanticValidationError(
|
||||
geminiClient.getCurrentSequenceModel() ?? config.getModel(),
|
||||
errorType || 'INVALID_STREAM',
|
||||
);
|
||||
|
||||
// If it's a fatal stream error, we should terminate and output final results
|
||||
emitFinalResult({
|
||||
type: 'INVALID_STREAM',
|
||||
message: errorMessage,
|
||||
});
|
||||
streamEnded = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (event.fatal) {
|
||||
throw reconstructFatalError(event);
|
||||
}
|
||||
@@ -613,7 +668,7 @@ export async function runNonInteractive({
|
||||
process.stderr.write(`Agent execution stopped: ${stopMessage}\n`);
|
||||
}
|
||||
|
||||
emitFinalSuccessResult();
|
||||
emitFinalResult();
|
||||
streamEnded = true;
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -36,6 +36,18 @@ function areModelMetricsEqual(a: ModelMetrics, b: ModelMetrics): boolean {
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const errorsA = a.api.errorsByType || {};
|
||||
const errorsB = b.api.errorsByType || {};
|
||||
const keysA = Object.keys(errorsA);
|
||||
const keysB = Object.keys(errorsB);
|
||||
if (keysA.length !== keysB.length) {
|
||||
return false;
|
||||
}
|
||||
for (const key of keysA) {
|
||||
if (errorsA[key] !== errorsB[key]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (
|
||||
a.tokens.input !== b.tokens.input ||
|
||||
a.tokens.prompt !== b.tokens.prompt ||
|
||||
|
||||
@@ -54,6 +54,7 @@ import {
|
||||
GeminiCliOperation,
|
||||
getPlanModeExitMessage,
|
||||
UPDATE_TOPIC_TOOL_NAME,
|
||||
TRUE_EMPTY_RESPONSE_MESSAGE,
|
||||
} from '@google/gemini-cli-core';
|
||||
import type { Part, PartListUnion } from '@google/genai';
|
||||
import type { UseHistoryManagerReturn } from './useHistoryManager.js';
|
||||
@@ -1772,6 +1773,120 @@ describe('useGeminiStream', () => {
|
||||
expect(mockCancelAllToolCalls).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should transition to Idle state when cancelled while a tool call is in progress and completes', async () => {
|
||||
const toolCalls: TrackedToolCall[] = [
|
||||
{
|
||||
request: { callId: 'call1', name: 'tool1', args: {} },
|
||||
status: CoreToolCallStatus.Executing,
|
||||
responseSubmittedToGemini: false,
|
||||
tool: {
|
||||
name: 'tool1',
|
||||
description: 'desc1',
|
||||
build: vi.fn().mockImplementation((_) => ({
|
||||
getDescription: () => `Mock description`,
|
||||
})),
|
||||
} as any,
|
||||
invocation: {
|
||||
getDescription: () => `Mock description`,
|
||||
},
|
||||
startTime: Date.now(),
|
||||
liveOutput: '...',
|
||||
} as TrackedExecutingToolCall,
|
||||
];
|
||||
|
||||
const { result } = await renderTestHook(toolCalls);
|
||||
|
||||
// State is `Responding` because a tool is running
|
||||
expect(result.current.streamingState).toBe(StreamingState.Responding);
|
||||
|
||||
// Try to cancel
|
||||
simulateEscapeKeyPress();
|
||||
|
||||
// Trigger the onComplete callback with the cancelled tool call
|
||||
await act(async () => {
|
||||
if (capturedOnComplete) {
|
||||
await capturedOnComplete([
|
||||
{
|
||||
...toolCalls[0],
|
||||
status: CoreToolCallStatus.Cancelled,
|
||||
response: {
|
||||
callId: 'call1',
|
||||
responseParts: [],
|
||||
},
|
||||
} as any,
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
// The final state should be idle because the cancelled tool call was marked as submitted
|
||||
expect(result.current.streamingState).toBe(StreamingState.Idle);
|
||||
});
|
||||
|
||||
it('should append cancelled tool responses to history when cancelled while a tool call is in progress and completes with response parts', async () => {
|
||||
const toolCalls: TrackedToolCall[] = [
|
||||
{
|
||||
request: { callId: 'call1', name: 'tool1', args: {} },
|
||||
status: CoreToolCallStatus.Executing,
|
||||
responseSubmittedToGemini: false,
|
||||
tool: {
|
||||
name: 'tool1',
|
||||
description: 'desc1',
|
||||
build: vi.fn().mockImplementation((_) => ({
|
||||
getDescription: () => `Mock description`,
|
||||
})),
|
||||
} as any,
|
||||
invocation: {
|
||||
getDescription: () => `Mock description`,
|
||||
},
|
||||
startTime: Date.now(),
|
||||
liveOutput: '...',
|
||||
} as TrackedExecutingToolCall,
|
||||
];
|
||||
|
||||
const { result, client } = await renderTestHook(toolCalls);
|
||||
|
||||
// State is `Responding` because a tool is running
|
||||
expect(result.current.streamingState).toBe(StreamingState.Responding);
|
||||
|
||||
// Try to cancel
|
||||
simulateEscapeKeyPress();
|
||||
|
||||
const expectedResponseParts = [
|
||||
{
|
||||
functionResponse: {
|
||||
name: 'tool1',
|
||||
id: 'call1',
|
||||
response: { error: 'cancelled' },
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// Trigger the onComplete callback with the cancelled tool call having non-empty response parts
|
||||
await act(async () => {
|
||||
if (capturedOnComplete) {
|
||||
await capturedOnComplete([
|
||||
{
|
||||
...toolCalls[0],
|
||||
status: CoreToolCallStatus.Cancelled,
|
||||
response: {
|
||||
callId: 'call1',
|
||||
responseParts: expectedResponseParts,
|
||||
},
|
||||
} as any,
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
// Assert that addHistory was called with the combined response parts
|
||||
expect(client.addHistory).toHaveBeenCalledWith({
|
||||
role: 'user',
|
||||
parts: expectedResponseParts,
|
||||
});
|
||||
|
||||
// The final state should be idle because the cancelled tool call was marked as submitted
|
||||
expect(result.current.streamingState).toBe(StreamingState.Idle);
|
||||
});
|
||||
|
||||
it('should cancel a request when a tool is awaiting confirmation', async () => {
|
||||
const mockOnConfirm = vi.fn().mockResolvedValue(undefined);
|
||||
const toolCalls: TrackedToolCall[] = [
|
||||
@@ -2306,6 +2421,68 @@ describe('useGeminiStream', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('should use TRUE_EMPTY_RESPONSE_MESSAGE when receiving an invalid stream event of type NO_RESPONSE_TEXT', async () => {
|
||||
mockSendMessageStream.mockClear();
|
||||
mockSendMessageStream.mockReturnValue(
|
||||
(async function* () {
|
||||
yield {
|
||||
type: ServerGeminiEventType.InvalidStream,
|
||||
value: {
|
||||
type: 'NO_RESPONSE_TEXT',
|
||||
message: 'empty response text',
|
||||
},
|
||||
};
|
||||
})(),
|
||||
);
|
||||
|
||||
const { result } = await renderTestHook();
|
||||
|
||||
await act(async () => {
|
||||
await result.current.submitQuery('test query');
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockAddItem).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: MessageType.ERROR,
|
||||
text: TRUE_EMPTY_RESPONSE_MESSAGE,
|
||||
}),
|
||||
expect.any(Number),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('should use the event message when receiving a non-NO_RESPONSE_TEXT invalid stream event', async () => {
|
||||
mockSendMessageStream.mockClear();
|
||||
mockSendMessageStream.mockReturnValue(
|
||||
(async function* () {
|
||||
yield {
|
||||
type: ServerGeminiEventType.InvalidStream,
|
||||
value: {
|
||||
type: 'MALFORMED_FUNCTION_CALL',
|
||||
message: 'Custom malformed function call message',
|
||||
},
|
||||
};
|
||||
})(),
|
||||
);
|
||||
|
||||
const { result } = await renderTestHook();
|
||||
|
||||
await act(async () => {
|
||||
await result.current.submitQuery('test query');
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockAddItem).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: MessageType.ERROR,
|
||||
text: 'Custom malformed function call message',
|
||||
}),
|
||||
expect.any(Number),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('handleApprovalModeChange', () => {
|
||||
@@ -4183,4 +4360,108 @@ describe('useGeminiStream', () => {
|
||||
});
|
||||
expect(spanMetadata.input).toBe('telemetry test query');
|
||||
});
|
||||
|
||||
describe('Quota Error fallback', () => {
|
||||
it('should add tool responses to geminiClient history if modelSwitchedFromQuotaError is true', async () => {
|
||||
const completedToolCalls: TrackedCompletedToolCall[] = [
|
||||
{
|
||||
request: {
|
||||
callId: 'call1',
|
||||
name: 'tool1',
|
||||
args: {},
|
||||
isClientInitiated: false,
|
||||
prompt_id: 'prompt-id-1',
|
||||
},
|
||||
status: CoreToolCallStatus.Success,
|
||||
responseSubmittedToGemini: false,
|
||||
response: {
|
||||
callId: 'call1',
|
||||
responseParts: [
|
||||
{
|
||||
functionResponse: {
|
||||
name: 'tool1',
|
||||
id: 'call1',
|
||||
response: { success: true },
|
||||
},
|
||||
},
|
||||
],
|
||||
errorType: undefined,
|
||||
},
|
||||
tool: {
|
||||
name: 'tool1',
|
||||
displayName: 'tool1',
|
||||
description: 'desc1',
|
||||
build: vi.fn(),
|
||||
isOutputMarkdown: false,
|
||||
} as any,
|
||||
invocation: {
|
||||
getDescription: () => 'desc1',
|
||||
} as any,
|
||||
} as unknown as TrackedCompletedToolCall,
|
||||
];
|
||||
const client = new MockedGeminiClientClass(mockConfig);
|
||||
|
||||
let capturedOnComplete:
|
||||
| ((completedTools: TrackedToolCall[]) => Promise<void>)
|
||||
| null = null;
|
||||
|
||||
mockUseToolScheduler.mockImplementation((onComplete) => {
|
||||
capturedOnComplete = onComplete;
|
||||
return [
|
||||
[],
|
||||
mockScheduleToolCalls,
|
||||
mockMarkToolsAsSubmitted,
|
||||
vi.fn(),
|
||||
mockCancelAllToolCalls,
|
||||
0,
|
||||
];
|
||||
});
|
||||
|
||||
await renderHookWithProviders(() =>
|
||||
useGeminiStream(
|
||||
client,
|
||||
[],
|
||||
mockAddItem,
|
||||
mockConfig,
|
||||
mockLoadedSettings,
|
||||
mockOnDebugMessage,
|
||||
mockHandleSlashCommand,
|
||||
false,
|
||||
() => 'vscode' as EditorType,
|
||||
() => {},
|
||||
() => Promise.resolve(),
|
||||
true, // modelSwitchedFromQuotaError is true
|
||||
() => {},
|
||||
() => {},
|
||||
() => {},
|
||||
80,
|
||||
24,
|
||||
),
|
||||
);
|
||||
|
||||
// Trigger the onComplete callback with completed tools
|
||||
await act(async () => {
|
||||
if (capturedOnComplete) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
await capturedOnComplete(completedToolCalls);
|
||||
}
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockMarkToolsAsSubmitted).toHaveBeenCalledWith(['call1']);
|
||||
expect(client.addHistory).toHaveBeenCalledWith({
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
name: 'tool1',
|
||||
id: 'call1',
|
||||
response: { success: true },
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
GitService,
|
||||
UnauthorizedError,
|
||||
UserPromptEvent,
|
||||
uiTelemetryService,
|
||||
DEFAULT_GEMINI_FLASH_MODEL,
|
||||
logConversationFinishedEvent,
|
||||
ConversationFinishedEvent,
|
||||
@@ -45,6 +46,12 @@ import {
|
||||
buildToolVisibilityContext,
|
||||
UPDATE_TOPIC_TOOL_NAME,
|
||||
UPDATE_TOPIC_DISPLAY_NAME,
|
||||
THINKING_ONLY_COMPRESS_SUGGESTION,
|
||||
MAX_TOKENS_EXCEEDED_SUGGESTION,
|
||||
SAFETY_BLOCKED_MESSAGE,
|
||||
RECITATION_BLOCKED_MESSAGE,
|
||||
OTHER_BLOCKED_MESSAGE,
|
||||
TRUE_EMPTY_RESPONSE_MESSAGE,
|
||||
} from '@google/gemini-cli-core';
|
||||
import type {
|
||||
Config,
|
||||
@@ -54,6 +61,7 @@ import type {
|
||||
ServerGeminiContentEvent as ContentEvent,
|
||||
ServerGeminiFinishedEvent,
|
||||
ServerGeminiStreamEvent as GeminiEvent,
|
||||
ServerGeminiInvalidStreamEvent,
|
||||
ThoughtSummary,
|
||||
ToolCallRequestInfo,
|
||||
ToolCallResponseInfo,
|
||||
@@ -1229,6 +1237,61 @@ export const useGeminiStream = (
|
||||
],
|
||||
);
|
||||
|
||||
const handleInvalidStreamEvent = useCallback(
|
||||
(
|
||||
eventValue: ServerGeminiInvalidStreamEvent['value'],
|
||||
userMessageTimestamp: number,
|
||||
) => {
|
||||
if (pendingHistoryItemRef.current) {
|
||||
addItem(pendingHistoryItemRef.current, userMessageTimestamp);
|
||||
setPendingHistoryItem(null);
|
||||
}
|
||||
maybeAddSuppressedToolErrorNote(userMessageTimestamp);
|
||||
|
||||
let text =
|
||||
eventValue?.message?.trim() || 'Invalid stream received from model';
|
||||
if (eventValue?.type === 'NO_RESPONSE_TEXT') {
|
||||
text = TRUE_EMPTY_RESPONSE_MESSAGE;
|
||||
} else if (eventValue?.type === 'THINKING_ONLY_RESPONSE') {
|
||||
text = THINKING_ONLY_COMPRESS_SUGGESTION;
|
||||
} else if (eventValue?.type === 'MAX_TOKENS_EXCEEDED') {
|
||||
text = MAX_TOKENS_EXCEEDED_SUGGESTION;
|
||||
} else if (eventValue?.type === 'SAFETY_BLOCKED') {
|
||||
text = SAFETY_BLOCKED_MESSAGE;
|
||||
} else if (eventValue?.type === 'RECITATION_BLOCKED') {
|
||||
text = RECITATION_BLOCKED_MESSAGE;
|
||||
} else if (eventValue?.type === 'OTHER_BLOCKED') {
|
||||
text = OTHER_BLOCKED_MESSAGE;
|
||||
}
|
||||
|
||||
// Log semantic error telemetry without double-counting requests
|
||||
uiTelemetryService.recordSemanticValidationError(
|
||||
geminiClient.getCurrentSequenceModel() ?? config.getModel(),
|
||||
eventValue?.type || 'INVALID_STREAM',
|
||||
);
|
||||
|
||||
addItem(
|
||||
{
|
||||
type: MessageType.ERROR,
|
||||
text,
|
||||
},
|
||||
userMessageTimestamp,
|
||||
);
|
||||
maybeAddLowVerbosityFailureNote(userMessageTimestamp);
|
||||
setThought(null); // Reset thought when there's an error
|
||||
},
|
||||
[
|
||||
addItem,
|
||||
pendingHistoryItemRef,
|
||||
setPendingHistoryItem,
|
||||
setThought,
|
||||
maybeAddSuppressedToolErrorNote,
|
||||
maybeAddLowVerbosityFailureNote,
|
||||
config,
|
||||
geminiClient,
|
||||
],
|
||||
);
|
||||
|
||||
const handleCitationEvent = useCallback(
|
||||
(text: string, userMessageTimestamp: number) => {
|
||||
if (!showCitations(settings)) {
|
||||
@@ -1541,8 +1604,10 @@ export const useGeminiStream = (
|
||||
loopDetectedRef.current = true;
|
||||
break;
|
||||
case ServerGeminiEventType.Retry:
|
||||
// Handled transparently by the backend stream retries.
|
||||
break;
|
||||
case ServerGeminiEventType.InvalidStream:
|
||||
// Will add the missing logic later
|
||||
handleInvalidStreamEvent(event.value, userMessageTimestamp);
|
||||
break;
|
||||
default: {
|
||||
// enforces exhaustive switch-case
|
||||
@@ -1575,6 +1640,7 @@ export const useGeminiStream = (
|
||||
handleChatModelEvent,
|
||||
handleAgentExecutionStoppedEvent,
|
||||
handleAgentExecutionBlockedEvent,
|
||||
handleInvalidStreamEvent,
|
||||
addItem,
|
||||
pendingHistoryItemRef,
|
||||
setPendingHistoryItem,
|
||||
@@ -1886,6 +1952,30 @@ export const useGeminiStream = (
|
||||
},
|
||||
);
|
||||
|
||||
if (turnCancelledRef.current) {
|
||||
setIsResponding(false);
|
||||
const geminiTools = completedAndReadyToSubmitTools.filter(
|
||||
(t) => !t.request.isClientInitiated,
|
||||
);
|
||||
if (geminiClient && geminiTools.length > 0) {
|
||||
const combinedParts = geminiTools.flatMap(
|
||||
(toolCall) => toolCall.response.responseParts,
|
||||
);
|
||||
if (combinedParts.length > 0) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
geminiClient.addHistory({
|
||||
role: 'user',
|
||||
parts: combinedParts,
|
||||
});
|
||||
}
|
||||
}
|
||||
const callIdsToMarkAsSubmitted = toolCalls.map(
|
||||
(toolCall) => toolCall.request.callId,
|
||||
);
|
||||
markToolsAsSubmitted(callIdsToMarkAsSubmitted);
|
||||
return;
|
||||
}
|
||||
|
||||
// Finalize any client-initiated tools as soon as they are done.
|
||||
const clientTools = completedAndReadyToSubmitTools.filter(
|
||||
(t) => t.request.isClientInitiated,
|
||||
@@ -2042,6 +2132,12 @@ export const useGeminiStream = (
|
||||
|
||||
// Don't continue if model was switched due to quota error
|
||||
if (modelSwitchedFromQuotaError) {
|
||||
if (geminiClient && responsesToSend.length > 0) {
|
||||
await geminiClient.addHistory({
|
||||
role: 'user',
|
||||
parts: responsesToSend,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -2066,6 +2162,7 @@ export const useGeminiStream = (
|
||||
maybeAddSuppressedToolErrorNote,
|
||||
maybeAddLowVerbosityFailureNote,
|
||||
setIsResponding,
|
||||
toolCalls,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -292,6 +292,140 @@ describe('sandbox', () => {
|
||||
await expect(start_sandbox(config)).rejects.toThrow(FatalSandboxError);
|
||||
});
|
||||
|
||||
it('should fall back to embedded profile if the .sb file is missing on disk', async () => {
|
||||
vi.mocked(os.platform).mockReturnValue('darwin');
|
||||
vi.mocked(fs.existsSync).mockImplementation((p) =>
|
||||
String(p).includes(
|
||||
'gemini-sandbox-macos-permissive-open-a1b2c3d4e5f6.sb',
|
||||
),
|
||||
);
|
||||
|
||||
const config: SandboxConfig = createMockSandboxConfig({
|
||||
command: 'sandbox-exec',
|
||||
image: 'some-image',
|
||||
});
|
||||
|
||||
const onSpy = vi.spyOn(process, 'on');
|
||||
const offSpy = vi.spyOn(process, 'off');
|
||||
|
||||
interface MockProcess extends EventEmitter {
|
||||
stdout: EventEmitter;
|
||||
stderr: EventEmitter;
|
||||
}
|
||||
const mockSpawnProcess = new EventEmitter() as MockProcess;
|
||||
mockSpawnProcess.stdout = new EventEmitter();
|
||||
mockSpawnProcess.stderr = new EventEmitter();
|
||||
vi.mocked(spawn).mockReturnValue(
|
||||
mockSpawnProcess as unknown as ReturnType<typeof spawn>,
|
||||
);
|
||||
|
||||
const promise = start_sandbox(config, [], undefined, ['arg1']);
|
||||
|
||||
setTimeout(() => {
|
||||
mockSpawnProcess.emit('close', 0);
|
||||
}, 10);
|
||||
|
||||
await expect(promise).resolves.toBe(0);
|
||||
|
||||
// Verify fs.writeFileSync was called with the temp profile file, content, and 0o600 permissions
|
||||
expect(fs.writeFileSync).toHaveBeenCalledWith(
|
||||
expect.stringContaining(
|
||||
'gemini-sandbox-macos-permissive-open-a1b2c3d4e5f6.sb',
|
||||
),
|
||||
expect.stringContaining('deny default'),
|
||||
expect.objectContaining({
|
||||
encoding: 'utf8',
|
||||
mode: 0o600,
|
||||
}),
|
||||
);
|
||||
|
||||
// Verify spawn was called with the temp profile file
|
||||
expect(spawn).toHaveBeenCalledWith(
|
||||
'sandbox-exec',
|
||||
expect.arrayContaining([
|
||||
'-f',
|
||||
expect.stringContaining(
|
||||
'gemini-sandbox-macos-permissive-open-a1b2c3d4e5f6.sb',
|
||||
),
|
||||
]),
|
||||
expect.objectContaining({ stdio: 'inherit' }),
|
||||
);
|
||||
|
||||
// Verify process on/off hooks were called for exit, SIGINT, and SIGTERM cleanups
|
||||
expect(onSpy).toHaveBeenCalledWith('exit', expect.any(Function));
|
||||
expect(onSpy).toHaveBeenCalledWith('SIGINT', expect.any(Function));
|
||||
expect(onSpy).toHaveBeenCalledWith('SIGTERM', expect.any(Function));
|
||||
|
||||
expect(offSpy).toHaveBeenCalledWith('exit', expect.any(Function));
|
||||
expect(offSpy).toHaveBeenCalledWith('SIGINT', expect.any(Function));
|
||||
expect(offSpy).toHaveBeenCalledWith('SIGTERM', expect.any(Function));
|
||||
|
||||
// Verify fs.unlinkSync was called to clean up the temp file
|
||||
expect(fs.unlinkSync).toHaveBeenCalledWith(
|
||||
expect.stringContaining(
|
||||
'gemini-sandbox-macos-permissive-open-a1b2c3d4e5f6.sb',
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'permissive-open',
|
||||
'permissive-closed',
|
||||
'permissive-proxied',
|
||||
'restrictive-open',
|
||||
'restrictive-closed',
|
||||
'restrictive-proxied',
|
||||
'strict-open',
|
||||
'strict-proxied',
|
||||
])(
|
||||
'should fall back to embedded content successfully for profile "%s"',
|
||||
async (profile) => {
|
||||
vi.mocked(os.platform).mockReturnValue('darwin');
|
||||
// Mock existsSync to return false for the profile file but true for temp directories
|
||||
vi.mocked(fs.existsSync).mockImplementation((p) =>
|
||||
String(p).includes('gemini-sandbox-macos-'),
|
||||
);
|
||||
|
||||
vi.stubEnv('SEATBELT_PROFILE', profile);
|
||||
|
||||
const config: SandboxConfig = createMockSandboxConfig({
|
||||
command: 'sandbox-exec',
|
||||
image: 'some-image',
|
||||
});
|
||||
|
||||
interface MockProcess extends EventEmitter {
|
||||
stdout: EventEmitter;
|
||||
stderr: EventEmitter;
|
||||
}
|
||||
const mockSpawnProcess = new EventEmitter() as MockProcess;
|
||||
mockSpawnProcess.stdout = new EventEmitter();
|
||||
mockSpawnProcess.stderr = new EventEmitter();
|
||||
vi.mocked(spawn).mockReturnValue(
|
||||
mockSpawnProcess as unknown as ReturnType<typeof spawn>,
|
||||
);
|
||||
|
||||
const promise = start_sandbox(config, [], undefined, ['arg1']);
|
||||
|
||||
setTimeout(() => {
|
||||
mockSpawnProcess.emit('close', 0);
|
||||
}, 10);
|
||||
|
||||
await expect(promise).resolves.toBe(0);
|
||||
|
||||
// Verify fs.writeFileSync was called with the correct file mode and content for the profile
|
||||
expect(fs.writeFileSync).toHaveBeenCalledWith(
|
||||
expect.stringContaining(`gemini-sandbox-macos-${profile}-`),
|
||||
expect.stringContaining('deny default'),
|
||||
expect.objectContaining({
|
||||
encoding: 'utf8',
|
||||
mode: 0o600,
|
||||
}),
|
||||
);
|
||||
|
||||
vi.unstubAllEnvs();
|
||||
},
|
||||
);
|
||||
|
||||
it('should handle Docker execution', async () => {
|
||||
const config: SandboxConfig = createMockSandboxConfig({
|
||||
command: 'docker',
|
||||
|
||||
+212
-149
@@ -39,6 +39,7 @@ import {
|
||||
SANDBOX_PROXY_NAME,
|
||||
BUILTIN_SEATBELT_PROFILES,
|
||||
} from './sandboxUtils.js';
|
||||
import { BUILTIN_SEATBELT_PROFILE_CONTENTS } from './sandboxBuiltinProfiles.js';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
const execFileAsync = promisify(execFile);
|
||||
@@ -56,6 +57,41 @@ export async function start_sandbox(
|
||||
patcher.patch();
|
||||
|
||||
let stopProxy: (() => void) | undefined = undefined;
|
||||
let tempProfileFile: string | null = null;
|
||||
|
||||
const cleanup = () => {
|
||||
if (tempProfileFile && fs.existsSync(tempProfileFile)) {
|
||||
try {
|
||||
fs.unlinkSync(tempProfileFile);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
tempProfileFile = null;
|
||||
}
|
||||
if (stopProxy) {
|
||||
try {
|
||||
stopProxy();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const sigintHandler = () => {
|
||||
cleanup();
|
||||
process.off('SIGINT', sigintHandler);
|
||||
process.kill(process.pid, 'SIGINT');
|
||||
};
|
||||
|
||||
const sigtermHandler = () => {
|
||||
cleanup();
|
||||
process.off('SIGTERM', sigtermHandler);
|
||||
process.kill(process.pid, 'SIGTERM');
|
||||
};
|
||||
|
||||
process.on('exit', cleanup);
|
||||
process.on('SIGINT', sigintHandler);
|
||||
process.on('SIGTERM', sigtermHandler);
|
||||
|
||||
try {
|
||||
if (config.command === 'sandbox-exec') {
|
||||
@@ -81,161 +117,193 @@ export async function start_sandbox(
|
||||
profileFile = fs.existsSync(userProfileFile)
|
||||
? userProfileFile
|
||||
: projectProfileFile;
|
||||
}
|
||||
if (!fs.existsSync(profileFile)) {
|
||||
throw new FatalSandboxError(
|
||||
`Missing macos seatbelt profile file '${profileFile}'`,
|
||||
);
|
||||
}
|
||||
debugLogger.log(`using macos seatbelt (profile: ${profile}) ...`);
|
||||
// if DEBUG is set, convert to --inspect-brk in NODE_OPTIONS
|
||||
const nodeOptions = [
|
||||
...(process.env['DEBUG'] ? ['--inspect-brk'] : []),
|
||||
...nodeArgs,
|
||||
].join(' ');
|
||||
|
||||
const args = [
|
||||
'-D',
|
||||
`TARGET_DIR=${fs.realpathSync(process.cwd())}`,
|
||||
'-D',
|
||||
`TMP_DIR=${fs.realpathSync(os.tmpdir())}`,
|
||||
'-D',
|
||||
`HOME_DIR=${fs.realpathSync(homedir())}`,
|
||||
'-D',
|
||||
`CACHE_DIR=${fs.realpathSync((await execAsync('getconf DARWIN_USER_CACHE_DIR')).stdout.trim())}`,
|
||||
];
|
||||
|
||||
// Add included directories from the workspace context
|
||||
// Always add 5 INCLUDE_DIR parameters to ensure .sb files can reference them
|
||||
const MAX_INCLUDE_DIRS = 5;
|
||||
const targetDir = fs.realpathSync(cliConfig?.getTargetDir() || '');
|
||||
const includedDirs: string[] = [];
|
||||
|
||||
if (cliConfig) {
|
||||
const workspaceContext = cliConfig.getWorkspaceContext();
|
||||
const directories = workspaceContext.getDirectories();
|
||||
|
||||
// Filter out TARGET_DIR
|
||||
for (const dir of directories) {
|
||||
const realDir = fs.realpathSync(dir);
|
||||
if (realDir !== targetDir) {
|
||||
includedDirs.push(realDir);
|
||||
} else {
|
||||
// For builtin profiles, if the file doesn't exist on disk (e.g. bundled or bazel environments),
|
||||
// write the embedded profile content to a temporary file.
|
||||
if (!fs.existsSync(profileFile)) {
|
||||
const content = BUILTIN_SEATBELT_PROFILE_CONTENTS[profile];
|
||||
if (content) {
|
||||
try {
|
||||
const tempDir = fs.realpathSync(os.tmpdir());
|
||||
const rand = randomBytes(8).toString('hex');
|
||||
tempProfileFile = path.join(
|
||||
tempDir,
|
||||
`gemini-sandbox-macos-${profile}-${rand}.sb`,
|
||||
);
|
||||
fs.writeFileSync(tempProfileFile, content, {
|
||||
encoding: 'utf8',
|
||||
mode: 0o600,
|
||||
});
|
||||
profileFile = tempProfileFile;
|
||||
} catch (err) {
|
||||
debugLogger.warn(
|
||||
`Failed to write temporary seatbelt profile: ${err}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add custom allowed paths from config
|
||||
if (config.allowedPaths) {
|
||||
for (const hostPath of config.allowedPaths) {
|
||||
if (
|
||||
hostPath &&
|
||||
path.isAbsolute(hostPath) &&
|
||||
fs.existsSync(hostPath)
|
||||
) {
|
||||
const realDir = fs.realpathSync(hostPath);
|
||||
if (!includedDirs.includes(realDir) && realDir !== targetDir) {
|
||||
try {
|
||||
if (!fs.existsSync(profileFile)) {
|
||||
throw new FatalSandboxError(
|
||||
`Missing macos seatbelt profile file '${profileFile}'`,
|
||||
);
|
||||
}
|
||||
debugLogger.log(`using macos seatbelt (profile: ${profile}) ...`);
|
||||
// if DEBUG is set, convert to --inspect-brk in NODE_OPTIONS
|
||||
const nodeOptions = [
|
||||
...(process.env['DEBUG'] ? ['--inspect-brk'] : []),
|
||||
...nodeArgs,
|
||||
].join(' ');
|
||||
|
||||
const args = [
|
||||
'-D',
|
||||
`TARGET_DIR=${fs.realpathSync(process.cwd())}`,
|
||||
'-D',
|
||||
`TMP_DIR=${fs.realpathSync(os.tmpdir())}`,
|
||||
'-D',
|
||||
`HOME_DIR=${fs.realpathSync(homedir())}`,
|
||||
'-D',
|
||||
`CACHE_DIR=${fs.realpathSync((await execAsync('getconf DARWIN_USER_CACHE_DIR')).stdout.trim())}`,
|
||||
];
|
||||
|
||||
// Add included directories from the workspace context
|
||||
// Always add 5 INCLUDE_DIR parameters to ensure .sb files can reference them
|
||||
const MAX_INCLUDE_DIRS = 5;
|
||||
const targetDir = fs.realpathSync(cliConfig?.getTargetDir() || '');
|
||||
const includedDirs: string[] = [];
|
||||
|
||||
if (cliConfig) {
|
||||
const workspaceContext = cliConfig.getWorkspaceContext();
|
||||
const directories = workspaceContext.getDirectories();
|
||||
|
||||
// Filter out TARGET_DIR
|
||||
for (const dir of directories) {
|
||||
const realDir = fs.realpathSync(dir);
|
||||
if (realDir !== targetDir) {
|
||||
includedDirs.push(realDir);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < MAX_INCLUDE_DIRS; i++) {
|
||||
let dirPath = '/dev/null'; // Default to a safe path that won't cause issues
|
||||
|
||||
if (i < includedDirs.length) {
|
||||
dirPath = includedDirs[i];
|
||||
}
|
||||
|
||||
args.push('-D', `INCLUDE_DIR_${i}=${dirPath}`);
|
||||
}
|
||||
|
||||
const finalArgv = cliArgs;
|
||||
|
||||
args.push(
|
||||
'-f',
|
||||
profileFile,
|
||||
'sh',
|
||||
'-c',
|
||||
[
|
||||
`SANDBOX=sandbox-exec`,
|
||||
`NODE_OPTIONS="${nodeOptions}"`,
|
||||
...finalArgv.map((arg) => quote([arg])),
|
||||
].join(' '),
|
||||
);
|
||||
// start and set up proxy if GEMINI_SANDBOX_PROXY_COMMAND is set
|
||||
const proxyCommand = process.env['GEMINI_SANDBOX_PROXY_COMMAND'];
|
||||
let proxyProcess: ChildProcess | undefined = undefined;
|
||||
let sandboxProcess: ChildProcess | undefined = undefined;
|
||||
const sandboxEnv = { ...process.env };
|
||||
if (proxyCommand) {
|
||||
const proxy =
|
||||
process.env['HTTPS_PROXY'] ||
|
||||
process.env['https_proxy'] ||
|
||||
process.env['HTTP_PROXY'] ||
|
||||
process.env['http_proxy'] ||
|
||||
'http://localhost:8877';
|
||||
sandboxEnv['HTTPS_PROXY'] = proxy;
|
||||
sandboxEnv['https_proxy'] = proxy; // lower-case can be required, e.g. for curl
|
||||
sandboxEnv['HTTP_PROXY'] = proxy;
|
||||
sandboxEnv['http_proxy'] = proxy;
|
||||
const noProxy = process.env['NO_PROXY'] || process.env['no_proxy'];
|
||||
if (noProxy) {
|
||||
sandboxEnv['NO_PROXY'] = noProxy;
|
||||
sandboxEnv['no_proxy'] = noProxy;
|
||||
}
|
||||
proxyProcess = spawn(proxyCommand, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
shell: true,
|
||||
detached: true,
|
||||
});
|
||||
// install handlers to stop proxy on exit/signal
|
||||
stopProxy = () => {
|
||||
debugLogger.log('stopping proxy ...');
|
||||
if (proxyProcess?.pid) {
|
||||
try {
|
||||
process.kill(-proxyProcess.pid, 'SIGTERM');
|
||||
} catch {
|
||||
// ignore
|
||||
// Add custom allowed paths from config
|
||||
if (config.allowedPaths) {
|
||||
for (const hostPath of config.allowedPaths) {
|
||||
if (
|
||||
hostPath &&
|
||||
path.isAbsolute(hostPath) &&
|
||||
fs.existsSync(hostPath)
|
||||
) {
|
||||
const realDir = fs.realpathSync(hostPath);
|
||||
if (!includedDirs.includes(realDir) && realDir !== targetDir) {
|
||||
includedDirs.push(realDir);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
process.on('exit', stopProxy);
|
||||
process.on('SIGINT', stopProxy);
|
||||
process.on('SIGTERM', stopProxy);
|
||||
}
|
||||
|
||||
// commented out as it disrupts ink rendering
|
||||
// proxyProcess.stdout?.on('data', (data) => {
|
||||
// console.info(data.toString());
|
||||
// });
|
||||
proxyProcess.stderr?.on('data', (data) => {
|
||||
debugLogger.debug(`[PROXY STDERR]: ${data.toString().trim()}`);
|
||||
});
|
||||
proxyProcess.on('close', (code, signal) => {
|
||||
if (sandboxProcess?.pid) {
|
||||
process.kill(-sandboxProcess.pid, 'SIGTERM');
|
||||
for (let i = 0; i < MAX_INCLUDE_DIRS; i++) {
|
||||
let dirPath = '/dev/null'; // Default to a safe path that won't cause issues
|
||||
|
||||
if (i < includedDirs.length) {
|
||||
dirPath = includedDirs[i];
|
||||
}
|
||||
throw new FatalSandboxError(
|
||||
`Proxy command '${proxyCommand}' exited with code ${code}, signal ${signal}`,
|
||||
);
|
||||
});
|
||||
debugLogger.log('waiting for proxy to start ...');
|
||||
await execAsync(
|
||||
`until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`,
|
||||
|
||||
args.push('-D', `INCLUDE_DIR_${i}=${dirPath}`);
|
||||
}
|
||||
|
||||
const finalArgv = cliArgs;
|
||||
|
||||
args.push(
|
||||
'-f',
|
||||
profileFile,
|
||||
'sh',
|
||||
'-c',
|
||||
[
|
||||
`SANDBOX=sandbox-exec`,
|
||||
'NODE_OPTIONS=' + quote([nodeOptions]),
|
||||
...finalArgv.map((arg) => quote([arg])),
|
||||
].join(' '),
|
||||
);
|
||||
}
|
||||
// spawn child and let it inherit stdio
|
||||
process.stdin.pause();
|
||||
sandboxProcess = spawn(config.command, args, {
|
||||
stdio: 'inherit',
|
||||
});
|
||||
return await new Promise((resolve, reject) => {
|
||||
sandboxProcess?.on('error', reject);
|
||||
sandboxProcess?.on('close', (code) => {
|
||||
process.stdin.resume();
|
||||
resolve(code ?? 1);
|
||||
// start and set up proxy if GEMINI_SANDBOX_PROXY_COMMAND is set
|
||||
const proxyCommand = process.env['GEMINI_SANDBOX_PROXY_COMMAND'];
|
||||
let proxyProcess: ChildProcess | undefined = undefined;
|
||||
let sandboxProcess: ChildProcess | undefined = undefined;
|
||||
const sandboxEnv = { ...process.env };
|
||||
if (proxyCommand) {
|
||||
const proxy =
|
||||
process.env['HTTPS_PROXY'] ||
|
||||
process.env['https_proxy'] ||
|
||||
process.env['HTTP_PROXY'] ||
|
||||
process.env['http_proxy'] ||
|
||||
'http://localhost:8877';
|
||||
sandboxEnv['HTTPS_PROXY'] = proxy;
|
||||
sandboxEnv['https_proxy'] = proxy; // lower-case can be required, e.g. for curl
|
||||
sandboxEnv['HTTP_PROXY'] = proxy;
|
||||
sandboxEnv['http_proxy'] = proxy;
|
||||
const noProxy = process.env['NO_PROXY'] || process.env['no_proxy'];
|
||||
if (noProxy) {
|
||||
sandboxEnv['NO_PROXY'] = noProxy;
|
||||
sandboxEnv['no_proxy'] = noProxy;
|
||||
}
|
||||
proxyProcess = spawn(proxyCommand, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
shell: true,
|
||||
detached: true,
|
||||
});
|
||||
// install handlers to stop proxy on exit/signal
|
||||
stopProxy = () => {
|
||||
debugLogger.log('stopping proxy ...');
|
||||
if (proxyProcess?.pid) {
|
||||
try {
|
||||
process.kill(-proxyProcess.pid, 'SIGTERM');
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// commented out as it disrupts ink rendering
|
||||
// proxyProcess.stdout?.on('data', (data) => {
|
||||
// console.info(data.toString());
|
||||
// });
|
||||
proxyProcess.stderr?.on('data', (data) => {
|
||||
debugLogger.debug(`[PROXY STDERR]: ${data.toString().trim()}`);
|
||||
});
|
||||
proxyProcess.on('close', (code, signal) => {
|
||||
if (sandboxProcess?.pid) {
|
||||
process.kill(-sandboxProcess.pid, 'SIGTERM');
|
||||
}
|
||||
throw new FatalSandboxError(
|
||||
`Proxy command '${proxyCommand}' exited with code ${code}, signal ${signal}`,
|
||||
);
|
||||
});
|
||||
debugLogger.log('waiting for proxy to start ...');
|
||||
await execAsync(
|
||||
`until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`,
|
||||
);
|
||||
}
|
||||
// spawn child and let it inherit stdio
|
||||
process.stdin.pause();
|
||||
sandboxProcess = spawn(config.command, args, {
|
||||
stdio: 'inherit',
|
||||
});
|
||||
});
|
||||
return await new Promise((resolve, reject) => {
|
||||
sandboxProcess?.on('error', (err) => {
|
||||
cleanup();
|
||||
reject(err);
|
||||
});
|
||||
sandboxProcess?.on('close', (code) => {
|
||||
process.stdin.resume();
|
||||
cleanup();
|
||||
resolve(code ?? 1);
|
||||
});
|
||||
});
|
||||
} catch (err) {
|
||||
cleanup();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
if (config.command === 'lxc') {
|
||||
@@ -768,9 +836,6 @@ export async function start_sandbox(
|
||||
// ignore
|
||||
}
|
||||
};
|
||||
process.on('exit', stopProxy);
|
||||
process.on('SIGINT', stopProxy);
|
||||
process.on('SIGTERM', stopProxy);
|
||||
|
||||
// commented out as it disrupts ink rendering
|
||||
// proxyProcess.stdout?.on('data', (data) => {
|
||||
@@ -821,12 +886,10 @@ export async function start_sandbox(
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
if (stopProxy) {
|
||||
stopProxy();
|
||||
process.off('exit', stopProxy);
|
||||
process.off('SIGINT', stopProxy);
|
||||
process.off('SIGTERM', stopProxy);
|
||||
}
|
||||
process.off('exit', cleanup);
|
||||
process.off('SIGINT', sigintHandler);
|
||||
process.off('SIGTERM', sigtermHandler);
|
||||
cleanup();
|
||||
patcher.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,555 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2026 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
export const BUILTIN_SEATBELT_PROFILE_CONTENTS: Record<string, string> = {
|
||||
'permissive-open': `(version 1)
|
||||
(deny default)
|
||||
(allow file-read*)
|
||||
(allow process-exec)
|
||||
(allow process-fork)
|
||||
(allow signal (target self))
|
||||
(allow sysctl-read
|
||||
(sysctl-name "hw.activecpu")
|
||||
(sysctl-name "hw.busfrequency_compat")
|
||||
(sysctl-name "hw.byteorder")
|
||||
(sysctl-name "hw.cacheconfig")
|
||||
(sysctl-name "hw.cachelinesize_compat")
|
||||
(sysctl-name "hw.cpufamily")
|
||||
(sysctl-name "hw.cpufrequency_compat")
|
||||
(sysctl-name "hw.cputype")
|
||||
(sysctl-name "hw.l1dcachesize_compat")
|
||||
(sysctl-name "hw.l1icachesize_compat")
|
||||
(sysctl-name "hw.l2cachesize_compat")
|
||||
(sysctl-name "hw.l3cachesize_compat")
|
||||
(sysctl-name "hw.logicalcpu_max")
|
||||
(sysctl-name "hw.machine")
|
||||
(sysctl-name "hw.ncpu")
|
||||
(sysctl-name "hw.nperflevels")
|
||||
(sysctl-name "hw.optional.arm.FEAT_BF16")
|
||||
(sysctl-name "hw.optional.arm.FEAT_DotProd")
|
||||
(sysctl-name "hw.optional.arm.FEAT_FCMA")
|
||||
(sysctl-name "hw.optional.arm.FEAT_FHM")
|
||||
(sysctl-name "hw.optional.arm.FEAT_FP16")
|
||||
(sysctl-name "hw.optional.arm.FEAT_I8MM")
|
||||
(sysctl-name "hw.optional.arm.FEAT_JSCVT")
|
||||
(sysctl-name "hw.optional.arm.FEAT_LSE")
|
||||
(sysctl-name "hw.optional.arm.FEAT_RDM")
|
||||
(sysctl-name "hw.optional.arm.FEAT_SHA512")
|
||||
(sysctl-name "hw.optional.armv8_2_sha512")
|
||||
(sysctl-name "hw.packages")
|
||||
(sysctl-name "hw.pagesize_compat")
|
||||
(sysctl-name "hw.physicalcpu_max")
|
||||
(sysctl-name "hw.tbfrequency_compat")
|
||||
(sysctl-name "hw.vectorunit")
|
||||
(sysctl-name "kern.hostname")
|
||||
(sysctl-name "kern.maxfilesperproc")
|
||||
(sysctl-name "kern.osproductversion")
|
||||
(sysctl-name "kern.osrelease")
|
||||
(sysctl-name "kern.ostype")
|
||||
(sysctl-name "kern.osvariant_status")
|
||||
(sysctl-name "kern.osversion")
|
||||
(sysctl-name "kern.secure_kernel")
|
||||
(sysctl-name "kern.usrstack64")
|
||||
(sysctl-name "kern.version")
|
||||
(sysctl-name "sysctl.proc_cputype")
|
||||
(sysctl-name-prefix "hw.perflevel")
|
||||
)
|
||||
(allow file-write*
|
||||
(subpath (param "TARGET_DIR"))
|
||||
(subpath (param "TMP_DIR"))
|
||||
(subpath (param "CACHE_DIR"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.gemini"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.npm"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.cache"))
|
||||
(subpath (param "INCLUDE_DIR_0"))
|
||||
(subpath (param "INCLUDE_DIR_1"))
|
||||
(subpath (param "INCLUDE_DIR_2"))
|
||||
(subpath (param "INCLUDE_DIR_3"))
|
||||
(subpath (param "INCLUDE_DIR_4"))
|
||||
(literal "/dev/stdout")
|
||||
(literal "/dev/stderr")
|
||||
(literal "/dev/null")
|
||||
(literal "/dev/ptmx")
|
||||
(regex #"^/dev/ttys[0-9]*$")
|
||||
)
|
||||
(allow mach-lookup
|
||||
(global-name "com.apple.sysmond")
|
||||
(global-name "com.apple.system.opendirectoryd.libinfo")
|
||||
(global-name "com.apple.system.opendirectoryd.membership")
|
||||
(global-name "com.apple.bsd.dirhelper")
|
||||
(global-name "com.apple.SecurityServer")
|
||||
(global-name "com.apple.networkd")
|
||||
(global-name "com.apple.ocspd")
|
||||
(global-name "com.apple.trustd")
|
||||
(global-name "com.apple.trustd.agent")
|
||||
(global-name "com.apple.mDNSResponder")
|
||||
(global-name "com.apple.mDNSResponderHelper")
|
||||
(global-name "com.apple.SystemConfiguration.DNSConfiguration")
|
||||
(global-name "com.apple.SystemConfiguration.configd")
|
||||
)
|
||||
(allow system-socket
|
||||
(require-all
|
||||
(socket-domain AF_SYSTEM)
|
||||
(socket-protocol 2)
|
||||
)
|
||||
)
|
||||
(allow file-ioctl (regex #"^/dev/tty.*"))
|
||||
(allow network-inbound (local ip "*:*"))
|
||||
(allow network-bind (local ip "*:*"))
|
||||
(allow network-outbound)`,
|
||||
|
||||
'permissive-proxied': `(version 1)
|
||||
(deny default)
|
||||
(allow file-read*)
|
||||
(allow process-exec)
|
||||
(allow process-fork)
|
||||
(allow signal (target self))
|
||||
(allow sysctl-read
|
||||
(sysctl-name "hw.activecpu")
|
||||
(sysctl-name "hw.busfrequency_compat")
|
||||
(sysctl-name "hw.byteorder")
|
||||
(sysctl-name "hw.cacheconfig")
|
||||
(sysctl-name "hw.cachelinesize_compat")
|
||||
(sysctl-name "hw.cpufamily")
|
||||
(sysctl-name "hw.cpufrequency_compat")
|
||||
(sysctl-name "hw.cputype")
|
||||
(sysctl-name "hw.l1dcachesize_compat")
|
||||
(sysctl-name "hw.l1icachesize_compat")
|
||||
(sysctl-name "hw.l2cachesize_compat")
|
||||
(sysctl-name "hw.l3cachesize_compat")
|
||||
(sysctl-name "hw.logicalcpu_max")
|
||||
(sysctl-name "hw.machine")
|
||||
(sysctl-name "hw.ncpu")
|
||||
(sysctl-name "hw.nperflevels")
|
||||
(sysctl-name "hw.optional.arm.FEAT_BF16")
|
||||
(sysctl-name "hw.optional.arm.FEAT_DotProd")
|
||||
(sysctl-name "hw.optional.arm.FEAT_FCMA")
|
||||
(sysctl-name "hw.optional.arm.FEAT_FHM")
|
||||
(sysctl-name "hw.optional.arm.FEAT_FP16")
|
||||
(sysctl-name "hw.optional.arm.FEAT_I8MM")
|
||||
(sysctl-name "hw.optional.arm.FEAT_JSCVT")
|
||||
(sysctl-name "hw.optional.arm.FEAT_LSE")
|
||||
(sysctl-name "hw.optional.arm.FEAT_RDM")
|
||||
(sysctl-name "hw.optional.arm.FEAT_SHA512")
|
||||
(sysctl-name "hw.optional.armv8_2_sha512")
|
||||
(sysctl-name "hw.packages")
|
||||
(sysctl-name "hw.pagesize_compat")
|
||||
(sysctl-name "hw.physicalcpu_max")
|
||||
(sysctl-name "hw.tbfrequency_compat")
|
||||
(sysctl-name "hw.vectorunit")
|
||||
(sysctl-name "kern.hostname")
|
||||
(sysctl-name "kern.maxfilesperproc")
|
||||
(sysctl-name "kern.osproductversion")
|
||||
(sysctl-name "kern.osrelease")
|
||||
(sysctl-name "kern.ostype")
|
||||
(sysctl-name "kern.osvariant_status")
|
||||
(sysctl-name "kern.osversion")
|
||||
(sysctl-name "kern.secure_kernel")
|
||||
(sysctl-name "kern.usrstack64")
|
||||
(sysctl-name "kern.version")
|
||||
(sysctl-name "sysctl.proc_cputype")
|
||||
(sysctl-name-prefix "hw.perflevel")
|
||||
)
|
||||
(allow file-write*
|
||||
(subpath (param "TARGET_DIR"))
|
||||
(subpath (param "TMP_DIR"))
|
||||
(subpath (param "CACHE_DIR"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.gemini"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.npm"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.cache"))
|
||||
(subpath (param "INCLUDE_DIR_0"))
|
||||
(subpath (param "INCLUDE_DIR_1"))
|
||||
(subpath (param "INCLUDE_DIR_2"))
|
||||
(subpath (param "INCLUDE_DIR_3"))
|
||||
(subpath (param "INCLUDE_DIR_4"))
|
||||
(literal "/dev/stdout")
|
||||
(literal "/dev/stderr")
|
||||
(literal "/dev/null")
|
||||
(literal "/dev/ptmx")
|
||||
(regex #"^/dev/ttys[0-9]*$")
|
||||
)
|
||||
(allow mach-lookup
|
||||
(global-name "com.apple.sysmond")
|
||||
(global-name "com.apple.system.opendirectoryd.libinfo")
|
||||
(global-name "com.apple.system.opendirectoryd.membership")
|
||||
(global-name "com.apple.bsd.dirhelper")
|
||||
(global-name "com.apple.SecurityServer")
|
||||
(global-name "com.apple.networkd")
|
||||
(global-name "com.apple.ocspd")
|
||||
(global-name "com.apple.trustd")
|
||||
(global-name "com.apple.trustd.agent")
|
||||
(global-name "com.apple.mDNSResponder")
|
||||
(global-name "com.apple.mDNSResponderHelper")
|
||||
(global-name "com.apple.SystemConfiguration.DNSConfiguration")
|
||||
(global-name "com.apple.SystemConfiguration.configd")
|
||||
)
|
||||
(allow system-socket
|
||||
(require-all
|
||||
(socket-domain AF_SYSTEM)
|
||||
(socket-protocol 2)
|
||||
)
|
||||
)
|
||||
(allow file-ioctl (regex #"^/dev/tty.*"))
|
||||
(allow network-inbound (local ip "localhost:9229"))
|
||||
(allow network-bind (local ip "*:*"))
|
||||
(allow network-outbound (remote tcp "localhost:8877"))`,
|
||||
|
||||
'restrictive-open': `(version 1)
|
||||
(deny default)
|
||||
(allow file-read*)
|
||||
(allow process-exec)
|
||||
(allow process-fork)
|
||||
(allow signal (target self))
|
||||
(allow sysctl-read
|
||||
(sysctl-name "hw.activecpu")
|
||||
(sysctl-name "hw.busfrequency_compat")
|
||||
(sysctl-name "hw.byteorder")
|
||||
(sysctl-name "hw.cacheconfig")
|
||||
(sysctl-name "hw.cachelinesize_compat")
|
||||
(sysctl-name "hw.cpufamily")
|
||||
(sysctl-name "hw.cpufrequency_compat")
|
||||
(sysctl-name "hw.cputype")
|
||||
(sysctl-name "hw.l1dcachesize_compat")
|
||||
(sysctl-name "hw.l1icachesize_compat")
|
||||
(sysctl-name "hw.l2cachesize_compat")
|
||||
(sysctl-name "hw.l3cachesize_compat")
|
||||
(sysctl-name "hw.logicalcpu_max")
|
||||
(sysctl-name "hw.machine")
|
||||
(sysctl-name "hw.ncpu")
|
||||
(sysctl-name "hw.nperflevels")
|
||||
(sysctl-name "hw.optional.arm.FEAT_BF16")
|
||||
(sysctl-name "hw.optional.arm.FEAT_DotProd")
|
||||
(sysctl-name "hw.optional.arm.FEAT_FCMA")
|
||||
(sysctl-name "hw.optional.arm.FEAT_FHM")
|
||||
(sysctl-name "hw.optional.arm.FEAT_FP16")
|
||||
(sysctl-name "hw.optional.arm.FEAT_I8MM")
|
||||
(sysctl-name "hw.optional.arm.FEAT_JSCVT")
|
||||
(sysctl-name "hw.optional.arm.FEAT_LSE")
|
||||
(sysctl-name "hw.optional.arm.FEAT_RDM")
|
||||
(sysctl-name "hw.optional.arm.FEAT_SHA512")
|
||||
(sysctl-name "hw.optional.armv8_2_sha512")
|
||||
(sysctl-name "hw.packages")
|
||||
(sysctl-name "hw.pagesize_compat")
|
||||
(sysctl-name "hw.physicalcpu_max")
|
||||
(sysctl-name "hw.tbfrequency_compat")
|
||||
(sysctl-name "hw.vectorunit")
|
||||
(sysctl-name "kern.hostname")
|
||||
(sysctl-name "kern.maxfilesperproc")
|
||||
(sysctl-name "kern.osproductversion")
|
||||
(sysctl-name "kern.osrelease")
|
||||
(sysctl-name "kern.ostype")
|
||||
(sysctl-name "kern.osvariant_status")
|
||||
(sysctl-name "kern.osversion")
|
||||
(sysctl-name "kern.secure_kernel")
|
||||
(sysctl-name "kern.usrstack64")
|
||||
(sysctl-name "kern.version")
|
||||
(sysctl-name "sysctl.proc_cputype")
|
||||
(sysctl-name-prefix "hw.perflevel")
|
||||
)
|
||||
(allow file-write*
|
||||
(subpath (param "TARGET_DIR"))
|
||||
(subpath (param "TMP_DIR"))
|
||||
(subpath (param "CACHE_DIR"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.gemini"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.npm"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.cache"))
|
||||
(subpath (param "INCLUDE_DIR_0"))
|
||||
(subpath (param "INCLUDE_DIR_1"))
|
||||
(subpath (param "INCLUDE_DIR_2"))
|
||||
(subpath (param "INCLUDE_DIR_3"))
|
||||
(subpath (param "INCLUDE_DIR_4"))
|
||||
(literal "/dev/stdout")
|
||||
(literal "/dev/stderr")
|
||||
(literal "/dev/null")
|
||||
)
|
||||
(allow mach-lookup (global-name "com.apple.sysmond"))
|
||||
(allow file-ioctl (regex #"^/dev/tty.*"))
|
||||
(allow network-inbound (local ip "localhost:9229"))
|
||||
(allow network-outbound)`,
|
||||
|
||||
'restrictive-proxied': `(version 1)
|
||||
(deny default)
|
||||
(allow file-read*)
|
||||
(allow process-exec)
|
||||
(allow process-fork)
|
||||
(allow signal (target self))
|
||||
(allow sysctl-read
|
||||
(sysctl-name "hw.activecpu")
|
||||
(sysctl-name "hw.busfrequency_compat")
|
||||
(sysctl-name "hw.byteorder")
|
||||
(sysctl-name "hw.cacheconfig")
|
||||
(sysctl-name "hw.cachelinesize_compat")
|
||||
(sysctl-name "hw.cpufamily")
|
||||
(sysctl-name "hw.cpufrequency_compat")
|
||||
(sysctl-name "hw.cputype")
|
||||
(sysctl-name "hw.l1dcachesize_compat")
|
||||
(sysctl-name "hw.l1icachesize_compat")
|
||||
(sysctl-name "hw.l2cachesize_compat")
|
||||
(sysctl-name "hw.l3cachesize_compat")
|
||||
(sysctl-name "hw.logicalcpu_max")
|
||||
(sysctl-name "hw.machine")
|
||||
(sysctl-name "hw.ncpu")
|
||||
(sysctl-name "hw.nperflevels")
|
||||
(sysctl-name "hw.optional.arm.FEAT_BF16")
|
||||
(sysctl-name "hw.optional.arm.FEAT_DotProd")
|
||||
(sysctl-name "hw.optional.arm.FEAT_FCMA")
|
||||
(sysctl-name "hw.optional.arm.FEAT_FHM")
|
||||
(sysctl-name "hw.optional.arm.FEAT_FP16")
|
||||
(sysctl-name "hw.optional.arm.FEAT_I8MM")
|
||||
(sysctl-name "hw.optional.arm.FEAT_JSCVT")
|
||||
(sysctl-name "hw.optional.arm.FEAT_LSE")
|
||||
(sysctl-name "hw.optional.arm.FEAT_RDM")
|
||||
(sysctl-name "hw.optional.arm.FEAT_SHA512")
|
||||
(sysctl-name "hw.optional.armv8_2_sha512")
|
||||
(sysctl-name "hw.packages")
|
||||
(sysctl-name "hw.pagesize_compat")
|
||||
(sysctl-name "hw.physicalcpu_max")
|
||||
(sysctl-name "hw.tbfrequency_compat")
|
||||
(sysctl-name "hw.vectorunit")
|
||||
(sysctl-name "kern.hostname")
|
||||
(sysctl-name "kern.maxfilesperproc")
|
||||
(sysctl-name "kern.osproductversion")
|
||||
(sysctl-name "kern.osrelease")
|
||||
(sysctl-name "kern.ostype")
|
||||
(sysctl-name "kern.osvariant_status")
|
||||
(sysctl-name "kern.osversion")
|
||||
(sysctl-name "kern.secure_kernel")
|
||||
(sysctl-name "kern.usrstack64")
|
||||
(sysctl-name "kern.version")
|
||||
(sysctl-name "sysctl.proc_cputype")
|
||||
(sysctl-name-prefix "hw.perflevel")
|
||||
)
|
||||
(allow file-write*
|
||||
(subpath (param "TARGET_DIR"))
|
||||
(subpath (param "TMP_DIR"))
|
||||
(subpath (param "CACHE_DIR"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.gemini"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.npm"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.cache"))
|
||||
(subpath (param "INCLUDE_DIR_0"))
|
||||
(subpath (param "INCLUDE_DIR_1"))
|
||||
(subpath (param "INCLUDE_DIR_2"))
|
||||
(subpath (param "INCLUDE_DIR_3"))
|
||||
(subpath (param "INCLUDE_DIR_4"))
|
||||
(literal "/dev/stdout")
|
||||
(literal "/dev/stderr")
|
||||
(literal "/dev/null")
|
||||
)
|
||||
(allow mach-lookup (global-name "com.apple.sysmond"))
|
||||
(allow file-ioctl (regex #"^/dev/tty.*"))
|
||||
(allow network-inbound (local ip "localhost:9229"))
|
||||
(allow network-outbound (remote tcp "localhost:8877"))`,
|
||||
|
||||
'strict-open': `(version 1)
|
||||
(deny default)
|
||||
(allow file-read*
|
||||
(literal "/")
|
||||
(subpath (param "TARGET_DIR"))
|
||||
(subpath (param "TMP_DIR"))
|
||||
(subpath (param "CACHE_DIR"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.gemini"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.npm"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.cache"))
|
||||
(literal (string-append (param "HOME_DIR") "/.gitconfig"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.nvm"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.fnm"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.node"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.config"))
|
||||
(subpath (param "INCLUDE_DIR_0"))
|
||||
(subpath (param "INCLUDE_DIR_1"))
|
||||
(subpath (param "INCLUDE_DIR_2"))
|
||||
(subpath (param "INCLUDE_DIR_3"))
|
||||
(subpath (param "INCLUDE_DIR_4"))
|
||||
(subpath "/usr")
|
||||
(subpath "/bin")
|
||||
(subpath "/sbin")
|
||||
(subpath "/Library")
|
||||
(subpath "/System")
|
||||
(subpath "/private")
|
||||
(subpath "/dev")
|
||||
(subpath "/etc")
|
||||
(subpath "/opt")
|
||||
(subpath "/Applications")
|
||||
)
|
||||
(allow file-read-metadata)
|
||||
(allow process-exec)
|
||||
(allow process-fork)
|
||||
(allow signal (target self))
|
||||
(allow sysctl-read
|
||||
(sysctl-name "hw.activecpu")
|
||||
(sysctl-name "hw.busfrequency_compat")
|
||||
(sysctl-name "hw.byteorder")
|
||||
(sysctl-name "hw.cacheconfig")
|
||||
(sysctl-name "hw.cachelinesize_compat")
|
||||
(sysctl-name "hw.cpufamily")
|
||||
(sysctl-name "hw.cpufrequency_compat")
|
||||
(sysctl-name "hw.cputype")
|
||||
(sysctl-name "hw.l1dcachesize_compat")
|
||||
(sysctl-name "hw.l1icachesize_compat")
|
||||
(sysctl-name "hw.l2cachesize_compat")
|
||||
(sysctl-name "hw.l3cachesize_compat")
|
||||
(sysctl-name "hw.logicalcpu_max")
|
||||
(sysctl-name "hw.machine")
|
||||
(sysctl-name "hw.ncpu")
|
||||
(sysctl-name "hw.nperflevels")
|
||||
(sysctl-name "hw.optional.arm.FEAT_BF16")
|
||||
(sysctl-name "hw.optional.arm.FEAT_DotProd")
|
||||
(sysctl-name "hw.optional.arm.FEAT_FCMA")
|
||||
(sysctl-name "hw.optional.arm.FEAT_FHM")
|
||||
(sysctl-name "hw.optional.arm.FEAT_FP16")
|
||||
(sysctl-name "hw.optional.arm.FEAT_I8MM")
|
||||
(sysctl-name "hw.optional.arm.FEAT_JSCVT")
|
||||
(sysctl-name "hw.optional.arm.FEAT_LSE")
|
||||
(sysctl-name "hw.optional.arm.FEAT_RDM")
|
||||
(sysctl-name "hw.optional.arm.FEAT_SHA512")
|
||||
(sysctl-name "hw.optional.armv8_2_sha512")
|
||||
(sysctl-name "hw.packages")
|
||||
(sysctl-name "hw.pagesize_compat")
|
||||
(sysctl-name "hw.physicalcpu_max")
|
||||
(sysctl-name "hw.tbfrequency_compat")
|
||||
(sysctl-name "hw.vectorunit")
|
||||
(sysctl-name "kern.hostname")
|
||||
(sysctl-name "kern.maxfilesperproc")
|
||||
(sysctl-name "kern.osproductversion")
|
||||
(sysctl-name "kern.osrelease")
|
||||
(sysctl-name "kern.ostype")
|
||||
(sysctl-name "kern.osvariant_status")
|
||||
(sysctl-name "kern.osversion")
|
||||
(sysctl-name "kern.secure_kernel")
|
||||
(sysctl-name "kern.usrstack64")
|
||||
(sysctl-name "kern.version")
|
||||
(sysctl-name "sysctl.proc_cputype")
|
||||
(sysctl-name-prefix "hw.perflevel")
|
||||
)
|
||||
(allow file-write*
|
||||
(subpath (param "TARGET_DIR"))
|
||||
(subpath (param "TMP_DIR"))
|
||||
(subpath (param "CACHE_DIR"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.gemini"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.npm"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.cache"))
|
||||
(subpath (param "INCLUDE_DIR_0"))
|
||||
(subpath (param "INCLUDE_DIR_1"))
|
||||
(subpath (param "INCLUDE_DIR_2"))
|
||||
(subpath (param "INCLUDE_DIR_3"))
|
||||
(subpath (param "INCLUDE_DIR_4"))
|
||||
(literal "/dev/stdout")
|
||||
(literal "/dev/stderr")
|
||||
(literal "/dev/null")
|
||||
)
|
||||
(allow mach-lookup (global-name "com.apple.sysmond"))
|
||||
(allow file-ioctl (regex #"^/dev/tty.*"))
|
||||
(allow network-inbound (local ip "localhost:9229"))
|
||||
(allow network-outbound)`,
|
||||
|
||||
'strict-proxied': `(version 1)
|
||||
(deny default)
|
||||
(allow file-read*
|
||||
(literal "/")
|
||||
(subpath (param "TARGET_DIR"))
|
||||
(subpath (param "TMP_DIR"))
|
||||
(subpath (param "CACHE_DIR"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.gemini"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.npm"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.cache"))
|
||||
(literal (string-append (param "HOME_DIR") "/.gitconfig"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.nvm"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.fnm"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.node"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.config"))
|
||||
(subpath (param "INCLUDE_DIR_0"))
|
||||
(subpath (param "INCLUDE_DIR_1"))
|
||||
(subpath (param "INCLUDE_DIR_2"))
|
||||
(subpath (param "INCLUDE_DIR_3"))
|
||||
(subpath (param "INCLUDE_DIR_4"))
|
||||
(subpath "/usr")
|
||||
(subpath "/bin")
|
||||
(subpath "/sbin")
|
||||
(subpath "/Library")
|
||||
(subpath "/System")
|
||||
(subpath "/private")
|
||||
(subpath "/dev")
|
||||
(subpath "/etc")
|
||||
(subpath "/opt")
|
||||
(subpath "/Applications")
|
||||
)
|
||||
(allow file-read-metadata)
|
||||
(allow process-exec)
|
||||
(allow process-fork)
|
||||
(allow signal (target self))
|
||||
(allow sysctl-read
|
||||
(sysctl-name "hw.activecpu")
|
||||
(sysctl-name "hw.busfrequency_compat")
|
||||
(sysctl-name "hw.byteorder")
|
||||
(sysctl-name "hw.cacheconfig")
|
||||
(sysctl-name "hw.cachelinesize_compat")
|
||||
(sysctl-name "hw.cpufamily")
|
||||
(sysctl-name "hw.cpufrequency_compat")
|
||||
(sysctl-name "hw.cputype")
|
||||
(sysctl-name "hw.l1dcachesize_compat")
|
||||
(sysctl-name "hw.l1icachesize_compat")
|
||||
(sysctl-name "hw.l2cachesize_compat")
|
||||
(sysctl-name "hw.l3cachesize_compat")
|
||||
(sysctl-name "hw.logicalcpu_max")
|
||||
(sysctl-name "hw.machine")
|
||||
(sysctl-name "hw.ncpu")
|
||||
(sysctl-name "hw.nperflevels")
|
||||
(sysctl-name "hw.optional.arm.FEAT_BF16")
|
||||
(sysctl-name "hw.optional.arm.FEAT_DotProd")
|
||||
(sysctl-name "hw.optional.arm.FEAT_FCMA")
|
||||
(sysctl-name "hw.optional.arm.FEAT_FHM")
|
||||
(sysctl-name "hw.optional.arm.FEAT_FP16")
|
||||
(sysctl-name "hw.optional.arm.FEAT_I8MM")
|
||||
(sysctl-name "hw.optional.arm.FEAT_JSCVT")
|
||||
(sysctl-name "hw.optional.arm.FEAT_LSE")
|
||||
(sysctl-name "hw.optional.arm.FEAT_RDM")
|
||||
(sysctl-name "hw.optional.arm.FEAT_SHA512")
|
||||
(sysctl-name "hw.optional.armv8_2_sha512")
|
||||
(sysctl-name "hw.packages")
|
||||
(sysctl-name "hw.pagesize_compat")
|
||||
(sysctl-name "hw.physicalcpu_max")
|
||||
(sysctl-name "hw.tbfrequency_compat")
|
||||
(sysctl-name "hw.vectorunit")
|
||||
(sysctl-name "kern.hostname")
|
||||
(sysctl-name "kern.maxfilesperproc")
|
||||
(sysctl-name "kern.osproductversion")
|
||||
(sysctl-name "kern.osrelease")
|
||||
(sysctl-name "kern.ostype")
|
||||
(sysctl-name "kern.osvariant_status")
|
||||
(sysctl-name "kern.osversion")
|
||||
(sysctl-name "kern.secure_kernel")
|
||||
(sysctl-name "kern.usrstack64")
|
||||
(sysctl-name "kern.version")
|
||||
(sysctl-name "sysctl.proc_cputype")
|
||||
(sysctl-name-prefix "hw.perflevel")
|
||||
)
|
||||
(allow file-write*
|
||||
(subpath (param "TARGET_DIR"))
|
||||
(subpath (param "TMP_DIR"))
|
||||
(subpath (param "CACHE_DIR"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.gemini"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.npm"))
|
||||
(subpath (string-append (param "HOME_DIR") "/.cache"))
|
||||
(subpath (param "INCLUDE_DIR_0"))
|
||||
(subpath (param "INCLUDE_DIR_1"))
|
||||
(subpath (param "INCLUDE_DIR_2"))
|
||||
(subpath (param "INCLUDE_DIR_3"))
|
||||
(subpath (param "INCLUDE_DIR_4"))
|
||||
(literal "/dev/stdout")
|
||||
(literal "/dev/stderr")
|
||||
(literal "/dev/null")
|
||||
)
|
||||
(allow mach-lookup (global-name "com.apple.sysmond"))
|
||||
(allow file-ioctl (regex #"^/dev/tty.*"))
|
||||
(allow network-inbound (local ip "localhost:9229"))
|
||||
(allow network-outbound (remote tcp "localhost:8877"))`,
|
||||
};
|
||||
|
||||
// Map standard 'closed' profiles to their strict counterparts for backward compatibility and fallback support
|
||||
BUILTIN_SEATBELT_PROFILE_CONTENTS['permissive-closed'] =
|
||||
BUILTIN_SEATBELT_PROFILE_CONTENTS['strict-open'];
|
||||
BUILTIN_SEATBELT_PROFILE_CONTENTS['restrictive-closed'] =
|
||||
BUILTIN_SEATBELT_PROFILE_CONTENTS['strict-proxied'];
|
||||
@@ -15,8 +15,10 @@ export const SANDBOX_NETWORK_NAME = 'gemini-cli-sandbox';
|
||||
export const SANDBOX_PROXY_NAME = 'gemini-cli-sandbox-proxy';
|
||||
export const BUILTIN_SEATBELT_PROFILES = [
|
||||
'permissive-open',
|
||||
'permissive-closed',
|
||||
'permissive-proxied',
|
||||
'restrictive-open',
|
||||
'restrictive-closed',
|
||||
'restrictive-proxied',
|
||||
'strict-open',
|
||||
'strict-proxied',
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@google/gemini-cli-core",
|
||||
"version": "0.54.0-nightly.20260728.gbef611950",
|
||||
"version": "0.55.0-nightly.20260729.g3499c84f7",
|
||||
"description": "Gemini CLI Core",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
|
||||
@@ -516,10 +516,34 @@ describe('translateEvent', () => {
|
||||
});
|
||||
|
||||
describe('InvalidStream events', () => {
|
||||
it('emits fatal error', () => {
|
||||
it('emits fatal error with specific message from event', () => {
|
||||
state.streamStartEmitted = true;
|
||||
const event: ServerGeminiStreamEvent = {
|
||||
type: GeminiEventType.InvalidStream,
|
||||
value: {
|
||||
type: 'NO_RESPONSE_TEXT',
|
||||
message: 'Empty response',
|
||||
},
|
||||
};
|
||||
const result = translateEvent(event, state);
|
||||
expect(result).toHaveLength(1);
|
||||
const err = result[0] as AgentEvent<'error'>;
|
||||
expect(err.status).toBe('INTERNAL');
|
||||
expect(err.message).toBe('Empty response');
|
||||
expect(err.fatal).toBe(true);
|
||||
expect(err._meta?.['code']).toBe('INVALID_STREAM');
|
||||
expect(err._meta?.['errorType']).toBe('NO_RESPONSE_TEXT');
|
||||
expect(err._meta?.['rawMessage']).toBe('Empty response');
|
||||
});
|
||||
|
||||
it('falls back to default message when message is missing', () => {
|
||||
state.streamStartEmitted = true;
|
||||
const event: ServerGeminiStreamEvent = {
|
||||
type: GeminiEventType.InvalidStream,
|
||||
value: {
|
||||
type: 'NO_RESPONSE_TEXT',
|
||||
message: '',
|
||||
},
|
||||
};
|
||||
const result = translateEvent(event, state);
|
||||
expect(result).toHaveLength(1);
|
||||
|
||||
@@ -222,8 +222,15 @@ export function translateEvent(
|
||||
out.push(
|
||||
makeEvent('error', state, {
|
||||
status: 'INTERNAL',
|
||||
message: 'Invalid stream received from model',
|
||||
message:
|
||||
event.value?.message?.trim() ||
|
||||
'Invalid stream received from model',
|
||||
fatal: true,
|
||||
_meta: {
|
||||
code: 'INVALID_STREAM',
|
||||
errorType: event.value?.type,
|
||||
rawMessage: event.value?.message,
|
||||
},
|
||||
}),
|
||||
);
|
||||
break;
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
*/
|
||||
|
||||
import { GeminiEventType } from '../core/turn.js';
|
||||
import type { Part } from '@google/genai';
|
||||
import type { Part, FinishReason } from '@google/genai';
|
||||
import type { GeminiClient } from '../core/client.js';
|
||||
import type { Config } from '../config/config.js';
|
||||
import type { ToolCallRequestInfo } from '../scheduler/types.js';
|
||||
@@ -192,6 +192,7 @@ export class LegacyAgentProtocol implements AgentProtocol {
|
||||
}
|
||||
|
||||
const toolCallRequests: ToolCallRequestInfo[] = [];
|
||||
let finishedReason: FinishReason | undefined = undefined;
|
||||
const responseStream = this._client.sendMessageStream(
|
||||
currentParts,
|
||||
this._abortController.signal,
|
||||
@@ -220,10 +221,7 @@ export class LegacyAgentProtocol implements AgentProtocol {
|
||||
this._finishStream('failed');
|
||||
return;
|
||||
case GeminiEventType.Finished:
|
||||
if (toolCallRequests.length === 0) {
|
||||
this._finishStream(mapFinishReason(event.value.reason));
|
||||
return;
|
||||
}
|
||||
finishedReason = event.value.reason;
|
||||
break;
|
||||
case GeminiEventType.AgentExecutionStopped:
|
||||
case GeminiEventType.UserCancelled:
|
||||
@@ -241,7 +239,11 @@ export class LegacyAgentProtocol implements AgentProtocol {
|
||||
}
|
||||
|
||||
if (toolCallRequests.length === 0) {
|
||||
this._finishStream('completed');
|
||||
if (finishedReason !== undefined) {
|
||||
this._finishStream(mapFinishReason(finishedReason));
|
||||
} else {
|
||||
this._finishStream('completed');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -165,6 +165,16 @@ ONLY use the built-in \`exit_plan_mode\` tool to present the plan for formal app
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. \`replace\`, \`write_file\`), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the \`replace\` tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
@@ -361,6 +371,16 @@ An approved plan is available for this task at \`../plans/feature-x.md\`.
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. \`replace\`, \`write_file\`), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the \`replace\` tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
@@ -671,6 +691,16 @@ ONLY use the built-in \`exit_plan_mode\` tool to present the plan for formal app
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. \`replace\`, \`write_file\`), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the \`replace\` tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
@@ -845,6 +875,16 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. \`replace\`, \`write_file\`), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the \`replace\` tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
@@ -1005,6 +1045,16 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. \`replace\`, \`write_file\`), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the \`replace\` tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
@@ -1148,6 +1198,16 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. \`replace\`, \`write_file\`), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the \`replace\` tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
@@ -1837,6 +1897,16 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. \`replace\`, \`write_file\`), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the \`replace\` tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
@@ -2011,6 +2081,16 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. \`replace\`, \`write_file\`), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the \`replace\` tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
@@ -2189,6 +2269,16 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. \`replace\`, \`write_file\`), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the \`replace\` tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
@@ -2367,6 +2457,16 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. \`replace\`, \`write_file\`), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the \`replace\` tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
@@ -2541,6 +2641,16 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. \`replace\`, \`write_file\`), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the \`replace\` tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
@@ -2709,6 +2819,16 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. \`replace\`, \`write_file\`), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the \`replace\` tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
@@ -2851,6 +2971,16 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. \`replace\`, \`write_file\`), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the \`replace\` tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
@@ -3025,6 +3155,16 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. \`replace\`, \`write_file\`), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the \`replace\` tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
@@ -3345,6 +3485,16 @@ You are operating with a persistent file-based task tracking system located at \
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. \`replace\`, \`write_file\`), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the \`replace\` tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
@@ -3774,6 +3924,16 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. \`replace\`, \`write_file\`), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the \`replace\` tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
@@ -3948,6 +4108,16 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. \`replace\`, \`write_file\`), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the \`replace\` tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
@@ -4241,6 +4411,16 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. \`replace\`, \`write_file\`), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the \`replace\` tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
@@ -4415,6 +4595,16 @@ Operate using a **Research -> Strategy -> Execution** lifecycle. For the Executi
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. \`replace\`, \`write_file\`), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the \`replace\` tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the \`run_shell_command\` tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2026 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { AgentChatHistory, type HistoryTurn } from './agentChatHistory.js';
|
||||
|
||||
describe('AgentChatHistory', () => {
|
||||
const dummyTurns: HistoryTurn[] = [
|
||||
{
|
||||
id: 'turn-1',
|
||||
content: { role: 'user', parts: [{ text: 'Hello' }] },
|
||||
},
|
||||
{
|
||||
id: 'turn-2',
|
||||
content: { role: 'model', parts: [{ text: 'Hi there' }] },
|
||||
},
|
||||
{
|
||||
id: 'turn-3',
|
||||
content: { role: 'user', parts: [{ text: 'How are you?' }] },
|
||||
},
|
||||
];
|
||||
|
||||
it('should initialize with empty history by default', () => {
|
||||
const history = new AgentChatHistory();
|
||||
expect(history.length).toBe(0);
|
||||
expect(history.get()).toEqual([]);
|
||||
});
|
||||
|
||||
it('should initialize with provided turns', () => {
|
||||
const history = new AgentChatHistory(dummyTurns);
|
||||
expect(history.length).toBe(3);
|
||||
expect(history.get()).toEqual(dummyTurns);
|
||||
});
|
||||
|
||||
it('should push new turns', () => {
|
||||
const history = new AgentChatHistory();
|
||||
history.push(dummyTurns[0]);
|
||||
expect(history.length).toBe(1);
|
||||
expect(history.get()[0]).toEqual(dummyTurns[0]);
|
||||
});
|
||||
|
||||
it('should set and overwrite history turns', () => {
|
||||
const history = new AgentChatHistory(dummyTurns.slice(0, 1));
|
||||
expect(history.length).toBe(1);
|
||||
history.set(dummyTurns);
|
||||
expect(history.length).toBe(3);
|
||||
expect(history.get()).toEqual(dummyTurns);
|
||||
});
|
||||
|
||||
it('should clear history', () => {
|
||||
const history = new AgentChatHistory(dummyTurns);
|
||||
expect(history.length).toBe(3);
|
||||
history.clear();
|
||||
expect(history.length).toBe(0);
|
||||
expect(history.get()).toEqual([]);
|
||||
});
|
||||
|
||||
describe('rollback', () => {
|
||||
it('should roll back history to a specified length', () => {
|
||||
const history = new AgentChatHistory(dummyTurns);
|
||||
history.rollback(1);
|
||||
expect(history.length).toBe(1);
|
||||
expect(history.get()).toEqual([dummyTurns[0]]);
|
||||
});
|
||||
|
||||
it('should roll back to 0', () => {
|
||||
const history = new AgentChatHistory(dummyTurns);
|
||||
history.rollback(0);
|
||||
expect(history.length).toBe(0);
|
||||
expect(history.get()).toEqual([]);
|
||||
});
|
||||
|
||||
it('should do nothing if rollback length is out of bounds (negative)', () => {
|
||||
const history = new AgentChatHistory(dummyTurns);
|
||||
history.rollback(-1);
|
||||
expect(history.length).toBe(3);
|
||||
expect(history.get()).toEqual(dummyTurns);
|
||||
});
|
||||
|
||||
it('should do nothing if rollback length is out of bounds (greater than current history length)', () => {
|
||||
const history = new AgentChatHistory(dummyTurns);
|
||||
history.rollback(5);
|
||||
expect(history.length).toBe(3);
|
||||
expect(history.get()).toEqual(dummyTurns);
|
||||
});
|
||||
});
|
||||
|
||||
it('should return raw Content array via getContents()', () => {
|
||||
const history = new AgentChatHistory(dummyTurns);
|
||||
expect(history.getContents()).toEqual(
|
||||
dummyTurns.map((turn) => turn.content),
|
||||
);
|
||||
});
|
||||
|
||||
it('should support mapping and flatMapping operations', () => {
|
||||
const history = new AgentChatHistory(dummyTurns);
|
||||
const mappedIds = history.map((turn) => turn.id);
|
||||
expect(mappedIds).toEqual(['turn-1', 'turn-2', 'turn-3']);
|
||||
|
||||
const flatMappedParts = history.flatMap((turn) => turn.content.parts || []);
|
||||
expect(flatMappedParts).toEqual([
|
||||
{ text: 'Hello' },
|
||||
{ text: 'Hi there' },
|
||||
{ text: 'How are you?' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -46,6 +46,16 @@ export class AgentChatHistory {
|
||||
this.history = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Rolls back the history to a specified length.
|
||||
* Useful when a stream fails and we need to remove the un-responded turn(s).
|
||||
*/
|
||||
rollback(length: number) {
|
||||
if (length >= 0 && length <= this.history.length) {
|
||||
this.history = this.history.slice(0, length);
|
||||
}
|
||||
}
|
||||
|
||||
get(): readonly HistoryTurn[] {
|
||||
return this.history;
|
||||
}
|
||||
|
||||
@@ -884,6 +884,555 @@ describe('GeminiChat', () => {
|
||||
).resolves.not.toThrow();
|
||||
});
|
||||
|
||||
it('should roll back the un-responded user turn from history when InvalidStreamError is thrown', async () => {
|
||||
const initialHistoryLength = chat.agentHistory.length;
|
||||
|
||||
// Setup: Stream with text but no finish reason and no tool call (will trigger InvalidStreamError)
|
||||
const streamWithoutFinishReason = (async function* () {
|
||||
yield {
|
||||
candidates: [
|
||||
{
|
||||
content: {
|
||||
role: 'model',
|
||||
parts: [{ text: 'some response' }],
|
||||
},
|
||||
// No finishReason
|
||||
},
|
||||
],
|
||||
} as unknown as GenerateContentResponse;
|
||||
})();
|
||||
|
||||
vi.mocked(mockContentGenerator.generateContentStream).mockResolvedValue(
|
||||
streamWithoutFinishReason,
|
||||
);
|
||||
|
||||
const stream = await chat.sendMessageStream(
|
||||
{ model: 'gemini-2.0-flash' },
|
||||
'test message to roll back',
|
||||
'prompt-id-rollback',
|
||||
new AbortController().signal,
|
||||
LlmRole.MAIN,
|
||||
);
|
||||
|
||||
// Verify the user turn WAS added during sendMessageStream
|
||||
expect(chat.agentHistory.length).toBe(initialHistoryLength + 1);
|
||||
expect(chat.getHistory()[initialHistoryLength].parts?.[0]?.text).toBe(
|
||||
'test message to roll back',
|
||||
);
|
||||
|
||||
await expect(
|
||||
(async () => {
|
||||
for await (const _ of stream) {
|
||||
// consume stream to trigger validation error
|
||||
}
|
||||
})(),
|
||||
).rejects.toThrow(InvalidStreamError);
|
||||
|
||||
// Verify history has been rolled back to its initial state
|
||||
expect(chat.agentHistory.length).toBe(initialHistoryLength);
|
||||
});
|
||||
|
||||
it('should preserve function responses during rollback when InvalidStreamError is thrown', async () => {
|
||||
// 1. Setup history ending with a model turn containing functionCall
|
||||
chat.agentHistory.push({
|
||||
id: 'model-turn-1',
|
||||
content: {
|
||||
role: 'model',
|
||||
parts: [
|
||||
{
|
||||
functionCall: {
|
||||
name: 'test_tool',
|
||||
args: {},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const initialHistoryLength = chat.agentHistory.length;
|
||||
|
||||
// Setup: Stream that will throw InvalidStreamError
|
||||
const streamWithNoResponseText = (async function* () {
|
||||
yield {
|
||||
candidates: [
|
||||
{
|
||||
content: { role: 'model', parts: [] },
|
||||
finishReason: 'STOP',
|
||||
},
|
||||
],
|
||||
} as unknown as GenerateContentResponse;
|
||||
})();
|
||||
|
||||
vi.mocked(mockContentGenerator.generateContentStream).mockResolvedValue(
|
||||
streamWithNoResponseText,
|
||||
);
|
||||
|
||||
const stream = await chat.sendMessageStream(
|
||||
{ model: 'gemini-2.0-flash' },
|
||||
[
|
||||
{
|
||||
functionResponse: {
|
||||
name: 'test_tool',
|
||||
response: { success: true },
|
||||
},
|
||||
},
|
||||
],
|
||||
'prompt-id-function-response-rollback',
|
||||
new AbortController().signal,
|
||||
LlmRole.MAIN,
|
||||
);
|
||||
|
||||
// Verify the function response was added
|
||||
expect(chat.agentHistory.length).toBe(initialHistoryLength + 1);
|
||||
|
||||
await expect(
|
||||
(async () => {
|
||||
for await (const _ of stream) {
|
||||
// consume
|
||||
}
|
||||
})(),
|
||||
).rejects.toThrow(InvalidStreamError);
|
||||
|
||||
// Verify that history was NOT rolled back, i.e., function response is preserved!
|
||||
expect(chat.agentHistory.length).toBe(initialHistoryLength + 1);
|
||||
const lastTurn = chat.agentHistory.get()[chat.agentHistory.length - 1];
|
||||
expect(lastTurn.content.parts?.[0]?.functionResponse).toBeDefined();
|
||||
});
|
||||
|
||||
it('should preserve mixed multimodal function responses during rollback when InvalidStreamError is thrown (regression)', async () => {
|
||||
// 1. Setup history ending with a model turn containing functionCall
|
||||
chat.agentHistory.push({
|
||||
id: 'model-turn-1',
|
||||
content: {
|
||||
role: 'model',
|
||||
parts: [
|
||||
{
|
||||
functionCall: {
|
||||
name: 'test_tool',
|
||||
args: {},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const initialHistoryLength = chat.agentHistory.length;
|
||||
|
||||
// Setup: Stream that will throw InvalidStreamError
|
||||
const streamWithNoResponseText = (async function* () {
|
||||
yield {
|
||||
candidates: [
|
||||
{
|
||||
content: { role: 'model', parts: [] },
|
||||
finishReason: 'STOP',
|
||||
},
|
||||
],
|
||||
} as unknown as GenerateContentResponse;
|
||||
})();
|
||||
|
||||
vi.mocked(mockContentGenerator.generateContentStream).mockResolvedValue(
|
||||
streamWithNoResponseText,
|
||||
);
|
||||
|
||||
const stream = await chat.sendMessageStream(
|
||||
{ model: 'gemini-2.0-flash' },
|
||||
[
|
||||
{
|
||||
functionResponse: {
|
||||
name: 'test_tool',
|
||||
response: { success: true },
|
||||
},
|
||||
},
|
||||
{
|
||||
fileData: {
|
||||
mimeType: 'image/png',
|
||||
fileUri: 'https://example.com/image.png',
|
||||
},
|
||||
},
|
||||
],
|
||||
'prompt-id-mixed-multimodal-rollback',
|
||||
new AbortController().signal,
|
||||
LlmRole.MAIN,
|
||||
);
|
||||
|
||||
// Verify the function response was added
|
||||
expect(chat.agentHistory.length).toBe(initialHistoryLength + 1);
|
||||
|
||||
await expect(
|
||||
(async () => {
|
||||
for await (const _ of stream) {
|
||||
// consume
|
||||
}
|
||||
})(),
|
||||
).rejects.toThrow(InvalidStreamError);
|
||||
|
||||
// Verify that history was NOT rolled back, i.e., function response and sibling fileData are preserved!
|
||||
expect(chat.agentHistory.length).toBe(initialHistoryLength + 1);
|
||||
const lastTurn = chat.agentHistory.get()[chat.agentHistory.length - 1];
|
||||
expect(lastTurn.content.parts?.[0]?.functionResponse).toBeDefined();
|
||||
expect(lastTurn.content.parts?.[1]?.fileData).toBeDefined();
|
||||
});
|
||||
|
||||
it('should restore the lastPromptTokenCount baseline on history rollback when InvalidStreamError is thrown', async () => {
|
||||
// Establish an initial token count baseline
|
||||
const initialBaseline = chat.getLastPromptTokenCount();
|
||||
|
||||
// Setup: Stream that yields usageMetadata updating token count and then throws an InvalidStreamError
|
||||
const streamWithUsageAndFailure = (async function* () {
|
||||
yield {
|
||||
candidates: [
|
||||
{
|
||||
content: {
|
||||
role: 'model',
|
||||
parts: [{ text: '' }],
|
||||
},
|
||||
finishReason: 'STOP',
|
||||
},
|
||||
],
|
||||
usageMetadata: {
|
||||
promptTokenCount: initialBaseline + 500, // mock updated larger token count
|
||||
candidatesTokenCount: 10,
|
||||
totalTokenCount: initialBaseline + 510,
|
||||
},
|
||||
} as unknown as GenerateContentResponse;
|
||||
})();
|
||||
|
||||
vi.mocked(mockContentGenerator.generateContentStream).mockResolvedValue(
|
||||
streamWithUsageAndFailure,
|
||||
);
|
||||
|
||||
const stream = await chat.sendMessageStream(
|
||||
{ model: 'gemini-2.0-flash' },
|
||||
'test prompt for token baseline rollback',
|
||||
'prompt-id-baseline-rollback',
|
||||
new AbortController().signal,
|
||||
LlmRole.MAIN,
|
||||
);
|
||||
|
||||
await expect(
|
||||
(async () => {
|
||||
for await (const _ of stream) {
|
||||
// consume stream to trigger validation error
|
||||
}
|
||||
})(),
|
||||
).rejects.toThrow(InvalidStreamError);
|
||||
|
||||
// Verify that the prompt token count has been successfully restored to its initial baseline
|
||||
expect(chat.getLastPromptTokenCount()).toBe(initialBaseline);
|
||||
});
|
||||
|
||||
it('should not write failed retry attempts to the chat recording service', async () => {
|
||||
const recordMessageSpy = vi.spyOn(
|
||||
chat.getChatRecordingService(),
|
||||
'recordMessage',
|
||||
);
|
||||
const recordSyntheticMessageSpy = vi.spyOn(
|
||||
chat.getChatRecordingService(),
|
||||
'recordSyntheticMessage',
|
||||
);
|
||||
|
||||
// Attempt 1: returns invalid stream (triggering InvalidStreamError)
|
||||
vi.mocked(mockContentGenerator.generateContentStream)
|
||||
.mockImplementationOnce(async () =>
|
||||
(async function* () {
|
||||
yield {
|
||||
candidates: [
|
||||
{
|
||||
content: { role: 'model', parts: [{ text: '' }] },
|
||||
finishReason: 'STOP',
|
||||
},
|
||||
],
|
||||
} as unknown as GenerateContentResponse;
|
||||
})(),
|
||||
)
|
||||
// Attempt 2: returns a valid response
|
||||
.mockImplementationOnce(async () =>
|
||||
(async function* () {
|
||||
yield {
|
||||
candidates: [
|
||||
{
|
||||
content: {
|
||||
role: 'model',
|
||||
parts: [{ text: 'successful retry response' }],
|
||||
},
|
||||
finishReason: 'STOP',
|
||||
},
|
||||
],
|
||||
} as unknown as GenerateContentResponse;
|
||||
})(),
|
||||
);
|
||||
|
||||
const stream = await chat.sendMessageStream(
|
||||
{ model: 'gemini-2.0-flash' },
|
||||
'test prompt for recording deferral',
|
||||
'prompt-id-recording-deferral',
|
||||
new AbortController().signal,
|
||||
LlmRole.MAIN,
|
||||
);
|
||||
|
||||
for await (const _ of stream) {
|
||||
// consume stream completely
|
||||
}
|
||||
|
||||
// 1. The execution was successful, and final history turn has the correct text
|
||||
const lastHistoryTurn =
|
||||
chat.agentHistory.get()[chat.agentHistory.length - 1];
|
||||
expect(lastHistoryTurn.content.parts?.[0]?.text).toBe(
|
||||
'successful retry response',
|
||||
);
|
||||
|
||||
// 2. recordMessage was only called for the successful turn
|
||||
// (The failed attempt was NEVER recorded!)
|
||||
const successfulCalls = recordMessageSpy.mock.calls.filter((call) => {
|
||||
const payload = call[0];
|
||||
return (
|
||||
typeof payload === 'object' &&
|
||||
payload !== null &&
|
||||
payload.content === 'successful retry response'
|
||||
);
|
||||
});
|
||||
const failedCalls = recordMessageSpy.mock.calls.filter((call) => {
|
||||
const payload = call[0];
|
||||
return (
|
||||
typeof payload === 'object' &&
|
||||
payload !== null &&
|
||||
payload.content === ''
|
||||
);
|
||||
});
|
||||
|
||||
expect(successfulCalls.length).toBe(1);
|
||||
expect(failedCalls.length).toBe(0);
|
||||
expect(recordSyntheticMessageSpy).not.toHaveBeenCalled();
|
||||
|
||||
recordMessageSpy.mockRestore();
|
||||
recordSyntheticMessageSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should not record thoughts or usage metadata to chatRecordingService from failed stream attempts', async () => {
|
||||
const recordThoughtSpy = vi.spyOn(
|
||||
chat.getChatRecordingService(),
|
||||
'recordThought',
|
||||
);
|
||||
const recordMessageTokensSpy = vi.spyOn(
|
||||
chat.getChatRecordingService(),
|
||||
'recordMessageTokens',
|
||||
);
|
||||
|
||||
// Attempt 1: returns invalid stream with thoughts and usage metadata (triggering InvalidStreamError)
|
||||
vi.mocked(mockContentGenerator.generateContentStream)
|
||||
.mockImplementationOnce(async () =>
|
||||
(async function* () {
|
||||
yield {
|
||||
candidates: [
|
||||
{
|
||||
content: {
|
||||
role: 'model',
|
||||
parts: [
|
||||
{
|
||||
thought: true,
|
||||
text: '**Stale subject** Stale description',
|
||||
},
|
||||
],
|
||||
},
|
||||
finishReason: 'STOP',
|
||||
},
|
||||
],
|
||||
usageMetadata: {
|
||||
promptTokenCount: 1000,
|
||||
candidatesTokenCount: 50,
|
||||
totalTokenCount: 1050,
|
||||
},
|
||||
} as unknown as GenerateContentResponse;
|
||||
})(),
|
||||
)
|
||||
// Attempt 2: returns a valid response with separate thoughts and usage metadata
|
||||
.mockImplementationOnce(async () =>
|
||||
(async function* () {
|
||||
yield {
|
||||
candidates: [
|
||||
{
|
||||
content: {
|
||||
role: 'model',
|
||||
parts: [
|
||||
{
|
||||
thought: true,
|
||||
text: '**Fresh subject** Fresh description',
|
||||
},
|
||||
{ text: 'successful retry response' },
|
||||
],
|
||||
},
|
||||
finishReason: 'STOP',
|
||||
},
|
||||
],
|
||||
usageMetadata: {
|
||||
promptTokenCount: 2000,
|
||||
candidatesTokenCount: 100,
|
||||
totalTokenCount: 2100,
|
||||
},
|
||||
} as unknown as GenerateContentResponse;
|
||||
})(),
|
||||
);
|
||||
|
||||
const stream = await chat.sendMessageStream(
|
||||
{ model: 'gemini-2.0-flash' },
|
||||
'test prompt for metadata deferral',
|
||||
'prompt-id-metadata-deferral',
|
||||
new AbortController().signal,
|
||||
LlmRole.MAIN,
|
||||
);
|
||||
|
||||
for await (const _ of stream) {
|
||||
// consume stream completely
|
||||
}
|
||||
|
||||
// Verify that recordThought was NOT called with the first (failed) attempt's thoughts
|
||||
expect(recordThoughtSpy).toHaveBeenCalledTimes(1);
|
||||
expect(recordThoughtSpy).toHaveBeenCalledWith({
|
||||
subject: 'Fresh subject',
|
||||
description: 'Fresh description',
|
||||
});
|
||||
expect(recordThoughtSpy).not.toHaveBeenCalledWith({
|
||||
subject: 'Stale subject',
|
||||
description: 'Stale description',
|
||||
});
|
||||
|
||||
// Verify that recordMessageTokens was only called with the second (successful) attempt's metadata
|
||||
expect(recordMessageTokensSpy).toHaveBeenCalledTimes(1);
|
||||
expect(recordMessageTokensSpy).toHaveBeenCalledWith({
|
||||
promptTokenCount: 2000,
|
||||
candidatesTokenCount: 100,
|
||||
totalTokenCount: 2100,
|
||||
});
|
||||
|
||||
// Verify that the prompt token count is correct
|
||||
expect(chat.getLastPromptTokenCount()).toBe(2000);
|
||||
|
||||
recordThoughtSpy.mockRestore();
|
||||
recordMessageTokensSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should sync the chat recording service on history rollback when InvalidStreamError is thrown', async () => {
|
||||
const initialHistoryLength = chat.agentHistory.length;
|
||||
const updateSpy = vi.spyOn(
|
||||
chat.getChatRecordingService(),
|
||||
'updateMessagesFromHistory',
|
||||
);
|
||||
|
||||
// Setup: Stream with text but no finish reason and no tool call (will trigger InvalidStreamError)
|
||||
const streamWithoutFinishReason = (async function* () {
|
||||
yield {
|
||||
candidates: [
|
||||
{
|
||||
content: {
|
||||
role: 'model',
|
||||
parts: [{ text: 'some response' }],
|
||||
},
|
||||
// No finishReason
|
||||
},
|
||||
],
|
||||
} as unknown as GenerateContentResponse;
|
||||
})();
|
||||
|
||||
vi.mocked(mockContentGenerator.generateContentStream).mockResolvedValue(
|
||||
streamWithoutFinishReason,
|
||||
);
|
||||
|
||||
const stream = await chat.sendMessageStream(
|
||||
{ model: 'gemini-2.0-flash' },
|
||||
'test disk sync rollback',
|
||||
'prompt-id-rollback-sync',
|
||||
new AbortController().signal,
|
||||
LlmRole.MAIN,
|
||||
);
|
||||
|
||||
await expect(
|
||||
(async () => {
|
||||
for await (const _ of stream) {
|
||||
// consume stream to trigger validation error
|
||||
}
|
||||
})(),
|
||||
).rejects.toThrow(InvalidStreamError);
|
||||
|
||||
// Verify history has been rolled back to its initial state
|
||||
expect(chat.agentHistory.length).toBe(initialHistoryLength);
|
||||
// Verify chatRecordingService.updateMessagesFromHistory was called to sync the disk
|
||||
expect(updateSpy).toHaveBeenCalled();
|
||||
|
||||
updateSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should roll back the un-responded user turn from history when the stream is aborted/cancelled', async () => {
|
||||
const initialHistoryLength = chat.agentHistory.length;
|
||||
const abortController = new AbortController();
|
||||
|
||||
// Setup: Stream that aborts/fails mid-generation
|
||||
const streamWithAbort = (async function* () {
|
||||
yield {
|
||||
candidates: [
|
||||
{
|
||||
content: {
|
||||
role: 'model',
|
||||
parts: [{ text: 'some text' }],
|
||||
},
|
||||
},
|
||||
],
|
||||
} as unknown as GenerateContentResponse;
|
||||
abortController.abort();
|
||||
throw new Error('User aborted a request.');
|
||||
})();
|
||||
|
||||
vi.mocked(mockContentGenerator.generateContentStream).mockResolvedValue(
|
||||
streamWithAbort,
|
||||
);
|
||||
|
||||
const stream = await chat.sendMessageStream(
|
||||
{ model: 'gemini-2.0-flash' },
|
||||
'test abort message',
|
||||
'prompt-id-abort',
|
||||
abortController.signal,
|
||||
LlmRole.MAIN,
|
||||
);
|
||||
|
||||
await expect(
|
||||
(async () => {
|
||||
for await (const _ of stream) {
|
||||
// consume stream to trigger abort error
|
||||
}
|
||||
})(),
|
||||
).rejects.toThrow();
|
||||
|
||||
// Verify history has been rolled back to its initial state
|
||||
expect(chat.agentHistory.length).toBe(initialHistoryLength);
|
||||
});
|
||||
|
||||
it('should roll back the un-responded user turn from history when an ApiError is thrown', async () => {
|
||||
const initialHistoryLength = chat.agentHistory.length;
|
||||
|
||||
// Setup: Stream that throws a standard API error
|
||||
vi.mocked(mockContentGenerator.generateContentStream).mockRejectedValue(
|
||||
new Error('API rate limit reached'),
|
||||
);
|
||||
|
||||
const stream = await chat.sendMessageStream(
|
||||
{ model: 'gemini-2.0-flash' },
|
||||
'test api error message',
|
||||
'prompt-id-api-error',
|
||||
new AbortController().signal,
|
||||
LlmRole.MAIN,
|
||||
);
|
||||
|
||||
await expect(
|
||||
(async () => {
|
||||
for await (const _ of stream) {
|
||||
// consume stream
|
||||
}
|
||||
})(),
|
||||
).rejects.toThrow('API rate limit reached');
|
||||
|
||||
// Verify history has been rolled back to its initial state
|
||||
expect(chat.agentHistory.length).toBe(initialHistoryLength);
|
||||
});
|
||||
|
||||
it('should throw InvalidStreamError when no tool call and no finish reason', async () => {
|
||||
// Setup: Stream with text but no finish reason and no tool call
|
||||
const streamWithoutFinishReason = (async function* () {
|
||||
@@ -921,7 +1470,7 @@ describe('GeminiChat', () => {
|
||||
).rejects.toThrow(InvalidStreamError);
|
||||
});
|
||||
|
||||
it('should throw InvalidStreamError without retrying when no tool call and empty response text', async () => {
|
||||
it('should retry when no tool call and empty response text, and succeed if a retry succeeds', async () => {
|
||||
vi.mocked(mockContentGenerator.generateContentStream)
|
||||
.mockImplementationOnce(async () =>
|
||||
// First attempt: finish reason is present, but the stream has no
|
||||
@@ -941,7 +1490,7 @@ describe('GeminiChat', () => {
|
||||
})(),
|
||||
)
|
||||
.mockImplementationOnce(async () =>
|
||||
// This would succeed if NO_RESPONSE_TEXT were retried.
|
||||
// Second attempt: succeeds
|
||||
(async function* () {
|
||||
yield {
|
||||
candidates: [
|
||||
@@ -965,6 +1514,54 @@ describe('GeminiChat', () => {
|
||||
LlmRole.MAIN,
|
||||
);
|
||||
|
||||
const chunks: GenerateContentResponse[] = [];
|
||||
for await (const chunk of stream) {
|
||||
if (chunk.type === StreamEventType.CHUNK) {
|
||||
chunks.push(chunk.value);
|
||||
}
|
||||
}
|
||||
|
||||
expect(mockContentGenerator.generateContentStream).toHaveBeenCalledTimes(
|
||||
2,
|
||||
);
|
||||
expect(mockLogContentRetry).toHaveBeenCalledTimes(1);
|
||||
expect(mockLogContentRetryFailure).not.toHaveBeenCalled();
|
||||
expect(chunks.length).toBe(2);
|
||||
expect(chunks[0].candidates?.[0]?.content?.parts?.[0]?.thought).toBe(
|
||||
true,
|
||||
);
|
||||
expect(chunks[1].candidates?.[0]?.content?.parts?.[0]?.text).toBe(
|
||||
'valid response after retry',
|
||||
);
|
||||
});
|
||||
|
||||
it('should retry when no tool call and empty response text, and throw InvalidStreamError after exhausting retries', async () => {
|
||||
vi.mocked(mockContentGenerator.generateContentStream).mockImplementation(
|
||||
async () =>
|
||||
// All attempts return empty response text
|
||||
(async function* () {
|
||||
yield {
|
||||
candidates: [
|
||||
{
|
||||
content: {
|
||||
role: 'model',
|
||||
parts: [{ thought: true, text: 'thinking...' }],
|
||||
},
|
||||
finishReason: 'STOP',
|
||||
},
|
||||
],
|
||||
} as unknown as GenerateContentResponse;
|
||||
})(),
|
||||
);
|
||||
|
||||
const stream = await chat.sendMessageStream(
|
||||
{ model: 'gemini-2.0-flash' },
|
||||
'test message',
|
||||
'prompt-id-1',
|
||||
new AbortController().signal,
|
||||
LlmRole.MAIN,
|
||||
);
|
||||
|
||||
await expect(
|
||||
(async () => {
|
||||
for await (const _ of stream) {
|
||||
@@ -972,10 +1569,11 @@ describe('GeminiChat', () => {
|
||||
}
|
||||
})(),
|
||||
).rejects.toThrow(InvalidStreamError);
|
||||
|
||||
expect(mockContentGenerator.generateContentStream).toHaveBeenCalledTimes(
|
||||
1,
|
||||
4,
|
||||
);
|
||||
expect(mockLogContentRetry).not.toHaveBeenCalled();
|
||||
expect(mockLogContentRetry).toHaveBeenCalledTimes(3);
|
||||
expect(mockLogContentRetryFailure).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
@@ -1117,6 +1715,157 @@ describe('GeminiChat', () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should throw InvalidStreamError with type MAX_TOKENS_EXCEEDED when finishReason is MAX_TOKENS and text is empty', async () => {
|
||||
vi.mocked(mockContentGenerator.generateContentStream).mockImplementation(
|
||||
async () =>
|
||||
(async function* () {
|
||||
yield {
|
||||
candidates: [
|
||||
{
|
||||
content: { role: 'model', parts: [] },
|
||||
finishReason: 'MAX_TOKENS',
|
||||
},
|
||||
],
|
||||
} as unknown as GenerateContentResponse;
|
||||
})(),
|
||||
);
|
||||
|
||||
const stream = await chat.sendMessageStream(
|
||||
{ model: 'gemini-2.5-pro' },
|
||||
'test',
|
||||
'prompt-id-max-tokens',
|
||||
new AbortController().signal,
|
||||
LlmRole.MAIN,
|
||||
);
|
||||
|
||||
let error: unknown;
|
||||
try {
|
||||
const chunks = [];
|
||||
for await (const chunk of stream) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
expect(error).toBeInstanceOf(InvalidStreamError);
|
||||
expect((error as InvalidStreamError).type).toBe('MAX_TOKENS_EXCEEDED');
|
||||
});
|
||||
|
||||
it('should throw InvalidStreamError with type THINKING_ONLY_RESPONSE when response contains thoughts but text is empty', async () => {
|
||||
vi.mocked(mockContentGenerator.generateContentStream).mockImplementation(
|
||||
async () =>
|
||||
(async function* () {
|
||||
yield {
|
||||
candidates: [
|
||||
{
|
||||
content: {
|
||||
role: 'model',
|
||||
parts: [{ thought: true, text: 'thinking...' }],
|
||||
},
|
||||
finishReason: 'STOP',
|
||||
},
|
||||
],
|
||||
} as unknown as GenerateContentResponse;
|
||||
})(),
|
||||
);
|
||||
|
||||
const stream = await chat.sendMessageStream(
|
||||
{ model: 'gemini-2.5-pro' },
|
||||
'test',
|
||||
'prompt-id-thoughts-only',
|
||||
new AbortController().signal,
|
||||
LlmRole.MAIN,
|
||||
);
|
||||
|
||||
let error: unknown;
|
||||
try {
|
||||
const chunks = [];
|
||||
for await (const chunk of stream) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
expect(error).toBeInstanceOf(InvalidStreamError);
|
||||
expect((error as InvalidStreamError).type).toBe('THINKING_ONLY_RESPONSE');
|
||||
});
|
||||
|
||||
it('should throw InvalidStreamError when response consists only of zero-width or invisible characters', async () => {
|
||||
vi.mocked(mockContentGenerator.generateContentStream).mockImplementation(
|
||||
async () =>
|
||||
(async function* () {
|
||||
yield {
|
||||
candidates: [
|
||||
{
|
||||
content: {
|
||||
role: 'model',
|
||||
parts: [{ text: '\u200B\uFEFF\u200D' }],
|
||||
},
|
||||
finishReason: 'STOP',
|
||||
},
|
||||
],
|
||||
} as unknown as GenerateContentResponse;
|
||||
})(),
|
||||
);
|
||||
|
||||
const stream = await chat.sendMessageStream(
|
||||
{ model: 'gemini-2.5-pro' },
|
||||
'test',
|
||||
'prompt-id-invisible-only',
|
||||
new AbortController().signal,
|
||||
LlmRole.MAIN,
|
||||
);
|
||||
|
||||
let error: unknown;
|
||||
try {
|
||||
for await (const _ of stream) {
|
||||
// consume
|
||||
}
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
expect(error).toBeInstanceOf(InvalidStreamError);
|
||||
expect((error as InvalidStreamError).type).toBe('NO_RESPONSE_TEXT');
|
||||
});
|
||||
|
||||
it('should throw InvalidStreamError when response consists only of HTML or Markdown comment blocks', async () => {
|
||||
vi.mocked(mockContentGenerator.generateContentStream).mockImplementation(
|
||||
async () =>
|
||||
(async function* () {
|
||||
yield {
|
||||
candidates: [
|
||||
{
|
||||
content: {
|
||||
role: 'model',
|
||||
parts: [{ text: '<!-- invisible comment -->' }],
|
||||
},
|
||||
finishReason: 'STOP',
|
||||
},
|
||||
],
|
||||
} as unknown as GenerateContentResponse;
|
||||
})(),
|
||||
);
|
||||
|
||||
const stream = await chat.sendMessageStream(
|
||||
{ model: 'gemini-2.5-pro' },
|
||||
'test',
|
||||
'prompt-id-comments-only',
|
||||
new AbortController().signal,
|
||||
LlmRole.MAIN,
|
||||
);
|
||||
|
||||
let error: unknown;
|
||||
try {
|
||||
for await (const _ of stream) {
|
||||
// consume
|
||||
}
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
expect(error).toBeInstanceOf(InvalidStreamError);
|
||||
expect((error as InvalidStreamError).type).toBe('NO_RESPONSE_TEXT');
|
||||
});
|
||||
|
||||
it('should call generateContentStream with the correct parameters', async () => {
|
||||
const response = (async function* () {
|
||||
yield {
|
||||
@@ -1545,6 +2294,84 @@ describe('GeminiChat', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should append nudge message to systemInstruction on retry when InvalidStreamError occurs', async () => {
|
||||
vi.mocked(mockContentGenerator.generateContentStream)
|
||||
.mockImplementationOnce(async () =>
|
||||
(async function* () {
|
||||
yield {
|
||||
candidates: [
|
||||
{
|
||||
content: {
|
||||
role: 'model',
|
||||
parts: [{ thought: true, text: 'thinking...' }],
|
||||
},
|
||||
finishReason: 'STOP',
|
||||
},
|
||||
],
|
||||
} as unknown as GenerateContentResponse;
|
||||
})(),
|
||||
)
|
||||
.mockImplementationOnce(async () =>
|
||||
(async function* () {
|
||||
yield {
|
||||
candidates: [
|
||||
{
|
||||
content: { parts: [{ text: 'valid response after nudge' }] },
|
||||
finishReason: 'STOP',
|
||||
},
|
||||
],
|
||||
} as unknown as GenerateContentResponse;
|
||||
})(),
|
||||
);
|
||||
|
||||
chat.setSystemInstruction('Initial instruction');
|
||||
|
||||
const stream = await chat.sendMessageStream(
|
||||
{ model: 'gemini-2.5-pro' },
|
||||
'test',
|
||||
'prompt-id-retry-nudge',
|
||||
new AbortController().signal,
|
||||
LlmRole.MAIN,
|
||||
);
|
||||
|
||||
for await (const _ of stream) {
|
||||
// consume
|
||||
}
|
||||
|
||||
expect(mockContentGenerator.generateContentStream).toHaveBeenCalledTimes(
|
||||
2,
|
||||
);
|
||||
|
||||
// First call should have original system instruction
|
||||
expect(
|
||||
mockContentGenerator.generateContentStream,
|
||||
).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({
|
||||
config: expect.objectContaining({
|
||||
systemInstruction: 'Initial instruction',
|
||||
}),
|
||||
}),
|
||||
'prompt-id-retry-nudge',
|
||||
LlmRole.MAIN,
|
||||
);
|
||||
|
||||
// Second call (retry) should have nudge message appended to systemInstruction
|
||||
expect(
|
||||
mockContentGenerator.generateContentStream,
|
||||
).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
config: expect.objectContaining({
|
||||
systemInstruction:
|
||||
'Initial instruction\n[System: You previously generated thoughts but failed to provide a final user-facing response. Please ensure you provide your final answer or call a tool now.]',
|
||||
}),
|
||||
}),
|
||||
'prompt-id-retry-nudge',
|
||||
LlmRole.MAIN,
|
||||
);
|
||||
});
|
||||
|
||||
it('should fail after all retries on persistent invalid content and report metrics', async () => {
|
||||
vi.mocked(mockContentGenerator.generateContentStream).mockImplementation(
|
||||
async () =>
|
||||
@@ -1582,13 +2409,9 @@ describe('GeminiChat', () => {
|
||||
expect(mockLogContentRetry).toHaveBeenCalledTimes(3);
|
||||
expect(mockLogContentRetryFailure).toHaveBeenCalledTimes(1);
|
||||
|
||||
// History should still contain the user message.
|
||||
// History should be rolled back to exclude the un-responded user message.
|
||||
const history = chat.getHistory();
|
||||
expect(history.length).toBe(1);
|
||||
expect(history[0]).toEqual({
|
||||
role: 'user',
|
||||
parts: [{ text: 'test' }],
|
||||
});
|
||||
expect(history.length).toBe(0);
|
||||
});
|
||||
|
||||
describe('API error retry behavior', () => {
|
||||
@@ -3076,6 +3899,48 @@ describe('GeminiChat', () => {
|
||||
'video/mp4',
|
||||
);
|
||||
});
|
||||
|
||||
it('should preserve all synthetic binary injection turns when the stream fails', async () => {
|
||||
const initialHistoryLength = chat.agentHistory.length;
|
||||
const audioParts = [
|
||||
{
|
||||
functionResponse: {
|
||||
id: 'call-123',
|
||||
name: 'read_file',
|
||||
response: {
|
||||
output: 'Success',
|
||||
[BINARY_INJECTION_KEY]: [
|
||||
{ inlineData: { mimeType: 'audio/mpeg', data: 'base64' } },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// Setup: Stream that throws an error
|
||||
vi.mocked(mockContentGenerator.generateContentStream).mockRejectedValue(
|
||||
new Error('API error during binary injection stream'),
|
||||
);
|
||||
|
||||
const stream = await chat.sendMessageStream(
|
||||
{ model: 'gemini-pro' },
|
||||
audioParts,
|
||||
'test-id',
|
||||
new AbortController().signal,
|
||||
LlmRole.MAIN,
|
||||
);
|
||||
|
||||
await expect(
|
||||
(async () => {
|
||||
for await (const _ of stream) {
|
||||
// consume stream
|
||||
}
|
||||
})(),
|
||||
).rejects.toThrow('API error during binary injection stream');
|
||||
|
||||
// Verify that history has been preserved, and all 3 synthetic binary injection turns are kept.
|
||||
expect(chat.agentHistory.length).toBe(initialHistoryLength + 3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('recordCompletedToolCalls', () => {
|
||||
|
||||
@@ -55,7 +55,11 @@ import {
|
||||
} from '../telemetry/types.js';
|
||||
import { handleFallback } from '../fallback/handler.js';
|
||||
import { isFunctionResponse } from '../utils/messageInspectors.js';
|
||||
import { scrubHistory, scrubContents } from '../utils/historyHardening.js';
|
||||
import {
|
||||
hardenHistory,
|
||||
scrubHistory,
|
||||
scrubContents,
|
||||
} from '../utils/historyHardening.js';
|
||||
import {
|
||||
partListUnionToString,
|
||||
ensureStableToolIds,
|
||||
@@ -225,7 +229,12 @@ export class InvalidStreamError extends Error {
|
||||
| 'NO_FINISH_REASON'
|
||||
| 'NO_RESPONSE_TEXT'
|
||||
| 'MALFORMED_FUNCTION_CALL'
|
||||
| 'UNEXPECTED_TOOL_CALL';
|
||||
| 'UNEXPECTED_TOOL_CALL'
|
||||
| 'MAX_TOKENS_EXCEEDED'
|
||||
| 'SAFETY_BLOCKED'
|
||||
| 'RECITATION_BLOCKED'
|
||||
| 'OTHER_BLOCKED'
|
||||
| 'THINKING_ONLY_RESPONSE';
|
||||
|
||||
constructor(
|
||||
message: string,
|
||||
@@ -233,7 +242,12 @@ export class InvalidStreamError extends Error {
|
||||
| 'NO_FINISH_REASON'
|
||||
| 'NO_RESPONSE_TEXT'
|
||||
| 'MALFORMED_FUNCTION_CALL'
|
||||
| 'UNEXPECTED_TOOL_CALL',
|
||||
| 'UNEXPECTED_TOOL_CALL'
|
||||
| 'MAX_TOKENS_EXCEEDED'
|
||||
| 'SAFETY_BLOCKED'
|
||||
| 'RECITATION_BLOCKED'
|
||||
| 'OTHER_BLOCKED'
|
||||
| 'THINKING_ONLY_RESPONSE',
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'InvalidStreamError';
|
||||
@@ -387,6 +401,9 @@ export class GeminiChat {
|
||||
): Promise<AsyncGenerator<StreamEvent>> {
|
||||
await this.sendPromise;
|
||||
|
||||
const historyLengthBefore = this.agentHistory.length;
|
||||
const baselinePromptTokenCount = this.lastPromptTokenCount;
|
||||
|
||||
let streamDoneResolver: () => void;
|
||||
const streamDonePromise = new Promise<void>((resolve) => {
|
||||
streamDoneResolver = resolve;
|
||||
@@ -394,6 +411,7 @@ export class GeminiChat {
|
||||
this.sendPromise = streamDonePromise;
|
||||
|
||||
let userContent = createUserContent(message);
|
||||
const isOriginalFunctionResponse = isFunctionResponse(userContent);
|
||||
const { model } =
|
||||
this.context.config.modelConfigService.getResolvedConfig(modelConfigKey);
|
||||
|
||||
@@ -402,7 +420,7 @@ export class GeminiChat {
|
||||
|
||||
// Record user input - capture complete message with all parts (text, files, images, etc.)
|
||||
// but skip recording function responses (tool call results) as they should be stored in tool call records
|
||||
if (!isFunctionResponse(userContent)) {
|
||||
if (!isOriginalFunctionResponse) {
|
||||
const userMessageParts = userContent.parts || [];
|
||||
const userMessageContent = partListUnionToString(userMessageParts);
|
||||
|
||||
@@ -519,6 +537,7 @@ export class GeminiChat {
|
||||
): AsyncGenerator<StreamEvent, void, void> {
|
||||
try {
|
||||
const maxAttempts = this.context.config.getMaxAttempts();
|
||||
let lastStreamError: unknown = undefined;
|
||||
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
let isConnectionPhase = true;
|
||||
@@ -530,7 +549,7 @@ export class GeminiChat {
|
||||
// If this is a retry, update the key with the new context.
|
||||
const currentConfigKey =
|
||||
attempt > 0
|
||||
? { ...modelConfigKey, isRetry: true }
|
||||
? { ...modelConfigKey, isRetry: true, lastStreamError }
|
||||
: modelConfigKey;
|
||||
|
||||
isConnectionPhase = true;
|
||||
@@ -549,6 +568,10 @@ export class GeminiChat {
|
||||
|
||||
return;
|
||||
} catch (error) {
|
||||
if (error instanceof InvalidStreamError) {
|
||||
lastStreamError = error;
|
||||
}
|
||||
|
||||
if (error instanceof AgentExecutionStoppedError) {
|
||||
yield {
|
||||
type: StreamEventType.AGENT_EXECUTION_STOPPED,
|
||||
@@ -585,8 +608,7 @@ export class GeminiChat {
|
||||
);
|
||||
|
||||
const isContentError = error instanceof InvalidStreamError;
|
||||
const isRetryableContentError =
|
||||
isContentError && error.type !== 'NO_RESPONSE_TEXT';
|
||||
const isRetryableContentError = isContentError;
|
||||
const errorType = isContentError
|
||||
? error.type
|
||||
: getRetryErrorType(error);
|
||||
@@ -648,6 +670,15 @@ export class GeminiChat {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (!isOriginalFunctionResponse) {
|
||||
this.agentHistory.rollback(historyLengthBefore);
|
||||
this.chatRecordingService.updateMessagesFromHistory(
|
||||
this.agentHistory.get(),
|
||||
);
|
||||
this.lastPromptTokenCount = baselinePromptTokenCount;
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
streamDoneResolver!();
|
||||
}
|
||||
@@ -685,14 +716,9 @@ export class GeminiChat {
|
||||
role: LlmRole,
|
||||
apiHistoryOverride?: Content[],
|
||||
): Promise<AsyncGenerator<GenerateContentResponse>> {
|
||||
// Last mile scrubbing to remove internal tracking properties (e.g. callIndex)
|
||||
// before sending to the Gemini API. This whitelists only standard Gemini fields.
|
||||
let scrubbedHistory = this.context.config.isContextManagementEnabled()
|
||||
? scrubHistory([...requestHistory])
|
||||
: [...requestHistory];
|
||||
|
||||
// Always coalesce consecutive roles to prevent 400 Bad Request errors
|
||||
scrubbedHistory = coalesceConsecutiveRoles(scrubbedHistory);
|
||||
// Last mile hardening and scrubbing to ensure absolute compliance with Gemini API invariants
|
||||
// and remove internal tracking properties (e.g. callIndex).
|
||||
const scrubbedHistory = hardenHistory([...requestHistory]);
|
||||
|
||||
const scrubbedContents = scrubbedHistory.map((h) => h.content);
|
||||
|
||||
@@ -770,6 +796,30 @@ export class GeminiChat {
|
||||
abortSignal,
|
||||
};
|
||||
|
||||
// Apply Context-Aware Retries (On-Retry Nudging) to guide the model out of silent loops
|
||||
if (
|
||||
modelConfigKey.isRetry &&
|
||||
modelConfigKey.lastStreamError instanceof InvalidStreamError
|
||||
) {
|
||||
const lastError = modelConfigKey.lastStreamError;
|
||||
let nudgeMessage = '';
|
||||
if (lastError.type === 'THINKING_ONLY_RESPONSE') {
|
||||
nudgeMessage =
|
||||
'\n[System: You previously generated thoughts but failed to provide a final user-facing response. Please ensure you provide your final answer or call a tool now.]';
|
||||
} else if (lastError.type === 'NO_RESPONSE_TEXT') {
|
||||
nudgeMessage =
|
||||
'\n[System: You previously returned an empty response with no text or thoughts. Please ensure you provide your final answer or call a tool now.]';
|
||||
}
|
||||
|
||||
if (nudgeMessage) {
|
||||
if (typeof config.systemInstruction === 'string') {
|
||||
config.systemInstruction += nudgeMessage;
|
||||
} else if (config.systemInstruction === undefined) {
|
||||
config.systemInstruction = nudgeMessage;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let contentsToUse: Content[] =
|
||||
supportsModernFeatures(modelToUse) || isGemini2Model(modelToUse)
|
||||
? [...contentsForPreviewModel]
|
||||
@@ -1143,6 +1193,13 @@ export class GeminiChat {
|
||||
let hasThoughts = false;
|
||||
let finishReason: FinishReason | undefined;
|
||||
|
||||
// Buffers to prevent failed stream attempts from polluting telemetry and logs
|
||||
const bufferedThoughts: Array<{ subject: string; description: string }> =
|
||||
[];
|
||||
let bufferedUsageMetadata:
|
||||
| GenerateContentResponse['usageMetadata']
|
||||
| undefined = undefined;
|
||||
|
||||
// The SDK provides fully assembled FunctionCall objects in chunk.functionCalls
|
||||
// We use a Map to ensure we only keep the latest version of each call (by ID)
|
||||
const finalFunctionCallsMap = new Map<string, FunctionCall>();
|
||||
@@ -1198,7 +1255,10 @@ export class GeminiChat {
|
||||
if (content.parts.some((part) => part.thought)) {
|
||||
// Record thoughts
|
||||
hasThoughts = true;
|
||||
this.recordThoughtFromContent(content);
|
||||
const thought = this.extractThoughtFromContent(content);
|
||||
if (thought) {
|
||||
bufferedThoughts.push(thought);
|
||||
}
|
||||
}
|
||||
if (content.parts.some((part) => part.functionCall)) {
|
||||
hasToolCall = true;
|
||||
@@ -1226,12 +1286,9 @@ export class GeminiChat {
|
||||
}
|
||||
}
|
||||
|
||||
// Record token usage if this chunk has usageMetadata
|
||||
// Buffer token usage if this chunk has usageMetadata
|
||||
if (chunk.usageMetadata) {
|
||||
this.chatRecordingService.recordMessageTokens(chunk.usageMetadata);
|
||||
if (chunk.usageMetadata.promptTokenCount !== undefined) {
|
||||
this.lastPromptTokenCount = chunk.usageMetadata.promptTokenCount;
|
||||
}
|
||||
bufferedUsageMetadata = chunk.usageMetadata;
|
||||
}
|
||||
|
||||
const hookSystem = this.context.config.getHookSystem();
|
||||
@@ -1318,29 +1375,22 @@ export class GeminiChat {
|
||||
}
|
||||
}
|
||||
|
||||
const responseText = consolidatedParts
|
||||
const rawResponseText = consolidatedParts
|
||||
.filter((part) => part.text)
|
||||
.map((part) => part.text)
|
||||
.join('')
|
||||
.trim();
|
||||
.join('');
|
||||
|
||||
let id: string;
|
||||
// Record model response text from the collected parts.
|
||||
// Also flush when there are thoughts or a tool call (even with no text)
|
||||
// so that BeforeTool hooks always see the latest transcript state.
|
||||
if (responseText || hasThoughts || hasToolCall) {
|
||||
id = this.chatRecordingService.recordMessage({
|
||||
model,
|
||||
type: 'gemini',
|
||||
content: responseText,
|
||||
});
|
||||
} else {
|
||||
// Still need a durable ID even if response is empty (e.g. only tool calls)
|
||||
id = this.chatRecordingService.recordSyntheticMessage(
|
||||
'gemini',
|
||||
consolidatedParts,
|
||||
);
|
||||
}
|
||||
// Clean zero-width/invisible characters and HTML comments to determine actual printable/visible content
|
||||
let responseText = rawResponseText.replace(
|
||||
/[\u200B-\u200D\uFEFF\u200E\u200F]/g,
|
||||
'',
|
||||
);
|
||||
let previous: string;
|
||||
do {
|
||||
previous = responseText;
|
||||
responseText = responseText.replace(/<!--[\s\S]*?-->/g, '');
|
||||
} while (responseText !== previous);
|
||||
responseText = responseText.trim();
|
||||
|
||||
// Stream validation logic: A stream is considered successful if:
|
||||
// 1. There's a tool call OR
|
||||
@@ -1370,6 +1420,36 @@ export class GeminiChat {
|
||||
);
|
||||
}
|
||||
if (!responseText) {
|
||||
if (finishReason === FinishReason.MAX_TOKENS) {
|
||||
throw new InvalidStreamError(
|
||||
'Model stream ended due to token limit exhaustion (MAX_TOKENS) with empty response text.',
|
||||
'MAX_TOKENS_EXCEEDED',
|
||||
);
|
||||
}
|
||||
if (finishReason === FinishReason.SAFETY) {
|
||||
throw new InvalidStreamError(
|
||||
'Model stream ended due to safety settings (SAFETY) with empty response text.',
|
||||
'SAFETY_BLOCKED',
|
||||
);
|
||||
}
|
||||
if (finishReason === FinishReason.RECITATION) {
|
||||
throw new InvalidStreamError(
|
||||
'Model stream ended due to recitation settings (RECITATION) with empty response text.',
|
||||
'RECITATION_BLOCKED',
|
||||
);
|
||||
}
|
||||
if (finishReason === FinishReason.OTHER) {
|
||||
throw new InvalidStreamError(
|
||||
'Model stream ended due to other settings (OTHER) with empty response text.',
|
||||
'OTHER_BLOCKED',
|
||||
);
|
||||
}
|
||||
if (hasThoughts) {
|
||||
throw new InvalidStreamError(
|
||||
'Model stream ended with empty response text but contained reasoning thoughts.',
|
||||
'THINKING_ONLY_RESPONSE',
|
||||
);
|
||||
}
|
||||
throw new InvalidStreamError(
|
||||
'Model stream ended with empty response text.',
|
||||
'NO_RESPONSE_TEXT',
|
||||
@@ -1377,6 +1457,37 @@ export class GeminiChat {
|
||||
}
|
||||
}
|
||||
|
||||
// Flush buffered thoughts from the successful attempt
|
||||
for (const thought of bufferedThoughts) {
|
||||
this.chatRecordingService.recordThought(thought);
|
||||
}
|
||||
|
||||
// Flush buffered usage metadata and token counts from the successful attempt
|
||||
if (bufferedUsageMetadata) {
|
||||
this.chatRecordingService.recordMessageTokens(bufferedUsageMetadata);
|
||||
if (bufferedUsageMetadata.promptTokenCount !== undefined) {
|
||||
this.lastPromptTokenCount = bufferedUsageMetadata.promptTokenCount;
|
||||
}
|
||||
}
|
||||
|
||||
let id: string;
|
||||
// Record model response text from the collected parts.
|
||||
// Also flush when there are thoughts or a tool call (even with no text)
|
||||
// so that BeforeTool hooks always see the latest transcript state.
|
||||
if (responseText || hasThoughts || hasToolCall) {
|
||||
id = this.chatRecordingService.recordMessage({
|
||||
model,
|
||||
type: 'gemini',
|
||||
content: responseText,
|
||||
});
|
||||
} else {
|
||||
// Still need a durable ID even if response is empty (e.g. only tool calls)
|
||||
id = this.chatRecordingService.recordSyntheticMessage(
|
||||
'gemini',
|
||||
consolidatedParts,
|
||||
);
|
||||
}
|
||||
|
||||
this.agentHistory.push({
|
||||
id,
|
||||
content: { role: 'model', parts: consolidatedParts },
|
||||
@@ -1431,11 +1542,13 @@ export class GeminiChat {
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts and records thought from thought content.
|
||||
* Extracts thought from thought content.
|
||||
*/
|
||||
private recordThoughtFromContent(content: Content): void {
|
||||
private extractThoughtFromContent(
|
||||
content: Content,
|
||||
): { subject: string; description: string } | undefined {
|
||||
if (!content.parts || content.parts.length === 0) {
|
||||
return;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const thoughtPart = content.parts[0];
|
||||
@@ -1448,11 +1561,12 @@ export class GeminiChat {
|
||||
: '';
|
||||
const description = rawText.replace(/\*\*(.*?)\*\*/s, '').trim();
|
||||
|
||||
this.chatRecordingService.recordThought({
|
||||
return {
|
||||
subject,
|
||||
description,
|
||||
});
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -254,7 +254,15 @@ describe('Turn', () => {
|
||||
events.push(event);
|
||||
}
|
||||
|
||||
expect(events).toEqual([{ type: GeminiEventType.InvalidStream }]);
|
||||
expect(events).toEqual([
|
||||
{
|
||||
type: GeminiEventType.InvalidStream,
|
||||
value: {
|
||||
type: 'NO_FINISH_REASON',
|
||||
message: 'Test invalid stream',
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(turn.getDebugResponses().length).toBe(0);
|
||||
expect(reportError).not.toHaveBeenCalled(); // Should not report as error
|
||||
});
|
||||
|
||||
@@ -105,6 +105,19 @@ export type ServerGeminiContextWindowWillOverflowEvent = {
|
||||
|
||||
export type ServerGeminiInvalidStreamEvent = {
|
||||
type: GeminiEventType.InvalidStream;
|
||||
value: {
|
||||
type:
|
||||
| 'NO_FINISH_REASON'
|
||||
| 'NO_RESPONSE_TEXT'
|
||||
| 'MALFORMED_FUNCTION_CALL'
|
||||
| 'UNEXPECTED_TOOL_CALL'
|
||||
| 'MAX_TOKENS_EXCEEDED'
|
||||
| 'SAFETY_BLOCKED'
|
||||
| 'RECITATION_BLOCKED'
|
||||
| 'OTHER_BLOCKED'
|
||||
| 'THINKING_ONLY_RESPONSE';
|
||||
message: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type ServerGeminiModelInfoEvent = {
|
||||
@@ -408,7 +421,13 @@ export class Turn {
|
||||
}
|
||||
|
||||
if (e instanceof InvalidStreamError) {
|
||||
yield { type: GeminiEventType.InvalidStream };
|
||||
yield {
|
||||
type: GeminiEventType.InvalidStream,
|
||||
value: {
|
||||
type: e.type,
|
||||
message: e.message,
|
||||
},
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -413,6 +413,16 @@ export function renderOperationalGuidelines(
|
||||
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||
|
||||
## Tool Usage
|
||||
- **Tool Execution Response Rules:**
|
||||
1. After receiving a \`functionResponse\`, you MUST ALWAYS execute one of the following two actions:
|
||||
a) Call another tool to proceed with the task.
|
||||
b) Provide a user-facing text response explaining the tool output, your analysis, and next steps.
|
||||
2. You MUST NEVER return an empty response with no text and no tool calls.
|
||||
- **Post-Edit Response Rules:**
|
||||
1. After an edit tool execution (e.g. ${formatToolName(EDIT_TOOL_NAME)}, ${formatToolName(WRITE_FILE_TOOL_NAME)}), you MUST ALWAYS generate a user-facing text response summarizing:
|
||||
- What changes were made to the file.
|
||||
- Your verification plan or next steps (e.g. running tests).
|
||||
2. You MUST NEVER return an empty response with 0 text tokens after completing an edit.
|
||||
- **Parallelism & Sequencing:** Tools execute in parallel by default. Execute multiple independent tool calls in parallel when feasible (e.g., searching, reading files, independent shell commands, or editing *different* files). If a tool depends on the output or side-effects of a previous tool in the same turn (e.g., running a shell command that depends on the success of a previous command), you MUST set the \`wait_for_previous\` parameter to \`true\` on the dependent tool to ensure sequential execution.
|
||||
- **File Editing Collisions:** Do NOT make multiple calls to the ${formatToolName(EDIT_TOOL_NAME)} tool for the SAME file in a single turn. To make multiple edits to the same file, you MUST perform them sequentially across multiple conversational turns to prevent race conditions and ensure the file state is accurate before each edit.
|
||||
- **Command Execution:** Use the ${formatToolName(SHELL_TOOL_NAME)} tool for running shell commands, remembering the safety rule to explain modifying commands first.${toolUsageInteractive(
|
||||
|
||||
@@ -630,8 +630,8 @@ describe('Scheduler (Orchestrator)', () => {
|
||||
CoreToolCallStatus.Cancelled,
|
||||
'Operation cancelled by user',
|
||||
);
|
||||
// finalizeCall is handled by the processing loop, not synchronously by cancelAll
|
||||
// expect(mockStateManager.finalizeCall).toHaveBeenCalledWith('call-1');
|
||||
// finalizeCall is called synchronously by cancelAll to ensure completedBatch is populated and isActive is updated immediately
|
||||
expect(mockStateManager.finalizeCall).toHaveBeenCalledWith('call-1');
|
||||
expect(mockStateManager.cancelAllQueued).toHaveBeenCalledWith(
|
||||
'Operation cancelled by user',
|
||||
);
|
||||
|
||||
@@ -278,6 +278,7 @@ export class Scheduler {
|
||||
CoreToolCallStatus.Cancelled,
|
||||
'Operation cancelled by user',
|
||||
);
|
||||
this.state.finalizeCall(activeCall.request.callId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -438,6 +439,14 @@ export class Scheduler {
|
||||
*/
|
||||
private async _processNextItem(signal: AbortSignal): Promise<boolean> {
|
||||
if (signal.aborted || this.isCancelling) {
|
||||
// Finalize active calls that are terminal
|
||||
const activeCalls = this.state.allActiveCalls;
|
||||
for (const call of activeCalls) {
|
||||
if (this.isTerminal(call.status)) {
|
||||
this.state.finalizeCall(call.request.callId);
|
||||
}
|
||||
}
|
||||
|
||||
this.state.cancelAllQueued('Operation cancelled');
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -37,6 +37,9 @@ export interface ModelConfigKey {
|
||||
// Indicates whether this request originates from the primary interactive chat model.
|
||||
// Enables the default fallback configuration to `chat-base` when unknown.
|
||||
isChatModel?: boolean;
|
||||
|
||||
// The last stream error that triggered this retry attempt, if any.
|
||||
lastStreamError?: unknown;
|
||||
}
|
||||
|
||||
export interface ModelConfig {
|
||||
|
||||
@@ -173,6 +173,7 @@ describe('UiTelemetryService', () => {
|
||||
totalRequests: 1,
|
||||
totalErrors: 0,
|
||||
totalLatencyMs: 500,
|
||||
errorsByType: {},
|
||||
},
|
||||
tokens: {
|
||||
input: 5,
|
||||
@@ -229,6 +230,7 @@ describe('UiTelemetryService', () => {
|
||||
totalRequests: 2,
|
||||
totalErrors: 0,
|
||||
totalLatencyMs: 1100,
|
||||
errorsByType: {},
|
||||
},
|
||||
tokens: {
|
||||
input: 10,
|
||||
@@ -305,6 +307,9 @@ describe('UiTelemetryService', () => {
|
||||
totalRequests: 1,
|
||||
totalErrors: 1,
|
||||
totalLatencyMs: 300,
|
||||
errorsByType: {
|
||||
UNKNOWN: 1,
|
||||
},
|
||||
},
|
||||
tokens: {
|
||||
input: 0,
|
||||
@@ -319,6 +324,42 @@ describe('UiTelemetryService', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('should track errors by error_type distinctly', () => {
|
||||
const event1 = {
|
||||
'event.name': EVENT_API_ERROR,
|
||||
model: 'gemini-2.5-pro',
|
||||
duration_ms: 200,
|
||||
error: 'Empty response',
|
||||
error_type: 'NO_RESPONSE_TEXT',
|
||||
} as unknown as ApiErrorEvent & { 'event.name': typeof EVENT_API_ERROR };
|
||||
|
||||
const event2 = {
|
||||
'event.name': EVENT_API_ERROR,
|
||||
model: 'gemini-2.5-pro',
|
||||
duration_ms: 250,
|
||||
error: 'Malformed JSON',
|
||||
error_type: 'MALFORMED_FUNCTION_CALL',
|
||||
} as unknown as ApiErrorEvent & { 'event.name': typeof EVENT_API_ERROR };
|
||||
|
||||
const event3 = {
|
||||
'event.name': EVENT_API_ERROR,
|
||||
model: 'gemini-2.5-pro',
|
||||
duration_ms: 100,
|
||||
error: 'Another empty response',
|
||||
error_type: 'NO_RESPONSE_TEXT',
|
||||
} as unknown as ApiErrorEvent & { 'event.name': typeof EVENT_API_ERROR };
|
||||
|
||||
service.addEvent(event1);
|
||||
service.addEvent(event2);
|
||||
service.addEvent(event3);
|
||||
|
||||
const metrics = service.getMetrics();
|
||||
expect(metrics.models['gemini-2.5-pro'].api.errorsByType).toEqual({
|
||||
NO_RESPONSE_TEXT: 2,
|
||||
MALFORMED_FUNCTION_CALL: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('should aggregate ApiErrorEvents and ApiResponseEvents', () => {
|
||||
const responseEvent = {
|
||||
'event.name': EVENT_API_RESPONSE,
|
||||
@@ -351,6 +392,9 @@ describe('UiTelemetryService', () => {
|
||||
totalRequests: 2,
|
||||
totalErrors: 1,
|
||||
totalLatencyMs: 800,
|
||||
errorsByType: {
|
||||
UNKNOWN: 1,
|
||||
},
|
||||
},
|
||||
tokens: {
|
||||
input: 5,
|
||||
|
||||
@@ -56,6 +56,7 @@ export interface ModelMetrics {
|
||||
totalRequests: number;
|
||||
totalErrors: number;
|
||||
totalLatencyMs: number;
|
||||
errorsByType?: Record<string, number>;
|
||||
};
|
||||
tokens: {
|
||||
input: number;
|
||||
@@ -110,6 +111,7 @@ const createInitialModelMetrics = (): ModelMetrics => ({
|
||||
totalRequests: 0,
|
||||
totalErrors: 0,
|
||||
totalLatencyMs: 0,
|
||||
errorsByType: {},
|
||||
},
|
||||
tokens: {
|
||||
input: 0,
|
||||
@@ -170,6 +172,23 @@ export class UiTelemetryService extends EventEmitter {
|
||||
});
|
||||
}
|
||||
|
||||
recordSemanticValidationError(model: string, errorType: string): void {
|
||||
const modelMetrics = this.getOrCreateModelMetrics(model);
|
||||
modelMetrics.api.totalErrors++;
|
||||
|
||||
if (!modelMetrics.api.errorsByType) {
|
||||
modelMetrics.api.errorsByType = {};
|
||||
}
|
||||
const type = errorType || 'INVALID_STREAM';
|
||||
modelMetrics.api.errorsByType[type] =
|
||||
(modelMetrics.api.errorsByType[type] || 0) + 1;
|
||||
|
||||
this.emit('update', {
|
||||
metrics: this.#metrics,
|
||||
lastPromptTokenCount: this.#lastPromptTokenCount,
|
||||
});
|
||||
}
|
||||
|
||||
getMetrics(): SessionMetrics {
|
||||
return this.#metrics;
|
||||
}
|
||||
@@ -326,6 +345,13 @@ export class UiTelemetryService extends EventEmitter {
|
||||
modelMetrics.api.totalErrors++;
|
||||
modelMetrics.api.totalLatencyMs += event.duration_ms;
|
||||
|
||||
if (!modelMetrics.api.errorsByType) {
|
||||
modelMetrics.api.errorsByType = {};
|
||||
}
|
||||
const errorType = event.error_type || 'UNKNOWN';
|
||||
modelMetrics.api.errorsByType[errorType] =
|
||||
(modelMetrics.api.errorsByType[errorType] || 0) + 1;
|
||||
|
||||
if (event.role) {
|
||||
if (!modelMetrics.roles[event.role]) {
|
||||
modelMetrics.roles[event.role] = createInitialRoleMetrics();
|
||||
|
||||
@@ -10,3 +10,24 @@ export const REFERENCE_CONTENT_END = '--- End of content ---';
|
||||
export const DEFAULT_MAX_LINES_TEXT_FILE = 2000;
|
||||
export const MAX_LINE_LENGTH_TEXT_FILE = 2000;
|
||||
export const MAX_FILE_SIZE_MB = 20;
|
||||
|
||||
export const EMPTY_RESPONSE_COMPRESS_SUGGESTION =
|
||||
'The model returned an empty text response. If your context window is near capacity, try using /compress.';
|
||||
|
||||
export const THINKING_ONLY_COMPRESS_SUGGESTION =
|
||||
'The model returned reasoning thoughts but no final response text. If your context window is near capacity, try using /compress.';
|
||||
|
||||
export const MAX_TOKENS_EXCEEDED_SUGGESTION =
|
||||
'Model response was truncated because it exceeded the token limit. Try using /compress to free up context space.';
|
||||
|
||||
export const SAFETY_BLOCKED_MESSAGE =
|
||||
'The model response was blocked due to safety settings.';
|
||||
|
||||
export const RECITATION_BLOCKED_MESSAGE =
|
||||
'The model response was blocked due to recitation/copyright filters.';
|
||||
|
||||
export const OTHER_BLOCKED_MESSAGE =
|
||||
'The model response was blocked due to other policy settings.';
|
||||
|
||||
export const TRUE_EMPTY_RESPONSE_MESSAGE =
|
||||
'The model returned an empty response with no text or thoughts. This may be a transient API issue; please try again.';
|
||||
|
||||
@@ -107,6 +107,63 @@ describe('classifyGoogleError', () => {
|
||||
expect((result as RetryableQuotaError).retryDelayMs).toBe(9000);
|
||||
});
|
||||
|
||||
it('should return TerminalQuotaError for MODEL_CAPACITY_EXHAUSTED when no retry delay is specified', () => {
|
||||
const apiError: GoogleApiError = {
|
||||
code: 429,
|
||||
message:
|
||||
'No capacity available for model gemini-3.1-pro-preview on the server',
|
||||
details: [
|
||||
{
|
||||
'@type': 'type.googleapis.com/google.rpc.ErrorInfo',
|
||||
reason: 'MODEL_CAPACITY_EXHAUSTED',
|
||||
domain: 'cloudcode-pa.googleapis.com',
|
||||
metadata: { model: 'gemini-3.1-pro-preview' },
|
||||
},
|
||||
],
|
||||
};
|
||||
vi.spyOn(errorParser, 'parseGoogleApiError').mockReturnValue(apiError);
|
||||
const result = classifyGoogleError(new Error());
|
||||
expect(result).toBeInstanceOf(TerminalQuotaError);
|
||||
});
|
||||
|
||||
it('should return TerminalQuotaError for MODEL_CAPACITY_EXHAUSTED even when the domain is not a Cloud Code domain (domain-agnostic)', () => {
|
||||
const apiError: GoogleApiError = {
|
||||
code: 429,
|
||||
message:
|
||||
'No capacity available for model gemini-3.1-pro-preview on the server',
|
||||
details: [
|
||||
{
|
||||
'@type': 'type.googleapis.com/google.rpc.ErrorInfo',
|
||||
reason: 'MODEL_CAPACITY_EXHAUSTED',
|
||||
domain: 'other.googleapis.com',
|
||||
metadata: { model: 'gemini-3.1-pro-preview' },
|
||||
},
|
||||
],
|
||||
};
|
||||
vi.spyOn(errorParser, 'parseGoogleApiError').mockReturnValue(apiError);
|
||||
const result = classifyGoogleError(new Error());
|
||||
expect(result).toBeInstanceOf(TerminalQuotaError);
|
||||
});
|
||||
|
||||
it('should return TerminalQuotaError for MODEL_CAPACITY_EXCEEDED when no retry delay is specified', () => {
|
||||
const apiError: GoogleApiError = {
|
||||
code: 429,
|
||||
message:
|
||||
'No capacity available for model gemini-3.1-pro-preview on the server',
|
||||
details: [
|
||||
{
|
||||
'@type': 'type.googleapis.com/google.rpc.ErrorInfo',
|
||||
reason: 'MODEL_CAPACITY_EXCEEDED',
|
||||
domain: 'cloudcode-pa.googleapis.com',
|
||||
metadata: { model: 'gemini-3.1-pro-preview' },
|
||||
},
|
||||
],
|
||||
};
|
||||
vi.spyOn(errorParser, 'parseGoogleApiError').mockReturnValue(apiError);
|
||||
const result = classifyGoogleError(new Error());
|
||||
expect(result).toBeInstanceOf(TerminalQuotaError);
|
||||
});
|
||||
|
||||
it('should return original error if code is not 429, 499 or 503', () => {
|
||||
const apiError: GoogleApiError = {
|
||||
code: 500,
|
||||
|
||||
@@ -330,6 +330,23 @@ export function classifyGoogleError(error: unknown): unknown {
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
errorInfo.reason === 'MODEL_CAPACITY_EXHAUSTED' ||
|
||||
errorInfo.reason === 'MODEL_CAPACITY_EXCEEDED'
|
||||
) {
|
||||
// If no server backoff delay is specified, treat capacity exhaustion as a terminal error
|
||||
// to trigger immediate model fallback without retrying on the same exhausted model.
|
||||
if (delaySeconds === undefined) {
|
||||
return new TerminalQuotaError(
|
||||
googleApiError.message,
|
||||
googleApiError,
|
||||
delaySeconds,
|
||||
errorInfo.reason,
|
||||
);
|
||||
}
|
||||
// Otherwise, fall through to RetryableQuotaError to honor the server's requested delay.
|
||||
}
|
||||
|
||||
// New Cloud Code API quota handling
|
||||
if (errorInfo.domain) {
|
||||
if (isCloudCodeDomain(errorInfo.domain)) {
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2026 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { isFunctionResponse, isFunctionCall } from './messageInspectors.js';
|
||||
|
||||
describe('messageInspectors', () => {
|
||||
describe('isFunctionResponse', () => {
|
||||
it('should return false if content role is not user', () => {
|
||||
const content = {
|
||||
role: 'model',
|
||||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
name: 'test_tool',
|
||||
response: { success: true },
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(isFunctionResponse(content)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if content has no parts', () => {
|
||||
const content = {
|
||||
role: 'user',
|
||||
};
|
||||
expect(isFunctionResponse(content)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if parts are empty', () => {
|
||||
const content = {
|
||||
role: 'user',
|
||||
parts: [],
|
||||
};
|
||||
expect(isFunctionResponse(content)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if none of the parts is a functionResponse', () => {
|
||||
const content = {
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
text: 'Hello world',
|
||||
},
|
||||
{
|
||||
fileData: {
|
||||
mimeType: 'image/png',
|
||||
fileUri: 'https://example.com/image.png',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(isFunctionResponse(content)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return true if all parts are functionResponses', () => {
|
||||
const content = {
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
name: 'test_tool_1',
|
||||
response: { success: true },
|
||||
},
|
||||
},
|
||||
{
|
||||
functionResponse: {
|
||||
name: 'test_tool_2',
|
||||
response: { value: 42 },
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(isFunctionResponse(content)).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true if content is a mixed multimodal tool response containing functionResponse and sibling parts', () => {
|
||||
const content = {
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
name: 'test_tool',
|
||||
response: { success: true },
|
||||
},
|
||||
},
|
||||
{
|
||||
fileData: {
|
||||
mimeType: 'image/png',
|
||||
fileUri: 'https://example.com/image.png',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(isFunctionResponse(content)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isFunctionCall', () => {
|
||||
it('should return false if content role is not model', () => {
|
||||
const content = {
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
functionCall: {
|
||||
name: 'test_tool',
|
||||
args: {},
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(isFunctionCall(content)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if content has no parts', () => {
|
||||
const content = {
|
||||
role: 'model',
|
||||
};
|
||||
expect(isFunctionCall(content)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if parts are empty', () => {
|
||||
const content = {
|
||||
role: 'model',
|
||||
parts: [],
|
||||
};
|
||||
expect(isFunctionCall(content)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if none of the parts is a functionCall', () => {
|
||||
const content = {
|
||||
role: 'model',
|
||||
parts: [
|
||||
{
|
||||
text: 'I am thinking...',
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(isFunctionCall(content)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return true if all parts are functionCalls', () => {
|
||||
const content = {
|
||||
role: 'model',
|
||||
parts: [
|
||||
{
|
||||
functionCall: {
|
||||
name: 'test_tool_1',
|
||||
args: {},
|
||||
},
|
||||
},
|
||||
{
|
||||
functionCall: {
|
||||
name: 'test_tool_2',
|
||||
args: { query: 'foo' },
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(isFunctionCall(content)).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -10,7 +10,7 @@ export function isFunctionResponse(content: Content): boolean {
|
||||
return (
|
||||
content.role === 'user' &&
|
||||
!!content.parts &&
|
||||
content.parts.every((part) => !!part.functionResponse)
|
||||
content.parts.some((part) => !!part.functionResponse)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ export function isFunctionCall(content: Content): boolean {
|
||||
return (
|
||||
content.role === 'model' &&
|
||||
!!content.parts &&
|
||||
content.parts.length > 0 &&
|
||||
content.parts.every((part) => !!part.functionCall)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@google/gemini-cli-devtools",
|
||||
"version": "0.54.0-nightly.20260728.gbef611950",
|
||||
"version": "0.55.0-nightly.20260729.g3499c84f7",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"main": "dist/src/index.js",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@google/gemini-cli-sdk",
|
||||
"version": "0.54.0-nightly.20260728.gbef611950",
|
||||
"version": "0.55.0-nightly.20260729.g3499c84f7",
|
||||
"description": "Gemini CLI SDK",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@google/gemini-cli-test-utils",
|
||||
"version": "0.54.0-nightly.20260728.gbef611950",
|
||||
"version": "0.55.0-nightly.20260729.g3499c84f7",
|
||||
"private": true,
|
||||
"main": "src/index.ts",
|
||||
"license": "Apache-2.0",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "gemini-cli-vscode-ide-companion",
|
||||
"displayName": "Gemini CLI Companion",
|
||||
"description": "Enable Gemini CLI with direct access to your IDE workspace.",
|
||||
"version": "0.54.0-nightly.20260728.gbef611950",
|
||||
"version": "0.55.0-nightly.20260729.g3499c84f7",
|
||||
"publisher": "google",
|
||||
"icon": "assets/icon.png",
|
||||
"repository": {
|
||||
|
||||
Reference in New Issue
Block a user