SPB Git

Repository Public

agent-environment.md 84.3 KB 2,406 lines markdown

1Environments are managed Linux sandboxes that give agents an isolated place to2execute code and persist files. They are decoupled from interaction context, so you can reuse the same environment across multiple interactions or start fresh at any time.34The following example demonstrates how to create an interaction with a fresh5remote environment and retrieve its ID:67### Python89    from google import genai1011    client = genai.Client()1213    interaction = client.interactions.create(14        agent="antigravity-preview-09-2026",15        input="Install pandas and matplotlib, verify the imports, and print the versions.",16        environment="remote",17    )1819    print(f"Environment ID: {interaction.environment_id}")2021### JavaScript2223    import { GoogleGenAI } from "@google/genai";2425    const client = new GoogleGenAI({});2627    const interaction = await client.interactions.create({28        agent: "antigravity-preview-09-2026",29        input: "Install pandas and matplotlib, verify the imports, and print the versions.",30        environment: "remote",31    });3233    console.log(`Environment ID: ${interaction.environment_id}`);3435### Java3637    import com.google.genai.Client;38    import com.google.genai.gaos.models.interactions.AgentOption;39    import com.google.genai.gaos.models.interactions.CreateAgentInteraction;40    import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;41    import com.google.genai.gaos.models.interactions.Interaction;42    import com.google.genai.gaos.models.interactions.InteractionsInput;43    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;4445    Client client = new Client();4647    CreateAgentInteraction params = CreateAgentInteraction.builder()48        .agent(AgentOption.of("antigravity-preview-09-2026"))49        .input(InteractionsInput.of("Install pandas and matplotlib, verify the imports, and print the versions."))50        .environment(CreateAgentInteractionEnvironment.of("remote"))51        .build();5253    Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();54    System.out.println("Environment ID: " + interaction.environmentId().orElse(""));5556### REST5758    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \59    -H "Content-Type: application/json" \60    -H "x-goog-api-key: $GEMINI_API_KEY" \61    -d '{62        "agent": "antigravity-preview-09-2026",63        "input": "Install pandas and matplotlib, verify the imports, and print the versions.",64        "environment": "remote"65    }'6667## The `environment` parameter6869The `environment` parameter accepts three forms:7071| Form | Example | When to use |72|---|---|---|73| `"remote"` | `environment="remote"` | Provision a fresh sandbox. |74| Environment ID | `environment="env_abc123"` | Reuse an existing sandbox with all its files and packages. |75| Config object | `environment={...}` | Provision a new sandbox with sources, network rules, environment variables, or a combination. |7677The following examples demonstrate the three ways of using the `environment`78parameter.7980### Python8182    from google import genai8384    client = genai.Client()8586    # Fresh sandbox87    interaction = client.interactions.create(88        agent="antigravity-preview-09-2026",89        input="Write a hello world script.",90        environment="remote",91    )9293    # Reuse an existing sandbox94    interaction_2 = client.interactions.create(95        agent="antigravity-preview-09-2026",96        input="Modify the script to accept a name argument.",97        environment=interaction.environment_id,98        previous_interaction_id=interaction.id,99    )100101    # New sandbox with sources102    interaction_3 = client.interactions.create(103        agent="antigravity-preview-09-2026",104        input="List all files and summarize the project.",105        environment={106            "type": "remote",107            "sources": [108                {109                    "type": "repository",110                    "source": "https://github.com/octocat/Spoon-Knife",111                    "target": "/workspace/spoon-knife",112                }113            ],114        },115    )116117    print(interaction.output_text)118119### JavaScript120121    import { GoogleGenAI } from "@google/genai";122123    const client = new GoogleGenAI({});124125    // Fresh sandbox126    const interaction = await client.interactions.create({127        agent: "antigravity-preview-09-2026",128        input: "Write a hello world script.",129        environment: "remote",130    });131132    // Reuse an existing sandbox133    const interaction2 = await client.interactions.create({134        agent: "antigravity-preview-09-2026",135        input: "Modify the script to accept a name argument.",136        environment: interaction.environment_id,137        previous_interaction_id: interaction.id,138    });139140    // New sandbox with sources141    const interaction3 = await client.interactions.create({142        agent: "antigravity-preview-09-2026",143        input: "List all files and summarize the project.",144        environment: {145            type: "remote",146            sources: [147                {148                    type: "repository",149                    source: "https://github.com/octocat/Spoon-Knife",150                    target: "/workspace/spoon-knife",151                },152            ],153        },154    });155156    console.log(interaction.output_text);157158### Java159160    import com.google.genai.Client;161    import com.google.genai.gaos.models.interactions.AgentOption;162    import com.google.genai.gaos.models.interactions.CreateAgentInteraction;163    import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;164    import com.google.genai.gaos.models.interactions.Environment;165    import com.google.genai.gaos.models.interactions.Interaction;166    import com.google.genai.gaos.models.interactions.InteractionsInput;167    import com.google.genai.gaos.models.interactions.Source;168    import com.google.genai.gaos.models.interactions.SourceType;169    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;170    import java.util.List;171172    Client client = new Client();173174    // Fresh sandbox175    CreateAgentInteraction params1 = CreateAgentInteraction.builder()176        .agent(AgentOption.of("antigravity-preview-09-2026"))177        .input(InteractionsInput.of("Write a hello world script."))178        .environment(CreateAgentInteractionEnvironment.of("remote"))179        .build();180    Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params1)).interaction().get();181182    // Reuse an existing sandbox183    CreateAgentInteraction params2 = CreateAgentInteraction.builder()184        .agent(AgentOption.of("antigravity-preview-09-2026"))185        .input(InteractionsInput.of("Modify the script to accept a name argument."))186        .environment(CreateAgentInteractionEnvironment.of(interaction.environmentId().orElse("")))187        .previousInteractionId(interaction.id().orElse(""))188        .build();189    Interaction interaction2 = client.interactions.create(CreateInteractionRequestBody.of(params2)).interaction().get();190191    // New sandbox with sources192    Environment env3 = Environment.builder()193        .sources(List.of(194            Source.builder()195                .type(SourceType.REPOSITORY)196                .source("https://github.com/octocat/Spoon-Knife")197                .target("/workspace/spoon-knife")198                .build()199        ))200        .build();201202    CreateAgentInteraction params3 = CreateAgentInteraction.builder()203        .agent(AgentOption.of("antigravity-preview-09-2026"))204        .input(InteractionsInput.of("List all files and summarize the project."))205        .environment(CreateAgentInteractionEnvironment.of(env3))206        .build();207    Interaction interaction3 = client.interactions.create(CreateInteractionRequestBody.of(params3)).interaction().get();208209    System.out.println(interaction.outputText().orElse(""));210211### REST212213    # Fresh sandbox214    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \215    -H "Content-Type: application/json" \216    -H "x-goog-api-key: $GEMINI_API_KEY" \217    -d '{218        "agent": "antigravity-preview-09-2026",219        "input": [{"type": "text", "text": "Write a hello world script."}],220        "environment": "remote"221    }'222223    # Reuse an existing sandbox (replace $ENV_ID and $INTERACTION_ID with values from the previous response)224    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \225    -H "Content-Type: application/json" \226    -H "x-goog-api-key: $GEMINI_API_KEY" \227    -d "{228        \"agent\": \"antigravity-preview-09-2026\",229        \"input\": [{\"type\": \"text\", \"text\": \"Modify the script to accept a name argument.\"}],230        \"environment\": \"$ENV_ID\",231        \"previous_interaction_id\": \"$INTERACTION_ID\"232    }"233234    # New sandbox with sources235    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \236    -H "Content-Type: application/json" \237    -H "x-goog-api-key: $GEMINI_API_KEY" \238    -d '{239        "agent": "antigravity-preview-09-2026",240        "input": [{"type": "text", "text": "List all files and summarize the project."}],241        "environment": {242            "type": "remote",243            "sources": [244                {245                    "type": "repository",246                    "source": "https://github.com/octocat/Spoon-Knife",247                    "target": "/workspace/spoon-knife"248                }249            ]250        }251    }'252253## Configure an environment254255One way to set up an environment is to tell the agent what you need installed.256It handles dependency resolution and troubleshooting. Once the environment is257ready, save the `environment_id` and reuse it.258259### Python260261    from google import genai262263    client = genai.Client()264265    interaction = client.interactions.create(266        agent="antigravity-preview-09-2026",267        input="Install pandas, matplotlib, and seaborn. Verify all imports work and print the installed versions.",268        environment="remote",269    )270271    # Reuse the configured environment272    interaction_2 = client.interactions.create(273        agent="antigravity-preview-09-2026",274        input="Clone https://github.com/octocat/Spoon-Knife into /workspace/tools. Run the test suite and fix any missing dependencies.",275        environment=interaction.environment_id,276        previous_interaction_id=interaction.id,277    )278279    # Reuse the configured environment280    interaction_3 = client.interactions.create(281        agent="antigravity-preview-09-2026",282        input="Using the tools in /workspace/tools, list the files.",283        environment=interaction.environment_id,284        previous_interaction_id=interaction_2.id,285    )286287    print(interaction.output_text)288289### JavaScript290291    import { GoogleGenAI } from "@google/genai";292293    const client = new GoogleGenAI({});294295    const interaction = await client.interactions.create({296        agent: "antigravity-preview-09-2026",297        input: "Install pandas, matplotlib, and seaborn. Verify all imports work and print the installed versions.",298        environment: "remote",299    });300301    const interaction2 = await client.interactions.create({302        agent: "antigravity-preview-09-2026",303        input: "Clone https://github.com/octocat/Spoon-Knife into /workspace/tools. Run the test suite and fix any missing dependencies.",304        environment: interaction.environment_id,305        previous_interaction_id: interaction.id,306    });307308    const interaction3 = await client.interactions.create({309        agent: "antigravity-preview-09-2026",310        input: "Using the tools in /workspace/tools, list the files.",311        environment: interaction.environment_id,312        previous_interaction_id: interaction2.id,313    });314    console.log(interaction.output_text);315316### Java317318    import com.google.genai.Client;319    import com.google.genai.gaos.models.interactions.AgentOption;320    import com.google.genai.gaos.models.interactions.CreateAgentInteraction;321    import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;322    import com.google.genai.gaos.models.interactions.Interaction;323    import com.google.genai.gaos.models.interactions.InteractionsInput;324    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;325326    Client client = new Client();327328    CreateAgentInteraction params1 = CreateAgentInteraction.builder()329        .agent(AgentOption.of("antigravity-preview-09-2026"))330        .input(InteractionsInput.of("Install pandas, matplotlib, and seaborn. Verify all imports work and print the installed versions."))331        .environment(CreateAgentInteractionEnvironment.of("remote"))332        .build();333    Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params1)).interaction().get();334335    // Reuse the configured environment336    CreateAgentInteraction params2 = CreateAgentInteraction.builder()337        .agent(AgentOption.of("antigravity-preview-09-2026"))338        .input(InteractionsInput.of("Clone https://github.com/octocat/Spoon-Knife into /workspace/tools. Run the test suite and fix any missing dependencies."))339        .environment(CreateAgentInteractionEnvironment.of(interaction.environmentId().orElse("")))340        .previousInteractionId(interaction.id().orElse(""))341        .build();342    Interaction interaction2 = client.interactions.create(CreateInteractionRequestBody.of(params2)).interaction().get();343344    // Reuse the configured environment345    CreateAgentInteraction params3 = CreateAgentInteraction.builder()346        .agent(AgentOption.of("antigravity-preview-09-2026"))347        .input(InteractionsInput.of("Using the tools in /workspace/tools, list the files."))348        .environment(CreateAgentInteractionEnvironment.of(interaction.environmentId().orElse("")))349        .previousInteractionId(interaction2.id().orElse(""))350        .build();351    Interaction interaction3 = client.interactions.create(CreateInteractionRequestBody.of(params3)).interaction().get();352353    System.out.println(interaction.outputText().orElse(""));354355### REST356357    # Create interaction358    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \359    -H "Content-Type: application/json" \360    -H "x-goog-api-key: $GEMINI_API_KEY" \361    -d '{362        "agent": "antigravity-preview-09-2026",363        "input": "Install pandas, matplotlib, and seaborn. Verify all imports work and print the installed versions.",364        "environment": "remote"365    }'366367### Mount from a source368369If you know exactly what files the agent needs, mount them in a single call370instead of iterating. The `environment` config object accepts a `sources` array371with three types:372373| Source type | `type` value | Description | Limit |374|---|---|---|---|375| Git repository | `repository` | Clones a repository from a URL into the sandbox at `target`. | 500 MB |376| Cloud Storage | `gcs` | Copies a file or directory from Cloud Storage into the sandbox at `target`. | 2 GB |377| Inline content | `inline` | Writes raw text content to a file in the sandbox at `target`. | 1 MB per file, 2 MB total |378379### Python380381    from google import genai382383    client = genai.Client()384385    interaction = client.interactions.create(386        agent="antigravity-preview-09-2026",387        input="List all files under /workspace and describe what you find.",388        environment={389            "type": "remote",390            "sources": [391                {392                    "type": "repository",393                    "source": "https://github.com/octocat/Spoon-Knife",394                    "target": "/workspace/spoon-knife",395                },396                {397                    "type": "gcs",398                    "source": "gs://cloud-samples-data/bigquery/us-states/",399                    "target": "/workspace/gcs-data",400                },401                {402                    "type": "inline",403                    "content": "# Project Notes\n\n- Analyze state population data\n- Create visualizations\n",404                    "target": "/workspace/notes/readme.md",405                },406            ],407        },408    )409410    print(interaction.output_text)411412### JavaScript413414    import { GoogleGenAI } from "@google/genai";415416    const client = new GoogleGenAI({});417418    const interaction = await client.interactions.create({419        agent: "antigravity-preview-09-2026",420        input: "List all files under /workspace and describe what you find.",421        environment: {422            type: "remote",423            sources: [424                {425                    type: "repository",426                    source: "https://github.com/octocat/Spoon-Knife",427                    target: "/workspace/spoon-knife",428                },429                {430                    type: "gcs",431                    source: "gs://cloud-samples-data/bigquery/us-states/",432                    target: "/workspace/gcs-data",433                },434                {435                    type: "inline",436                    content: "# Project Notes\n\n- Analyze state population data\n- Create visualizations\n",437                    target: "/workspace/notes/readme.md",438                },439            ],440        },441    });442443    console.log(interaction.output_text);444445### Java446447    import com.google.genai.Client;448    import com.google.genai.gaos.models.interactions.AgentOption;449    import com.google.genai.gaos.models.interactions.CreateAgentInteraction;450    import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;451    import com.google.genai.gaos.models.interactions.Environment;452    import com.google.genai.gaos.models.interactions.Interaction;453    import com.google.genai.gaos.models.interactions.InteractionsInput;454    import com.google.genai.gaos.models.interactions.Source;455    import com.google.genai.gaos.models.interactions.SourceType;456    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;457    import java.util.List;458459    Client client = new Client();460461    Environment env = Environment.builder()462        .sources(List.of(463            Source.builder()464                .type(SourceType.REPOSITORY)465                .source("https://github.com/octocat/Spoon-Knife")466                .target("/workspace/spoon-knife")467                .build(),468            Source.builder()469                .type(SourceType.GCS)470                .source("gs://cloud-samples-data/bigquery/us-states/")471                .target("/workspace/gcs-data")472                .build(),473            Source.builder()474                .type(SourceType.INLINE)475                .content("# Project Notes\n\n- Analyze state population data\n- Create visualizations\n")476                .target("/workspace/notes/readme.md")477                .build()478        ))479        .build();480481    CreateAgentInteraction params = CreateAgentInteraction.builder()482        .agent(AgentOption.of("antigravity-preview-09-2026"))483        .input(InteractionsInput.of("List all files under /workspace and describe what you find."))484        .environment(CreateAgentInteractionEnvironment.of(env))485        .build();486487    Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();488    System.out.println(interaction.outputText().orElse(""));489490### REST491492    # Create interaction with sources493    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \494    -H "Content-Type: application/json" \495    -H "x-goog-api-key: $GEMINI_API_KEY" \496    -d '{497        "agent": "antigravity-preview-09-2026",498        "input": "List all files under /workspace and describe what you find.",499        "environment": {500            "type": "remote",501            "sources": [502                {503                    "type": "repository",504                    "source": "https://github.com/octocat/Spoon-Knife",505                    "target": "/workspace/spoon-knife"506                },507                {508                    "type": "gcs",509                    "source": "gs://cloud-samples-data/bigquery/us-states/",510                    "target": "/workspace/gcs-data"511                },512                {513                    "type": "inline",514                    "content": "# Project Notes\n\n- Analyze state population data\n- Create visualizations\n",515                    "target": "/workspace/notes/readme.md"516                }517            ]518        }519    }'520521You can combine both approaches: mount known sources declaratively, then iterate522with follow-up interactions to install packages or run setup scripts. You can't523set root (`/`) as target when adding a custom source, you must always specify a524sub-directory.525526### Hooks527528You can also mount a `.agents/hooks.json` configuration file and custom interception scripts into the sandbox to enforce security guardrails or run automated validations whenever tools execute. For schema definitions and code examples, see [Hooks](https://ai.google.dev/gemini-api/docs/agent-hooks).529530### Private sources531532You can also download from private GitHub repositories or private Cloud533Storage buckets by authenticating the source domain in the network534configuration.535536One option is a stored [credential](https://ai.google.dev/gemini-api/docs/agent-credentials)537referenced by ID, so you store the secret once and every environment that needs538that source can reference it:539540    "network": {541        "allowlist": [542            { "domain": "github.com", "credential": "github-production" },543            { "domain": "*" }544        ]545    }546547You can also set the header inline with `transform`, as the following examples548do. The egress proxy applies both forms the same way, and in neither case does549the secret land inside the sandbox.550551For **private Git repositories** , use `Basic` authentication with your552[GitHub Personal Access Token553(PAT)](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens).554Encode the token using `x-oauth-basic` as the username:555556    echo -n "x-oauth-basic:ghp_YourPATHere" | base64557558### Python559560    interaction = client.interactions.create(561        agent="antigravity-preview-09-2026",562        input="Run the test for my backend app and fix any issue.",563        environment={564            "type": "remote",565            "sources": [566                {567                    "type": "repository",568                    "source": "https://github.com/your-org/backend",569                    "target": "/backend-app"570                }571            ],572            "network": {573                "allowlist": [574                    {575                        "domain": "github.com",576                        "transform": {577                            "Authorization": "Basic YOUR_BASE64_TOKEN"578                        }579                    },580                    {581                        "domain": "*"582                    }583                ]584            }585        }586    )587588### JavaScript589590    const interaction = await client.interactions.create({591        agent: "antigravity-preview-09-2026",592        input: "Run the test for my backend app and fix any issue.",593        environment: {594            type: "remote",595            sources: [596                {597                    type: "repository",598                    source: "https://github.com/your-org/backend",599                    target: "/backend-app"600                }601            ],602            network: {603                allowlist: [604                    {605                        domain: "github.com",606                        transform: {607                            "Authorization": "Basic YOUR_BASE64_TOKEN"608                        }609                    },610                    {611                        domain: "*"612                    }613                ]614            }615        },616    });617618### Java619620    import com.google.genai.Client;621    import com.google.genai.gaos.models.interactions.AgentOption;622    import com.google.genai.gaos.models.interactions.Allowlist;623    import com.google.genai.gaos.models.interactions.AllowlistEntry;624    import com.google.genai.gaos.models.interactions.CreateAgentInteraction;625    import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;626    import com.google.genai.gaos.models.interactions.Environment;627    import com.google.genai.gaos.models.interactions.EnvironmentNetworkEgressAllowlist;628    import com.google.genai.gaos.models.interactions.Interaction;629    import com.google.genai.gaos.models.interactions.InteractionsInput;630    import com.google.genai.gaos.models.interactions.Network;631    import com.google.genai.gaos.models.interactions.Source;632    import com.google.genai.gaos.models.interactions.SourceType;633    import com.google.genai.gaos.models.interactions.Transform;634    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;635    import java.util.List;636    import java.util.Map;637638    Client client = new Client();639640    Environment env = Environment.builder()641        .sources(List.of(642            Source.builder()643                .type(SourceType.REPOSITORY)644                .source("https://github.com/your-org/backend")645                .target("/backend-app")646                .build()647        ))648        .network(Network.of(EnvironmentNetworkEgressAllowlist.of(649            Allowlist.builder()650                .allowlist(List.of(651                    AllowlistEntry.builder()652                        .domain("github.com")653                        .transform(Transform.of(Map.of(654                            "Authorization", "Basic YOUR_BASE64_TOKEN"655                        )))656                        .build(),657                    AllowlistEntry.builder()658                        .domain("*")659                        .build()660                ))661                .build()662        )))663        .build();664665    CreateAgentInteraction params = CreateAgentInteraction.builder()666        .agent(AgentOption.of("antigravity-preview-09-2026"))667        .input(InteractionsInput.of("Run the test for my backend app and fix any issue."))668        .environment(CreateAgentInteractionEnvironment.of(env))669        .build();670671    Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();672    System.out.println(interaction.outputText().orElse(""));673674### REST675676    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \677    -H "Content-Type: application/json" \678    -H "x-goog-api-key: $GEMINI_API_KEY" \679    -d '{680        "agent": "antigravity-preview-09-2026",681        "input": "Run the test for my backend app and fix any issue.",682        "environment": {683            "type": "remote",684            "sources": [685                {686                    "type": "repository",687                    "source": "https://github.com/your-org/backend",688                    "target": "/backend-app"689                }690            ],691            "network": {692                "allowlist": [693                    {694                        "domain": "github.com",695                        "transform": {696                            "Authorization": "Basic YOUR_BASE64_TOKEN"697                        }698                    },699                    {700                        "domain": "*"701                    }702                ]703            }704        }705    }'706707For **private Cloud Storage buckets**, use a standard OAuth 2.0 Bearer token:708709    gcloud auth print-access-token710711### Python712713    interaction = client.interactions.create(714        agent="antigravity-preview-09-2026",715        input="Analyze the discrepancies across the data in workspace",716        environment={717            "type": "remote",718            "sources": [719                {720                    "type": "gcs",721                    "source": "gs://my-private-bucket/data",722                    "target": "/workspace",723                }724            ],725            "network": {726                "allowlist": [727                    {728                        "domain": "*.googleapis.com",729                        "transform": {730                            "Authorization": "Bearer YOUR_GCS_TOKEN"731                        }732                    },733                    {734                        "domain": "*"735                    }736                ]737            }738        },739    )740741### JavaScript742743    const interaction = await client.interactions.create({744        agent: "antigravity-preview-09-2026",745        input: "Analyze the discrepancies across the data in workspace",746        environment: {747            type: "remote",748            sources: [749                {750                    type: "gcs",751                    source: "gs://my-private-bucket/data",752                    target: "/workspace",753                }754            ],755            network: {756                allowlist: [757                    {758                        domain: "storage.googleapis.com",759                        transform: {760                            "Authorization": "Bearer YOUR_GCS_TOKEN"761                        }762                    },763                    {764                        domain: "*"765                    }766                ]767            }768        },769    });770771### Java772773    import com.google.genai.Client;774    import com.google.genai.gaos.models.interactions.AgentOption;775    import com.google.genai.gaos.models.interactions.Allowlist;776    import com.google.genai.gaos.models.interactions.AllowlistEntry;777    import com.google.genai.gaos.models.interactions.CreateAgentInteraction;778    import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;779    import com.google.genai.gaos.models.interactions.Environment;780    import com.google.genai.gaos.models.interactions.EnvironmentNetworkEgressAllowlist;781    import com.google.genai.gaos.models.interactions.Interaction;782    import com.google.genai.gaos.models.interactions.InteractionsInput;783    import com.google.genai.gaos.models.interactions.Network;784    import com.google.genai.gaos.models.interactions.Source;785    import com.google.genai.gaos.models.interactions.SourceType;786    import com.google.genai.gaos.models.interactions.Transform;787    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;788    import java.util.List;789    import java.util.Map;790791    Client client = new Client();792793    Environment env = Environment.builder()794        .sources(List.of(795            Source.builder()796                .type(SourceType.GCS)797                .source("gs://my-private-bucket/data")798                .target("/workspace")799                .build()800        ))801        .network(Network.of(EnvironmentNetworkEgressAllowlist.of(802            Allowlist.builder()803                .allowlist(List.of(804                    AllowlistEntry.builder()805                        .domain("*.googleapis.com")806                        .transform(Transform.of(Map.of(807                            "Authorization", "Bearer YOUR_GCS_TOKEN"808                        )))809                        .build(),810                    AllowlistEntry.builder()811                        .domain("*")812                        .build()813                ))814                .build()815        )))816        .build();817818    CreateAgentInteraction params = CreateAgentInteraction.builder()819        .agent(AgentOption.of("antigravity-preview-09-2026"))820        .input(InteractionsInput.of("Analyze the discrepancies across the data in workspace"))821        .environment(CreateAgentInteractionEnvironment.of(env))822        .build();823824    Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();825    System.out.println(interaction.outputText().orElse(""));826827### REST828829    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \830    -H "Content-Type: application/json" \831    -H "x-goog-api-key: $GEMINI_API_KEY" \832    -d '{833        "agent": "antigravity-preview-09-2026",834        "input": "Analyze the discrepancies across the data in workspace",835        "environment": {836            "type": "remote",837            "sources": [838                {839                    "type": "gcs",840                    "source": "gs://my-private-bucket/data",841                    "target": "/workspace"842                }843            ],844            "network": {845                "allowlist": [846                    {847                        "domain": "storage.googleapis.com",848                        "transform": {849                            "Authorization": "Bearer YOUR_GCS_TOKEN"850                        }851                    },852                    {853                        "domain": "*"854                    }855                ]856            }857        }858    }'859860## Pre-installed software861862The sandbox runs on Ubuntu and comes with runtimes and common packages863pre-installed. The agent can install additional packages at runtime using `pip864install` or `npm install`. Packages installed during an interaction persist when865you reuse the same `environment_id`.866867| Category | Pre-installed packages |868|---|---|869| **UNIX tools** | `curl`, `wget`, `git`, `rsync`, `unzip`, `ripgrep`, `fd-find`, `gawk`, `bc`, `tree`, `which`, `lsof`, `htop`, `jq`, `iproute2`, `procps`, `gcloud CLI` |870| **Python 3.12** | `numpy`, `pandas`, `requests`, `google-genai`, `beautifulsoup4`, `pyyaml`, `ast-grep-cli` |871| **Node.js 22** | `create-next-app`, `create-vite`, `typescript` |872873## Environment variables874875Use the `env` field to set environment variables inside the sandbox. Each entry876maps a variable name to either a literal string for configuration or a877reference to a stored [credential](https://ai.google.dev/gemini-api/docs/agent-credentials) for a878secret. The agent sees them the way it would in any shell, so tools and scripts879that read from the process environment pick them up without extra wiring.880881| Field | Type | Description |882|---|---|---|883| `env` | `object` | Map of variable name to value. A value is either a literal `string` or a credential reference of the form `{"credential": "credential-id"}`. |884885### Python886887    from google import genai888889    client = genai.Client()890891    interaction = client.interactions.create(892        agent="antigravity-preview-09-2026",893        input="Build the project and run the test suite.",894        environment={895            "type": "remote",896            "env": {897                "NODE_ENV": "production",898                "LOG_LEVEL": "debug",899                "API_TOKEN": {"credential": "my-api-token"},900            },901        },902    )903904    print(interaction.output_text)905906### JavaScript907908    import { GoogleGenAI } from "@google/genai";909910    const client = new GoogleGenAI({});911912    const interaction = await client.interactions.create({913        agent: "antigravity-preview-09-2026",914        input: "Build the project and run the test suite.",915        environment: {916            type: "remote",917            env: {918                NODE_ENV: "production",919                LOG_LEVEL: "debug",920                API_TOKEN: { credential: "my-api-token" },921            },922        },923    });924925    console.log(interaction.output_text);926927### REST928929    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \930    -H "Content-Type: application/json" \931    -H "x-goog-api-key: $GEMINI_API_KEY" \932    -d '{933        "agent": "antigravity-preview-09-2026",934        "input": [{"type": "text", "text": "Build the project and run the test suite."}],935        "environment": {936            "type": "remote",937            "env": {938                "NODE_ENV": "production",939                "LOG_LEVEL": "debug",940                "API_TOKEN": {"credential": "my-api-token"}941            }942        }943    }'944945Variables apply to every command the agent runs in that interaction, including946shell commands, build steps, and any process it starts.947948The two value types behave differently. A literal string is written into the949container as plain text. A credential reference is not: the variable receives a950placeholder, and the egress proxy substitutes the real secret only on outbound951requests to that credential's trusted domains. See952[Use credentials as environment variables](https://ai.google.dev/gemini-api/docs/agent-credentials#environment-variables)953for how that works.954955> [!CAUTION]956> **Caution:** Literal values are readable by anything running in the sandbox, including the agent itself. Use them for configuration like `NODE_ENV`, not for secrets. Every secret belongs in a credential.957958## Network configuration959960By default, environments have unrestricted outbound network access. Use the961`network` field to restrict outbound traffic to specific domains. Each rule962specifies a `domain`, plus an optional `credential` to inject a stored secret963and an optional `transform` object to inject headers into matching requests.964These headers can be unique per interaction, and you can update them for the same environment.965966| Field | Type | Description |967|---|---|---|968| `domain` | `string` | Domain to match. Use an exact hostname or `*` for all domains. |969| `credential` | `string` | ID of a stored [credential](https://ai.google.dev/gemini-api/docs/agent-credentials). The egress proxy resolves it and injects the auth header at request time. |970| `transform` | `object` | Object containing flat key-value pairs representing headers to inject into matching requests, e.g. `{"Authorization": "Bearer ..."}`. |971972### Python973974    from google import genai975976    client = genai.Client()977978    interaction = client.interactions.create(979        agent="antigravity-preview-09-2026",980        input="Fetch the latest issues from the GitHub API for my-org/my-repo.",981        environment={982            "type": "remote",983            "network": {984                "allowlist": [985                    {986                        "domain": "api.github.com",987                        "transform": {988                            "Authorization": "Bearer ghp_your_github_token"989                        },990                    },991                    {"domain": "pypi.org"},992                    {"domain": "*"},993                ]994            },995        },996    )997998    print(interaction.output_text)9991000### JavaScript10011002    import { GoogleGenAI } from "@google/genai";10031004    const client = new GoogleGenAI({});10051006    const interaction = await client.interactions.create({1007        agent: "antigravity-preview-09-2026",1008        input: "Fetch the latest issues from the GitHub API for my-org/my-repo.",1009        environment: {1010            type: "remote",1011            network: {1012                allowlist: [1013                    {1014                        domain: "api.github.com",1015                        transform: {1016                            "Authorization": "Bearer ghp_your_github_token"1017                        },1018                    },1019                    { domain: "pypi.org" },1020                    { domain: "*" },1021                ]1022            }1023        },1024    });10251026    console.log(interaction.output_text);10271028### Java10291030    import com.google.genai.Client;1031    import com.google.genai.gaos.models.interactions.AgentOption;1032    import com.google.genai.gaos.models.interactions.Allowlist;1033    import com.google.genai.gaos.models.interactions.AllowlistEntry;1034    import com.google.genai.gaos.models.interactions.CreateAgentInteraction;1035    import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;1036    import com.google.genai.gaos.models.interactions.Environment;1037    import com.google.genai.gaos.models.interactions.EnvironmentNetworkEgressAllowlist;1038    import com.google.genai.gaos.models.interactions.Interaction;1039    import com.google.genai.gaos.models.interactions.InteractionsInput;1040    import com.google.genai.gaos.models.interactions.Network;1041    import com.google.genai.gaos.models.interactions.Transform;1042    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;1043    import java.util.List;1044    import java.util.Map;10451046    Client client = new Client();10471048    Environment env = Environment.builder()1049        .network(Network.of(EnvironmentNetworkEgressAllowlist.of(1050            Allowlist.builder()1051                .allowlist(List.of(1052                    AllowlistEntry.builder()1053                        .domain("api.github.com")1054                        .transform(Transform.of(Map.of(1055                            "Authorization", "Bearer ghp_your_github_token"1056                        )))1057                        .build(),1058                    AllowlistEntry.builder().domain("pypi.org").build(),1059                    AllowlistEntry.builder().domain("*").build()1060                ))1061                .build()1062        )))1063        .build();10641065    CreateAgentInteraction params = CreateAgentInteraction.builder()1066        .agent(AgentOption.of("antigravity-preview-09-2026"))1067        .input(InteractionsInput.of("Fetch the latest issues from the GitHub API for my-org/my-repo."))1068        .environment(CreateAgentInteractionEnvironment.of(env))1069        .build();10701071    Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();1072    System.out.println(interaction.outputText().orElse(""));10731074### REST10751076    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \1077    -H "Content-Type: application/json" \1078    -H "x-goog-api-key: $GEMINI_API_KEY" \1079    -d '{1080        "agent": "antigravity-preview-09-2026",1081        "input": [{"type": "text", "text": "Fetch the latest issues from the GitHub API for my-org/my-repo."}],1082        "environment": {1083            "type": "remote",1084            "network": {1085                "allowlist": [1086                    {1087                        "domain": "api.github.com",1088                        "transform": {1089                            "Authorization": "Bearer ghp_your_github_token"1090                        }1091                    },1092                    {"domain": "pypi.org"},1093                    {"domain": "*"}1094                ]1095            }1096        }1097    }'10981099When an allowlist is set, only requests to explicitly listed domains are1100permitted. You can use wildcards to match subdomains (e.g., `{"domain":1101"*.example.com"}`), but note that this does not match the root domain1102`example.com`, which must be added separately. To permit all other traffic, such1103as routing unlisted domains without injected headers, add `{"domain": "*"}` as a1104catch-all entry.11051106### Credentials11071108There are two ways to authenticate outbound traffic, a stored credential1109referenced by ID and an inline `transform` on the allowlist rule. The egress1110proxy applies both on the wire, so in both cases the secret never enters the1111sandbox and never appears in your interaction payloads.11121113A [managed credential](https://ai.google.dev/gemini-api/docs/agent-credentials) is the one to reach1114for when you want to store the secret once and reuse it. Every environment,1115agent, and trigger in your project can reference the same ID, and you rotate it1116in one place.11171118### Python11191120    from google import genai11211122    client = genai.Client()11231124    # Store the secret once1125    client.credentials.create(1126        id="github-production",1127        type="bearer_token",1128        token="ghp_your_github_token",1129    )11301131    interaction = client.interactions.create(1132        agent="antigravity-preview-09-2026",1133        input="Fetch the latest issues from the GitHub API for my-org/my-repo.",1134        environment={1135            "type": "remote",1136            "network": {1137                "allowlist": [1138                    {"domain": "api.github.com", "credential": "github-production"},1139                    {"domain": "*"},1140                ]1141            },1142        },1143    )11441145    print(interaction.output_text)11461147### JavaScript11481149    import { GoogleGenAI } from "@google/genai";11501151    const client = new GoogleGenAI({});11521153    // Store the secret once1154    await client.credentials.create({1155        id: "github-production",1156        type: "bearer_token",1157        token: "ghp_your_github_token",1158    });11591160    const interaction = await client.interactions.create({1161        agent: "antigravity-preview-09-2026",1162        input: "Fetch the latest issues from the GitHub API for my-org/my-repo.",1163        environment: {1164            type: "remote",1165            network: {1166                allowlist: [1167                    { domain: "api.github.com", credential: "github-production" },1168                    { domain: "*" },1169                ]1170            }1171        },1172    });11731174    console.log(interaction.output_text);11751176### REST11771178    # Store the secret once1179    curl -X POST "https://generativelanguage.googleapis.com/v1beta/credentials" \1180    -H "Content-Type: application/json" \1181    -H "x-goog-api-key: $GEMINI_API_KEY" \1182    -d '{1183        "id": "github-production",1184        "type": "bearer_token",1185        "token": "ghp_your_github_token"1186    }'11871188    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \1189    -H "Content-Type: application/json" \1190    -H "x-goog-api-key: $GEMINI_API_KEY" \1191    -d '{1192        "agent": "antigravity-preview-09-2026",1193        "input": "Fetch the latest issues from the GitHub API for my-org/my-repo.",1194        "environment": {1195            "type": "remote",1196            "network": {1197                "allowlist": [1198                    { "domain": "api.github.com", "credential": "github-production" },1199                    { "domain": "*" }1200                ]1201            }1202        }1203    }'12041205An `oauth2` credential also refreshes its access token on its own, so a1206long-running interaction does not break when the token expires. See1207[Credentials](https://ai.google.dev/gemini-api/docs/agent-credentials) for the full list of1208credential types and management operations.12091210You can also set headers inline with `transform`. This fits when the value1211belongs to a single call, for example a token you generate right before creating1212the interaction. Headers set this way are injected by the same egress proxy,1213they are never exposed inside the sandbox as environment variables or files.12141215### Python12161217    import subprocess1218    from google import genai12191220    # Fetch a short-lived access token from your local gcloud CLI1221    gcloud_token = subprocess.check_output(1222        ["gcloud", "auth", "print-access-token"], text=True1223    ).strip()12241225    client = genai.Client()12261227    interaction = client.interactions.create(1228        agent="antigravity-preview-09-2026",1229        input="List the files in gs://my-bucket/reports/ using the GCS JSON API.",1230        environment={1231            "type": "remote",1232            "network": {1233                "allowlist": [1234                    {1235                        "domain": "storage.googleapis.com",1236                        "transform": {1237                            "Authorization": f"Bearer {gcloud_token}"1238                        },1239                    }1240                ]1241            },1242        },1243    )12441245    print(interaction.output_text)12461247### JavaScript12481249    import { GoogleGenAI } from "@google/genai";12501251    import { execSync } from "child_process";12521253    const gcloudToken = execSync("gcloud auth print-access-token").toString().trim();12541255    const client = new GoogleGenAI({});12561257    const interaction = await client.interactions.create({1258        agent: "antigravity-preview-09-2026",1259        input: "List the files in gs://my-bucket/reports/ using the GCS JSON API.",1260        environment: {1261            type: "remote",1262            network: {1263                allowlist: [1264                    {1265                        domain: "storage.googleapis.com",1266                        transform: {1267                            "Authorization": `Bearer ${gcloudToken}`1268                        },1269                    }1270                ]1271            }1272        },1273    });12741275    console.log(interaction.output_text);12761277### Java12781279    import com.google.genai.Client;1280    import com.google.genai.gaos.models.interactions.AgentOption;1281    import com.google.genai.gaos.models.interactions.Allowlist;1282    import com.google.genai.gaos.models.interactions.AllowlistEntry;1283    import com.google.genai.gaos.models.interactions.CreateAgentInteraction;1284    import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;1285    import com.google.genai.gaos.models.interactions.Environment;1286    import com.google.genai.gaos.models.interactions.EnvironmentNetworkEgressAllowlist;1287    import com.google.genai.gaos.models.interactions.Interaction;1288    import com.google.genai.gaos.models.interactions.InteractionsInput;1289    import com.google.genai.gaos.models.interactions.Network;1290    import com.google.genai.gaos.models.interactions.Transform;1291    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;1292    import java.nio.charset.StandardCharsets;1293    import java.util.List;1294    import java.util.Map;12951296    // Fetch a short-lived access token from your local gcloud CLI1297    Process process = new ProcessBuilder("gcloud", "auth", "print-access-token").start();1298    String gcloudToken = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8).trim();12991300    Client client = new Client();13011302    Environment env = Environment.builder()1303        .network(Network.of(EnvironmentNetworkEgressAllowlist.of(1304            Allowlist.builder()1305                .allowlist(List.of(1306                    AllowlistEntry.builder()1307                        .domain("storage.googleapis.com")1308                        .transform(Transform.of(Map.of(1309                            "Authorization", "Bearer " + gcloudToken1310                        )))1311                        .build()1312                ))1313                .build()1314        )))1315        .build();13161317    CreateAgentInteraction params = CreateAgentInteraction.builder()1318        .agent(AgentOption.of("antigravity-preview-09-2026"))1319        .input(InteractionsInput.of("List the files in gs://my-bucket/reports/ using the GCS JSON API."))1320        .environment(CreateAgentInteractionEnvironment.of(env))1321        .build();13221323    Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();1324    System.out.println(interaction.outputText().orElse(""));13251326### REST13271328    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \1329    -H "Content-Type: application/json" \1330    -H "x-goog-api-key: $GEMINI_API_KEY" \1331    -d '{1332        "agent": "antigravity-preview-09-2026",1333        "input": "List the files in gs://my-bucket/reports/ using the GCS JSON API.",1334        "environment": {1335            "type": "remote",1336            "network": {1337                "allowlist": [1338                    {1339                        "domain": "storage.googleapis.com",1340                        "transform": {1341                            "Authorization": "Bearer <YOUR_GCLOUD_TOKEN>"1342                        }1343                    }1344                ]1345            }1346        }1347    }'13481349`credential` and `transform` can appear on the same rule. The credential is1350applied first and `transform` merges on top, so an explicit `transform` header1351wins if both set the same key. A common pattern is a credential for the1352authentication header plus a `transform` for the extra headers the service1353expects alongside it.13541355### Disable network access13561357To block all outbound network access, set `network` to `disabled`:13581359### Python13601361    from google import genai13621363    client = genai.Client()13641365    interaction = client.interactions.create(1366        agent="antigravity-preview-09-2026",1367        input="Analyze the local files only.",1368        environment={1369            "type": "remote",1370            "network": "disabled",1371        },1372    )13731374    print(interaction.output_text)13751376### JavaScript13771378    import { GoogleGenAI } from "@google/genai";13791380    const client = new GoogleGenAI({});13811382    const interaction = await client.interactions.create({1383        agent: "antigravity-preview-09-2026",1384        input: "Analyze the local files only.",1385        environment: {1386            type: "remote",1387            network: "disabled",1388        },1389    });13901391    console.log(interaction.output_text);13921393### Java13941395    import com.google.genai.Client;1396    import com.google.genai.gaos.models.interactions.AgentOption;1397    import com.google.genai.gaos.models.interactions.CreateAgentInteraction;1398    import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;1399    import com.google.genai.gaos.models.interactions.Environment;1400    import com.google.genai.gaos.models.interactions.Interaction;1401    import com.google.genai.gaos.models.interactions.InteractionsInput;1402    import com.google.genai.gaos.models.interactions.Network;1403    import com.google.genai.gaos.models.interactions.NetworkEnum;1404    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;14051406    Client client = new Client();14071408    Environment env = Environment.builder()1409        .network(Network.of(NetworkEnum.DISABLED))1410        .build();14111412    CreateAgentInteraction params = CreateAgentInteraction.builder()1413        .agent(AgentOption.of("antigravity-preview-09-2026"))1414        .input(InteractionsInput.of("Analyze the local files only."))1415        .environment(CreateAgentInteractionEnvironment.of(env))1416        .build();14171418    Interaction interaction = client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();1419    System.out.println(interaction.outputText().orElse(""));14201421### REST14221423    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \1424    -H "Content-Type: application/json" \1425    -H "x-goog-api-key: $GEMINI_API_KEY" \1426    -d '{1427        "agent": "antigravity-preview-09-2026",1428        "input": "Analyze the local files only.",1429        "environment": {1430            "type": "remote",1431            "network": "disabled"1432        }1433    }'14341435### Refresh credentials14361437Inline tokens such as access tokens and short-lived API keys expire.1438You can refresh them by passing the existing `environment_id` together with a1439new `network` configuration on the next interaction. The new network rules1440fully replace the previous ones, while the environment's file system state1441(installed packages, files, repositories) is preserved.14421443If you use a stored [credential](https://ai.google.dev/gemini-api/docs/agent-credentials) instead,1444you don't need this. An `oauth2` credential refreshes itself, and rotating any1445credential is a `PATCH` on the credential that leaves every allowlist rule1446referencing it untouched.14471448### Python14491450    from google import genai14511452    client = genai.Client()14531454    # First interaction: use an initial token1455    first = client.interactions.create(1456        agent="antigravity-preview-09-2026",1457        input="List the files in gs://my-bucket/reports/ using the GCS JSON API.",1458        environment={1459            "type": "remote",1460            "network": {1461                "allowlist": [1462                    {1463                        "domain": "storage.googleapis.com",1464                        "transform": {1465                            "Authorization": "Bearer INITIAL_TOKEN"1466                        },1467                    }1468                ]1469            },1470        },1471    )14721473    # Later: refresh the token on the same environment1474    result = client.interactions.create(1475        agent="antigravity-preview-09-2026",1476        input="Now download the file reports/q1.csv from the same bucket.",1477        environment={1478            "type": "remote",1479            "environment_id": first.environment_id,1480            "network": {1481                "allowlist": [1482                    {1483                        "domain": "storage.googleapis.com",1484                        "transform": {1485                            "Authorization": "Bearer REFRESHED_TOKEN"1486                        },1487                    }1488                ]1489            },1490        },1491    )14921493    print(result.output_text)14941495### JavaScript14961497    import { GoogleGenAI } from "@google/genai";14981499    const client = new GoogleGenAI({});15001501    // First interaction: use an initial token1502    const first = await client.interactions.create({1503        agent: "antigravity-preview-09-2026",1504        input: "List the files in gs://my-bucket/reports/ using the GCS JSON API.",1505        environment: {1506            type: "remote",1507            network: {1508                allowlist: [1509                    {1510                        domain: "storage.googleapis.com",1511                        transform: {1512                            "Authorization": "Bearer INITIAL_TOKEN"1513                        },1514                    }1515                ]1516            }1517        },1518    });15191520    // Later: refresh the token on the same environment1521    const result = await client.interactions.create({1522        agent: "antigravity-preview-09-2026",1523        input: "Now download the file reports/q1.csv from the same bucket.",1524        environment: {1525            type: "remote",1526            environment_id: first.environment_id,1527            network: {1528                allowlist: [1529                    {1530                        domain: "storage.googleapis.com",1531                        transform: {1532                            "Authorization": "Bearer REFRESHED_TOKEN"1533                        },1534                    }1535                ]1536            }1537        },1538    });15391540    console.log(result.output_text);15411542### Java15431544    import com.google.genai.Client;1545    import com.google.genai.gaos.models.interactions.AgentOption;1546    import com.google.genai.gaos.models.interactions.Allowlist;1547    import com.google.genai.gaos.models.interactions.AllowlistEntry;1548    import com.google.genai.gaos.models.interactions.CreateAgentInteraction;1549    import com.google.genai.gaos.models.interactions.CreateAgentInteractionEnvironment;1550    import com.google.genai.gaos.models.interactions.Environment;1551    import com.google.genai.gaos.models.interactions.EnvironmentNetworkEgressAllowlist;1552    import com.google.genai.gaos.models.interactions.Interaction;1553    import com.google.genai.gaos.models.interactions.InteractionsInput;1554    import com.google.genai.gaos.models.interactions.Network;1555    import com.google.genai.gaos.models.interactions.Transform;1556    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;1557    import java.util.List;1558    import java.util.Map;15591560    Client client = new Client();15611562    // First interaction: use an initial token1563    Environment initialEnv = Environment.builder()1564        .network(Network.of(EnvironmentNetworkEgressAllowlist.of(1565            Allowlist.builder()1566                .allowlist(List.of(1567                    AllowlistEntry.builder()1568                        .domain("storage.googleapis.com")1569                        .transform(Transform.of(Map.of(1570                            "Authorization", "Bearer INITIAL_TOKEN"1571                        )))1572                        .build()1573                ))1574                .build()1575        )))1576        .build();15771578    CreateAgentInteraction firstParams = CreateAgentInteraction.builder()1579        .agent(AgentOption.of("antigravity-preview-09-2026"))1580        .input(InteractionsInput.of("List the files in gs://my-bucket/reports/ using the GCS JSON API."))1581        .environment(CreateAgentInteractionEnvironment.of(initialEnv))1582        .build();15831584    Interaction first = client.interactions.create(CreateInteractionRequestBody.of(firstParams)).interaction().get();15851586    // Later: refresh the token on the same environment1587    Environment refreshedEnv = Environment.builder()1588        .environmentId(first.environmentId().orElse(""))1589        .network(Network.of(EnvironmentNetworkEgressAllowlist.of(1590            Allowlist.builder()1591                .allowlist(List.of(1592                    AllowlistEntry.builder()1593                        .domain("storage.googleapis.com")1594                        .transform(Transform.of(Map.of(1595                            "Authorization", "Bearer REFRESHED_TOKEN"1596                        )))1597                        .build()1598                ))1599                .build()1600        )))1601        .build();16021603    CreateAgentInteraction secondParams = CreateAgentInteraction.builder()1604        .agent(AgentOption.of("antigravity-preview-09-2026"))1605        .input(InteractionsInput.of("Now download the file reports/q1.csv from the same bucket."))1606        .environment(CreateAgentInteractionEnvironment.of(refreshedEnv))1607        .build();16081609    Interaction result = client.interactions.create(CreateInteractionRequestBody.of(secondParams)).interaction().get();1610    System.out.println(result.outputText().orElse(""));16111612### REST16131614    # Use the environment_id from a previous interaction1615    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \1616    -H "Content-Type: application/json" \1617    -H "x-goog-api-key: $GEMINI_API_KEY" \1618    -d '{1619        "agent": "antigravity-preview-09-2026",1620        "input": "Now download the file reports/q1.csv from the same bucket.",1621        "environment": {1622            "type": "remote",1623            "environment_id": "<ENVIRONMENT_ID_FROM_PREVIOUS_INTERACTION>",1624            "network": {1625                "allowlist": [1626                    {1627                        "domain": "storage.googleapis.com",1628                        "transform": {1629                            "Authorization": "Bearer REFRESHED_TOKEN"1630                        }1631                    }1632                ]1633            }1634        }1635    }'16361637## Environment lifecycle16381639Environments follow this lifecycle:16401641| State | Behavior |1642|---|---|1643| **Created** | Provisioned when an interaction specifies `environment: "remote"` or a config object. |1644| **Active** | Running while an interaction is in progress. |1645| **Idle** | Auto-snapshot and stopped after 15 minutes of inactivity. |1646| **Offline** | Retained for 7 days since last active. Can be resumed by passing its ID. |1647| **Deleted** | Removed from the system automatically after 7-day TTL retention expires or upon manual deletion. |16481649## Environments API16501651You can use the Environments API to programmatically manage sandbox sessions.1652Enumerating environments lets you discover active session IDs and recover state1653if a client connection terminates during a long-running task. You can also1654inspect session metadata and explicitly delete environments when workflows1655conclude rather than waiting for automatic TTL expiration.16561657### List environments16581659List active environments belonging to your project. Use pagination parameters1660to control the response batch size.16611662### Python16631664    from google import genai16651666    client = genai.Client()16671668    response = client.environments.list(page_size=10)1669    for env in response.environments:1670        print(f"Environment ID: {env.id}, Status: {env.status}")16711672### JavaScript16731674    import { GoogleGenAI } from "@google/genai";16751676    const client = new GoogleGenAI({});16771678    const response = await client.environments.list({ page_size: 10 });1679    for (const env of response.environments) {1680        console.log(`Environment ID: ${env.id}, Status: ${env.status}`);1681    }16821683### Java16841685    import com.google.genai.Client;1686    import com.google.genai.gaos.models.environments.Environment;1687    import com.google.genai.gaos.models.environments.ListEnvironmentsResponse;1688    import java.util.List;16891690    Client client = new Client();16911692    ListEnvironmentsResponse response = client.environments.listEnvironments()1693        .pageSize(10)1694        .call()1695        .listEnvironmentsResponse()1696        .get();16971698    for (Environment env : response.environments().orElse(List.of())) {1699        System.out.println("Environment ID: " + env.id().orElse("") + ", Status: " + env.status().orElse(null));1700    }17011702### REST17031704    curl -X GET "https://generativelanguage.googleapis.com/v1beta/environments?pageSize=10" \1705    -H "x-goog-api-key: $GEMINI_API_KEY"17061707The response looks similar to the following:17081709    {1710      "environments": [1711        {1712          "id": "140128b2a13c12c00a5a0d8cf7af9469",1713          "status": "active"1714        },1715        {1716          "id": "362b738275a1d74af6f1c62bc050da73",1717          "status": "active"1718        }1719      ],1720      "next_page_token": "Cj...5aE="1721    }17221723### Get an environment17241725Retrieve metadata and configuration details for a specific environment by its1726resource name.17271728### Python17291730    from google import genai17311732    client = genai.Client()17331734    env = client.environments.get(id="YOUR_ENVIRONMENT_ID")1735    print(f"Environment ID: {env.id}, Status: {env.status}")17361737### JavaScript17381739    import { GoogleGenAI } from "@google/genai";17401741    const client = new GoogleGenAI({});17421743    const env = await client.environments.get("YOUR_ENVIRONMENT_ID");1744    console.log(`Environment ID: ${env.id}, Status: ${env.status}`);17451746### Java17471748    import com.google.genai.Client;1749    import com.google.genai.gaos.models.environments.Environment;17501751    Client client = new Client();17521753    Environment env = client.environments.getEnvironment("YOUR_ENVIRONMENT_ID").environment().get();1754    System.out.println("Environment ID: " + env.id().orElse("") + ", Status: " + env.status().orElse(null));17551756### REST17571758    curl -X GET "https://generativelanguage.googleapis.com/v1beta/environments/YOUR_ENVIRONMENT_ID" \1759    -H "x-goog-api-key: $GEMINI_API_KEY"17601761The response looks similar to the following:17621763    {1764      "id": "140128b2a13c12c00a5a0d8cf7af9469",1765      "status": "active",1766      "sources": [1767        {1768          "type": "repository",1769          "source": "https://github.com/octocat/Spoon-Knife",1770          "target": "/workspace/spoon-knife"1771        }1772      ],1773      "network": {1774        "allowlist": [1775          {1776            "domain": "api.github.com"1777          },1778          {1779            "domain": "github.com"1780          }1781        ]1782      }1783    }17841785### Delete an environment17861787Explicitly terminate and delete an environment to clean up sandbox resources1788when your tasks or pipelines finish.17891790### Python17911792    from google import genai17931794    client = genai.Client()17951796    client.environments.delete(id="YOUR_ENVIRONMENT_ID")17971798### JavaScript17991800    import { GoogleGenAI } from "@google/genai";18011802    const client = new GoogleGenAI({});18031804    await client.environments.delete("YOUR_ENVIRONMENT_ID");18051806### Java18071808    import com.google.genai.Client;18091810    Client client = new Client();18111812    client.environments.deleteEnvironment("YOUR_ENVIRONMENT_ID");18131814### REST18151816    curl -X DELETE "https://generativelanguage.googleapis.com/v1beta/environments/YOUR_ENVIRONMENT_ID" \1817    -H "x-goog-api-key: $GEMINI_API_KEY"18181819## Manage files in the environment18201821The agent creates and modifies files inside the sandbox during execution. You1822can browse directory contents, get file metadata, download individual files or1823entire directories as tar archives, and upload files or extract archives1824directly into the environment. Storage in sandbox environments is subject to1825fair usage limits.18261827### List files in a directory18281829List the contents of a directory in the environment. By default, lists the root1830directory.18311832#### Query parameters18331834| Parameter | Type | Description |1835|---|---|---|1836| `recursive` | boolean | When `true`, lists all files and directories recursively. Default: `false`. |18371838### Python18391840    from google import genai18411842    client = genai.Client()18431844    # List root directory1845    response = client.environments.files.list(1846        environment="YOUR_ENVIRONMENT_ID",1847        path="",1848    )1849    for file in response.files:1850        print(f"{file.name} ({file.type}) - {file.path}")18511852    # List a subdirectory recursively1853    response = client.environments.files.list(1854        environment="YOUR_ENVIRONMENT_ID",1855        path="src",1856        recursive=True,1857    )1858    for file in response.files:1859        print(f"{file.name} ({file.type}) - {file.path}")18601861### JavaScript18621863    import { GoogleGenAI } from "@google/genai";18641865    const client = new GoogleGenAI({});18661867    // List root directory1868    const response = await client.environments.files.list({1869        environment: "YOUR_ENVIRONMENT_ID",1870        path: "",1871    });1872    for (const file of response.files) {1873        console.log(`${file.name} (${file.type}) - ${file.path}`);1874    }18751876    // List a subdirectory recursively1877    const srcResponse = await client.environments.files.list({1878        environment: "YOUR_ENVIRONMENT_ID",1879        path: "src",1880        recursive: true,1881    });1882    for (const file of srcResponse.files) {1883        console.log(`${file.name} (${file.type}) - ${file.path}`);1884    }18851886### REST18871888    # List root directory1889    curl -X GET "https://generativelanguage.googleapis.com/v1beta/environments/$ENV_ID/files" \1890      -H "x-goog-api-key: $GEMINI_API_KEY"18911892    # List a subdirectory1893    curl -X GET "https://generativelanguage.googleapis.com/v1beta/environments/$ENV_ID/files/src" \1894      -H "x-goog-api-key: $GEMINI_API_KEY"18951896    # List all files recursively1897    curl -X GET "https://generativelanguage.googleapis.com/v1beta/environments/$ENV_ID/files?recursive=true" \1898      -H "x-goog-api-key: $GEMINI_API_KEY"18991900The response returns a `files` array with metadata for each entry:19011902    {1903      "files": [1904        {1905          "name": "config",1906          "path": "config",1907          "type": "DIRECTORY",1908          "created": "2026-08-12T07:44:18Z",1909          "modified": "2026-08-12T07:44:18Z"1910        },1911        {1912          "name": "main.py",1913          "path": "src/main.py",1914          "type": "FILE",1915          "size_bytes": "15",1916          "mime_type": "text/x-python; charset=utf-8",1917          "created": "2026-08-12T07:44:20Z",1918          "modified": "2026-08-12T07:44:20Z"1919        }1920      ]1921    }19221923#### File entry fields19241925| Field | Type | Description |1926|---|---|---|1927| `name` | string | The file or directory name. |1928| `path` | string | The full path relative to the environment root. |1929| `type` | string | Either `FILE` or `DIRECTORY`. |1930| `size_bytes` | string | File size in bytes (files only). |1931| `mime_type` | string | MIME type (files only). |1932| `created` | string | ISO 8601 creation timestamp. |1933| `modified` | string | ISO 8601 last-modified timestamp. |19341935### Get file metadata19361937Get metadata for a specific file by path.19381939### Python19401941    from google import genai19421943    client = genai.Client()19441945    response = client.environments.files.list(1946        environment="YOUR_ENVIRONMENT_ID",1947        path="src/main.py",1948    )1949    file = response.files[0]1950    print(f"Name: {file.name}, Size: {file.size_bytes} bytes, Type: {file.mime_type}")19511952### JavaScript19531954    import { GoogleGenAI } from "@google/genai";19551956    const client = new GoogleGenAI({});19571958    const response = await client.environments.files.list({1959        environment: "YOUR_ENVIRONMENT_ID",1960        path: "src/main.py",1961    });1962    const file = response.files[0];1963    console.log(`Name: ${file.name}, Size: ${file.size_bytes} bytes, Type: ${file.mime_type}`);19641965### REST19661967    curl -X GET "https://generativelanguage.googleapis.com/v1beta/environments/$ENV_ID/files/src/main.py" \1968      -H "x-goog-api-key: $GEMINI_API_KEY"19691970The response returns the file metadata wrapped in a `files` array:19711972    {1973      "files": [1974        {1975          "name": "main.py",1976          "path": "src/main.py",1977          "type": "FILE",1978          "size_bytes": "15",1979          "mime_type": "text/x-python; charset=utf-8",1980          "created": "2026-08-12T07:44:20Z",1981          "modified": "2026-08-12T07:44:20Z"1982        }1983      ]1984    }19851986If the file doesn't exist, the API returns a `404` error:19871988    {1989      "error": {1990        "message": "Path 'nonexistent.txt' not found in environment 'ENV_ID'.",1991        "code": "not_found"1992      }1993    }19941995### Download a single file19961997Download the contents of a specific file. In the SDKs, use the `download()`1998method. In REST requests, append the `?alt=media` query parameter to the file1999path. The server responds with `200 OK` and streams the raw file content.20002001### Python20022003    from google import genai20042005    client = genai.Client()20062007    content = client.environments.files.download(2008        environment="YOUR_ENVIRONMENT_ID",2009        path="src/main.py",2010    )20112012    with open("main.py", "wb") as f:2013        f.write(content)20142015### JavaScript20162017    import { GoogleGenAI } from "@google/genai";2018    import * as fs from "fs";20192020    const client = new GoogleGenAI({});20212022    const bytes = await client.environments.files.download({2023        environment: "YOUR_ENVIRONMENT_ID",2024        path: "src/main.py",2025    });20262027    fs.writeFileSync("main.py", Buffer.from(bytes));20282029### REST20302031    curl -L -X GET "https://generativelanguage.googleapis.com/v1beta/environments/$ENV_ID/files/src/main.py?alt=media" \2032      -H "x-goog-api-key: $GEMINI_API_KEY" \2033      -o main.py20342035### Download a directory as a tar archive20362037Download an entire directory as a tar archive by requesting the directory path2038with `?alt=media`. This returns a POSIX tar file (not gzipped). Use2039`recursive=true` to include nested subdirectories.20402041### Python20422043    import tarfile2044    from google import genai20452046    client = genai.Client()20472048    # Download a subdirectory archive2049    archive = client.environments.files.download(2050        environment="YOUR_ENVIRONMENT_ID",2051        path="src",2052    )20532054    with open("src.tar", "wb") as f:2055        f.write(archive)20562057    with tarfile.open("src.tar") as tar:2058        tar.extractall(path="./extracted")20592060### JavaScript20612062    import { GoogleGenAI } from "@google/genai";2063    import { execSync } from "child_process";2064    import * as fs from "fs";20652066    const client = new GoogleGenAI({});20672068    // Download a subdirectory archive2069    const bytes = await client.environments.files.download({2070        environment: "YOUR_ENVIRONMENT_ID",2071        path: "src",2072    });20732074    fs.writeFileSync("src.tar", Buffer.from(bytes));2075    execSync("tar -xf src.tar -C ./extracted");20762077### REST20782079    # Download a subdirectory (top-level files only)2080    curl -L -X GET "https://generativelanguage.googleapis.com/v1beta/environments/$ENV_ID/files/src?alt=media" \2081      -H "x-goog-api-key: $GEMINI_API_KEY" \2082      -o src.tar20832084    # Download a subdirectory recursively (includes nested directories)2085    curl -L -X GET "https://generativelanguage.googleapis.com/v1beta/environments/$ENV_ID/files/config?alt=media&recursive=true" \2086      -H "x-goog-api-key: $GEMINI_API_KEY" \2087      -o config.tar20882089    # Download root directory2090    curl -L -X GET "https://generativelanguage.googleapis.com/v1beta/environments/$ENV_ID/files?alt=media" \2091      -H "x-goog-api-key: $GEMINI_API_KEY" \2092      -o snapshot.tar20932094    # Extract the archive2095    tar xf snapshot.tar -C ./extracted20962097#### Behavior matrix20982099The following behavior matrix summarizes the expected response and archive behavior across file and directory endpoints, HTTP methods, and query parameters:21002101| Request | `alt` | `recursive` | `extract` | `overwrite` | Response |2102|---|---|---|---|---|---|2103| `GET /files` | (none) | (none) | - | - | JSON listing of root directory |2104| `GET /files/{path}` (file) | (none) | - | - | - | JSON metadata for the file |2105| `GET /files/{path}` (dir) | (none) | `false` | - | - | JSON listing of immediate children |2106| `GET /files/{path}` (dir) | (none) | `true` | - | - | JSON listing of all descendants |2107| `GET /files/{path}?alt=media` (file) | `media` | - | - | - | Raw file content |2108| `GET /files/{path}?alt=media` (dir) | `media` | `false` | - | - | Tar archive of immediate files in directory |2109| `GET /files/{path}?alt=media` (dir) | `media` | `true` | - | - | Tar archive of all files recursively |2110| `GET /files?alt=media` | `media` | `false` | - | - | Tar archive of root-level files only |2111| `PUT /files/{path}` (file) | - | - | `false` | `false` | Writes the file at path. Returns `409 Conflict` if it already exists |2112| `PUT /files/{path}?overwrite=true` | - | - | `false` | `true` | Writes or overwrites the file at path |2113| `PUT /files/{path}?extract=true` | - | - | `true` | `false` | Unpacks archive into destination directory. Returns `409 Conflict` if any target file exists |2114| `PUT /files/{path}?extract=true&overwrite=true` | - | - | `true` | `true` | Unpacks archive, replacing any existing files |21152116### Upload files to the environment21172118Upload individual files or directory archives directly to an existing environment2119sandbox using HTTP `PUT`. Parent directories are created automatically if they2120do not exist. Storage in environments is subject to fair usage limits.21212122> [!NOTE]2123> **Note:** REST uploads use the `/upload/` path prefix, for example `https://generativelanguage.googleapis.com/upload/v1beta/environments/{environment_id}/files/{path}`. A `PUT` sent without the prefix returns a `400` error. The Python and JavaScript clients add the prefix for you.21242125#### Upload a single file21262127### Python21282129    from google import genai21302131    client = genai.Client()21322133    with open("local_file.txt", "rb") as f:2134        result = client.environments.files.upload(2135            environment="YOUR_ENVIRONMENT_ID",2136            path="workspace/data/file.txt",2137            file=f,2138            mime_type="text/plain",2139            overwrite=True,2140        )21412142    file = result.files[0]2143    print(f"Uploaded: {file.name} ({file.size_bytes} bytes)")21442145### JavaScript21462147    import { GoogleGenAI } from "@google/genai";2148    import * as fs from "fs";21492150    const client = new GoogleGenAI({});21512152    const content = fs.readFileSync("local_file.txt");2153    const result = await client.environments.files.upload({2154        environment: "YOUR_ENVIRONMENT_ID",2155        path: "workspace/data/file.txt",2156        file: content,2157        mime_type: "text/plain",2158        overwrite: true,2159    });21602161    const file = result.files[0];2162    console.log(`Uploaded: ${file.name} (${file.size_bytes} bytes)`);21632164### REST21652166    curl -X PUT "https://generativelanguage.googleapis.com/upload/v1beta/environments/$ENV_ID/files/workspace/data/file.txt" \2167      -H "x-goog-api-key: $GEMINI_API_KEY" \2168      -H "Content-Type: text/plain" \2169      --data-binary @local_file.txt21702171The response returns metadata for the uploaded file, wrapped in a `files` array2172for consistency with the list and get endpoints:21732174    {2175      "files": [2176        {2177          "name": "file.txt",2178          "path": "workspace/data/file.txt",2179          "type": "FILE",2180          "size_bytes": "1024",2181          "mime_type": "text/plain"2182        }2183      ]2184    }21852186#### Upload and extract a directory archive21872188To seed an entire codebase or directory structure in a single request, upload a2189`.tar` or `.tar.gz` archive with `extract=true`.21902191### Python21922193    from google import genai21942195    client = genai.Client()21962197    with open("source.tar.gz", "rb") as f:2198        result = client.environments.files.upload(2199            environment="YOUR_ENVIRONMENT_ID",2200            path="workspace/src/",2201            file=f,2202            extract=True,2203        )22042205    for entry in result.files:2206        print(f"Extracted: {entry.path}")22072208### JavaScript22092210    import { GoogleGenAI } from "@google/genai";2211    import * as fs from "fs";22122213    const client = new GoogleGenAI({});22142215    const archive = fs.readFileSync("source.tar.gz");2216    const result = await client.environments.files.upload({2217        environment: "YOUR_ENVIRONMENT_ID",2218        path: "workspace/src/",2219        file: archive,2220        extract: true,2221    });22222223    for (const entry of result.files) {2224        console.log(`Extracted: ${entry.path}`);2225    }22262227### REST22282229    curl -X PUT "https://generativelanguage.googleapis.com/upload/v1beta/environments/$ENV_ID/files/workspace/src/?extract=true" \2230      -H "x-goog-api-key: $GEMINI_API_KEY" \2231      -H "Content-Type: application/x-tar" \2232      --data-binary @source.tar.gz22332234The response lists every file written by the archive:22352236    {2237      "files": [2238        {2239          "name": "app.py",2240          "path": "workspace/src/app.py",2241          "type": "FILE",2242          "size_bytes": "15",2243          "mime_type": "text/x-python"2244        },2245        {2246          "name": "requirements.txt",2247          "path": "workspace/src/requirements.txt",2248          "type": "FILE",2249          "size_bytes": "17",2250          "mime_type": "text/plain"2251        }2252      ]2253    }22542255> [!NOTE]2256> **Note:** The archive format is detected from the payload itself, so `.tar` and `.tar.gz` both work regardless of the `Content-Type` you send.22572258#### Upload large files with a resumable session22592260For large payloads, or when uploading over an unreliable connection, use a2261resumable session instead of sending the whole body in one request. A resumable2262upload splits the transfer into chunks that can be retried individually, so a2263failure part way through does not force you to start over.22642265Start by initiating the session with `uploadType=resumable`. Send an empty body2266and use the `X-Upload-Content-Type` and `X-Upload-Content-Length` headers to2267declare the media type and total size of the payload you intend to upload:22682269    PUT /upload/v1beta/environments/$ENV_ID/files/workspace/data/large_dataset.bin?uploadType=resumable HTTP/1.12270    Host: generativelanguage.googleapis.com2271    X-Upload-Content-Type: application/octet-stream2272    X-Upload-Content-Length: 209715202273    Content-Length: 02274    x-goog-api-key: $GEMINI_API_KEY22752276The response carries the session URL in the `Location` header. This URL already2277contains an `upload_id`, so it does not need the API key again:22782279    HTTP/1.1 200 OK2280    Location: https://generativelanguage.googleapis.com/upload/v1beta/environments/$ENV_ID/files/workspace/data/large_dataset.bin?uploadType=resumable&upload_id=AJjja9bfHjiYlGi60pUazCaTuPY2281    Content-Length: 022822283Upload the payload to that URL in chunks. Each chunk declares its byte range and2284the total size with a `Content-Range` header:22852286    PUT /upload/v1beta/environments/$ENV_ID/files/workspace/data/large_dataset.bin?uploadType=resumable&upload_id=AJjja9bfHjiYlGi60pUazCaTuPY HTTP/1.12287    Host: generativelanguage.googleapis.com2288    Content-Type: application/octet-stream2289    Content-Range: bytes 0-10485759/209715202290    Content-Length: 1048576022912292    <10 MB binary payload>22932294Every chunk except the last returns `308 Resume Incomplete`. The `Range` header2295tells you how many bytes the server has committed, which is where you resume2296from if a chunk fails:22972298    HTTP/1.1 308 Resume Incomplete2299    Range: bytes=0-104857592300    Content-Length: 023012302Send the remaining chunks the same way:23032304    PUT /upload/v1beta/environments/$ENV_ID/files/workspace/data/large_dataset.bin?uploadType=resumable&upload_id=AJjja9bfHjiYlGi60pUazCaTuPY HTTP/1.12305    Host: generativelanguage.googleapis.com2306    Content-Type: application/octet-stream2307    Content-Range: bytes 10485760-20971519/209715202308    Content-Length: 1048576023092310    <remaining 10 MB binary payload>23112312The final chunk completes the upload and returns the file metadata, in the same2313`files` envelope as a single-shot upload:23142315    {2316      "files": [2317        {2318          "name": "large_dataset.bin",2319          "path": "workspace/data/large_dataset.bin",2320          "type": "FILE",2321          "size_bytes": "20971520",2322          "mime_type": "application/octet-stream"2323        }2324      ]2325    }23262327Resumable sessions work with `extract` and `overwrite` as well. Set those query2328parameters on the initiating request, not on the individual chunks.23292330#### Overwrite protection23312332By default, `overwrite` is `false`. If the destination path already exists, the2333request returns a `409 Conflict` error and nothing is written:23342335    {2336      "error": {2337        "message": "Requested entity already exists",2338        "code": "aborted"2339      }2340    }23412342To replace an existing file or directory, set `overwrite=true` (or append2343`?overwrite=true` in REST). With `extract=true`, the conflict check applies to2344every file in the archive, so the request fails if any target file exists.23452346### Download full snapshot (deprecated)23472348> [!CAUTION]2349> **Caution:** The legacy `/files/environment-{id}:download` endpoint is deprecated. Use the [environment files endpoint](https://ai.google.dev/gemini-api/docs/agent-environment#download-directory) to download directories or individual files instead.23502351To migrate existing code to the environment files API:23522353- **Python**: Replace legacy file download requests with:23542355      archive = client.environments.files.download(2356          environment="YOUR_ENVIRONMENT_ID",2357          path="workspace",2358      )2359      with open("snapshot.tar", "wb") as f:2360          f.write(archive)23612362- **JavaScript**: Replace legacy file download requests with:23632364      const bytes = await client.environments.files.download({2365          environment: "YOUR_ENVIRONMENT_ID",2366          path: "workspace",2367      });2368      fs.writeFileSync("snapshot.tar", Buffer.from(bytes));23692370- **REST** : Replace `GET /v1beta/files/environment-$ENV_ID:download?alt=media` with:23712372      curl -L -X GET "https://generativelanguage.googleapis.com/v1beta/environments/$ENV_ID/files?alt=media" \2373        -H "x-goog-api-key: $GEMINI_API_KEY" \2374        -o snapshot.tar23752376## Pricing \& resources23772378Each environment runs with fixed resource allocations:23792380| Resource | Value |2381|---|---|2382| **CPU** | 4 cores |2383| **Memory** | 16 GB |23842385Environment compute (CPU, memory, sandbox execution) is **not billed** during2386the preview period. See2387[Pricing](https://ai.google.dev/gemini-api/docs/pricing#pricing-for-agents) for2388agent token costs.23892390## Limitations23912392- **Preview status:** Environments and managed agents are in preview. Features and schemas may change.2393- **Inline source size:** Inline sources are limited to 1 MB per file, and 2 MB total across all files.2394- **Source size**: Git repositories are limited to 500 MB and Cloud Storage repositories to 2 GB.2395- **Environment startup:** Provisioning a new environment takes up to \~5 seconds. Large source repositories may increase this time.2396- **Environment expiration:** Inactive offline environments are retained for 7 days before expiring using automatic TTL cleanup. Passing an expired or invalid environment ID returns a `404 Not Found` error.2397- **File support:** The agent is currently constrained to reading text and image files. Binary file support is not yet available.2398- **No mounting from root:** You can't set root (`/`) as target when adding a custom source, you must always specify a sub-directory.23992400## What's next24012402- [Agents Overview](https://ai.google.dev/gemini-api/docs/agents): Learn about the core concepts of managed agents.2403- [Quickstart](https://ai.google.dev/gemini-api/docs/managed-agents-quickstart): Start building with multi-turn conversations and streaming.2404- [Antigravity Agent](https://ai.google.dev/gemini-api/docs/antigravity-agent): Explore capabilities, tools, model selection, and pricing for the default agent.2405- [Building Custom Agents](https://ai.google.dev/gemini-api/docs/custom-agents): Define your own agents using `AGENTS.md` and `SKILL.md`.2406- [Hooks](https://ai.google.dev/gemini-api/docs/agent-hooks): Enforce security guardrails and run side-effect validations inside the sandbox.
Files main
Menu

Theme