Skip to content

armgit / ax

Public Imported from GitHub
0

Agent Executor (AX) is Google's open agentic orchestration runtime

Go

antigravity: remove _resolve_localhost /etc/hosts hack (#328)

Joyce Liua34bbebf2de1
diff --git a/.github/workflows/check-binaries.yml b/.github/workflows/check-binaries.yml
new file mode 100644
index 0000000..c06b7fa
--- /dev/null
+++ b/.github/workflows/check-binaries.yml
@@ -0,0 +1,39 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+name: Check Binaries
+
+on:
+ pull_request:
+ branches: [ "main" ]
+
+jobs:
+ check-no-binaries:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+
+ - name: Check for binary files in PR
+ run: |
+ git fetch origin ${{ github.base_ref }}
+ BINARIES=$(git diff --numstat --diff-filter=ACM origin/${{ github.base_ref }}...HEAD | awk '$1 == "-" || $2 == "-" {print $3}')
+
+ if [ -n "$BINARIES" ]; then
+ echo "::error::Binary files are not allowed to be committed in PRs. Found:"
+ echo "$BINARIES"
+ exit 1
+ fi
diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml
index 3fd354f..9130a0d 100644
--- a/.github/workflows/go.yml
+++ b/.github/workflows/go.yml
@@ -60,14 +60,3 @@ jobs:
- name: Test
run: go test -v ./...
-
- - name: Check for binary files in PR
- run: |
- # Get the list of files where Git shows no line count (binary)
- BINARIES=$(git diff --numstat origin/${{ github.base_ref }}...HEAD | grep "^-" | cut -f3)
-
- if [ -n "$BINARIES" ]; then
- echo "Binary files detected in diff:"
- echo "$BINARIES"
- exit 1 # Fail the check if binaries are found
- fi
diff --git a/.gitignore b/.gitignore
index 55472ef..fa40af3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,17 +1,9 @@
bin/*
eventlog/*
/ax
-local_agent
-remote_agent
*.log
ax-bin
-google-cloud-cli-darwin-arm.tar.gz
-google-cloud-sdk/
-test-sandbox-config.yaml
-sandbox-router
-examples/sandbox_agent/cloudbuild.yaml
-tasklog/*
python/__pycache__
python/proto/__pycache__
-/axepp
__pycache__/
+e2e
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index ae063f6..6b31efb 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -60,12 +60,6 @@ make proto
make test
```
-### Run remote agent
-
-```bash
-make run-remote
-```
-
### Install the ax CLI
```bash
diff --git a/Makefile b/Makefile
index e0b730a..ce04e63 100644
--- a/Makefile
+++ b/Makefile
@@ -1,4 +1,4 @@
-.PHONY: all build proto test test-python clean install
+.PHONY: all build proto test test-python clean install deps clean-logs
# Build all binaries
all: proto build
diff --git a/cmd/ax/harness.go b/cmd/ax/harness.go
index c028007..6ecf3ac 100644
--- a/cmd/ax/harness.go
+++ b/cmd/ax/harness.go
@@ -70,6 +70,9 @@ func setHarnessWorkDir() error {
if dir == "" {
return nil
}
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return fmt.Errorf("create harness working directory %q: %w", dir, err)
+ }
if err := os.Chdir(dir); err != nil {
return fmt.Errorf("set harness working directory %q: %w", dir, err)
}
@@ -174,9 +177,16 @@ func runAntigravityInteractionsHarness(ctx context.Context) error {
return err
}
+ // WorkDir is the agent's working directory. It is authoritative for built-in
+ // env tools (see AntigravityInteractionsConfig.WorkDir) so their execution
+ // does not depend on the process cwd. Empty falls back to the process cwd.
+ workDir := os.Getenv("AX_HARNESS_WORKDIR")
+
cfg := antigravityinteractions.AntigravityInteractionsConfig{
- Agent: agent,
- StateDir: stateDir,
+ Agent: agent,
+ StateDir: stateDir,
+ WorkDir: workDir,
+ SystemInstruction: antigravityinteractions.JoinSystemInstruction(hc.SystemInstruction, antigravityinteractions.WorkspaceSystemInstruction(workDir)),
}
return antigravityinteractions.Serve(ctx, cfg, harnessHost, harnessPort, harnessReadyzPort)
}
diff --git a/cmd/ax/harness_test.go b/cmd/ax/harness_test.go
index 599f5ab..cabe160 100644
--- a/cmd/ax/harness_test.go
+++ b/cmd/ax/harness_test.go
@@ -65,10 +65,14 @@ func TestSetHarnessWorkDir(t *testing.T) {
}
})
- t.Run("missing directory returns an error", func(t *testing.T) {
- t.Setenv("AX_HARNESS_WORKDIR", filepath.Join(t.TempDir(), "does-not-exist"))
- if err := setHarnessWorkDir(); err == nil {
- t.Error("expected an error for a missing directory, got nil")
+ t.Run("missing directory is created", func(t *testing.T) {
+ dir := filepath.Join(t.TempDir(), "created", "workdir")
+ t.Setenv("AX_HARNESS_WORKDIR", dir)
+ if err := setHarnessWorkDir(); err != nil {
+ t.Fatalf("setHarnessWorkDir: %v", err)
+ }
+ if _, err := os.Stat(dir); err != nil {
+ t.Errorf("working directory %q was not created: %v", dir, err)
}
})
}
diff --git a/cmd/ax/internal/cliutil/cliutil.go b/cmd/ax/internal/cliutil/cliutil.go
index a5637d3..7a91f00 100644
--- a/cmd/ax/internal/cliutil/cliutil.go
+++ b/cmd/ax/internal/cliutil/cliutil.go
@@ -126,12 +126,23 @@ func NewControllerFromConfig(ctx context.Context, cfg *Config) (*controller.Cont
if sErr != nil {
return nil, fmt.Errorf("antigravity-interactions harness: %w", sErr)
}
+ // WorkDir is the agent's working directory, authoritative for built-in env
+ // tools (see AntigravityInteractionsConfig.WorkDir). Mirrors the substrate
+ // path (cmd/ax harness): sourced from AX_HARNESS_WORKDIR, empty falls back
+ // to the process cwd.
+ workDir := os.Getenv("AX_HARNESS_WORKDIR")
// skillsPointer was built once, up front, from the top-level skills
- // config (see above). Append it to any configured system instruction.
+ // config (see above). Append it, plus the workspace pointer, to any
+ // configured system instruction.
+ systemInstruction := antigravityinteractions.JoinSystemInstruction(
+ antigravityinteractions.JoinSystemInstruction(aiCfg.SystemInstruction, skillsPointer),
+ antigravityinteractions.WorkspaceSystemInstruction(workDir),
+ )
antigravityInteractionsHarness, err = antigravityinteractions.New(antigravityinteractions.AntigravityInteractionsConfig{
Agent: agent,
- SystemInstruction: antigravityinteractions.JoinSystemInstruction(aiCfg.SystemInstruction, skillsPointer),
+ SystemInstruction: systemInstruction,
StateDir: stateDir,
+ WorkDir: workDir,
})
} else {
antigravityInteractionsHarness, err = substrate.New(config.AntigravityInteractionsHarnessID, "", "", config.AntigravityInteractionsTemplate, 80)
diff --git a/internal/config/config.go b/internal/config/config.go
index 58ec500..ec89b8b 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -324,6 +324,9 @@ func (c *Config) Validate() error {
}
func AXAssetsDir() (string, error) {
+ if dir := os.Getenv("AX_DURABLE_DIR"); dir != "" {
+ return filepath.Join(dir, ".ax"), nil
+ }
home, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("resolving home directory: %w", err)
diff --git a/internal/config/config_test.go b/internal/config/config_test.go
index baebb03..cdcda58 100644
--- a/internal/config/config_test.go
+++ b/internal/config/config_test.go
@@ -15,6 +15,8 @@
package config
import (
+ "os"
+ "path/filepath"
"strings"
"testing"
@@ -345,3 +347,32 @@ func TestValidate_SkillsSelectionOneof(t *testing.T) {
}
})
}
+
+func TestAXAssetsDir(t *testing.T) {
+ t.Run("durable-dir env roots the .ax tree on the volume", func(t *testing.T) {
+ t.Setenv("AX_DURABLE_DIR", "/mnt/durable")
+ got, err := AXAssetsDir()
+ if err != nil {
+ t.Fatalf("AXAssetsDir: %v", err)
+ }
+ want := filepath.Join("/mnt/durable", ".ax")
+ if got != want {
+ t.Errorf("AXAssetsDir() = %q, want %q", got, want)
+ }
+ })
+ t.Run("unset roots under the home directory", func(t *testing.T) {
+ t.Setenv("AX_DURABLE_DIR", "")
+ home, err := os.UserHomeDir()
+ if err != nil {
+ t.Skipf("no home directory: %v", err)
+ }
+ got, err := AXAssetsDir()
+ if err != nil {
+ t.Fatalf("AXAssetsDir: %v", err)
+ }
+ want := filepath.Join(home, ".ax")
+ if got != want {
+ t.Errorf("AXAssetsDir() = %q, want %q", got, want)
+ }
+ })
+}
diff --git a/internal/harness/antigravityinteractions/antigravityinteractions.go b/internal/harness/antigravityinteractions/antigravityinteractions.go
index cb84faf..ce9cc00 100644
--- a/internal/harness/antigravityinteractions/antigravityinteractions.go
+++ b/internal/harness/antigravityinteractions/antigravityinteractions.go
@@ -116,6 +116,13 @@ type AntigravityInteractionsConfig struct {
// --- Optional ---
+ // WorkDir is the working directory the agent operates in. When set, it is the
+ // authoritative base for built-in env tools: run_command executes there (and
+ // resolves a relative Cwd against it). This makes tool execution independent
+ // of the process's ambient cwd. Empty means "use the process cwd" (the
+ // previous behavior). Defaults from AX_HARNESS_WORKDIR.
+ WorkDir string
+
// SystemInstruction, if set, is sent as the interaction's system_instruction
// (a free-form system prompt prepended to the agent's own instructions). It
// is sent on every turn of the interaction loop so it persists across them.
@@ -143,6 +150,9 @@ func (c *AntigravityInteractionsConfig) withDefaults() {
if c.MaxTurns == 0 {
c.MaxTurns = 100
}
+ if c.WorkDir == "" {
+ c.WorkDir = os.Getenv("AX_HARNESS_WORKDIR")
+ }
}
// cloudProject returns the Cloud project id from GOOGLE_CLOUD_PROJECT.
@@ -159,12 +169,12 @@ func cloudLocation() string {
return defaultLocation
}
-// DefaultStateDir returns the default resume-cursor directory, ~/.ax/antigravityinteractions/cursors,
-// used when a caller does not set StateDir explicitly. It lives outside the
-// agent's working directory on purpose: the working directory is the agent's
-// operating surface (it reads and edits files there), so AX's internal state is
-// kept separate to avoid the agent seeing or clobbering it. New still requires a
-// non-empty StateDir; callers apply this default.
+// DefaultStateDir returns the default resume-cursor directory,
+// <AXAssetsDir>/antigravityinteractions/cursors, used when a caller does not set
+// StateDir explicitly. Locally that is ~/.ax/...; on a substrate actor
+// AX_DURABLE_DIR points AXAssetsDir at a durable volume (e.g. /durable/.ax), kept
+// outside the agent's working directory so the agent does not see or modify it.
+// New still requires a non-empty StateDir; callers apply this default.
func DefaultStateDir() (string, error) {
axDir, err := config.AXAssetsDir()
if err != nil {
diff --git a/internal/harness/antigravityinteractions/antigravityinteractions_tools.go b/internal/harness/antigravityinteractions/antigravityinteractions_tools.go
index ad4b979..d3541c0 100644
--- a/internal/harness/antigravityinteractions/antigravityinteractions_tools.go
+++ b/internal/harness/antigravityinteractions/antigravityinteractions_tools.go
@@ -44,7 +44,7 @@ func (h *AntigravityInteractionsHarness) executeTool(ctx context.Context, call c
case "view_file":
return execViewFile(call)
case "run_command":
- return execRunCommand(ctx, call)
+ return execRunCommand(ctx, call, h.cfg.WorkDir)
case "list_dir", "list_directory":
return execListDir(call)
case "move":
@@ -229,7 +229,7 @@ func applyByteWindow(content string, offset int) string {
// command (e.g. `find /`, or `ping` without a count) cannot wedge the harness.
const runCommandTimeout = 60 * time.Second
-func execRunCommand(ctx context.Context, call capturedToolCall) any {
+func execRunCommand(ctx context.Context, call capturedToolCall, workDir string) any {
cmdLine := stringArg(call.arguments, "CommandLine")
if cmdLine == "" {
return map[string]any{"error": "run_command: missing required argument 'CommandLine'"}
@@ -240,9 +240,11 @@ func execRunCommand(ctx context.Context, call capturedToolCall) any {
defer cancel()
cmd := exec.CommandContext(runCtx, "/bin/sh", "-c", cmdLine)
- if cwd := stringArg(call.arguments, "Cwd"); cwd != "" {
- cmd.Dir = cwd
- }
+ // Resolve the working directory. workDir is authoritative so execution does
+ // not depend on the process's ambient cwd. A model-supplied Cwd is honored
+ // relative to workDir if relative, or as-is if absolute; without one, the
+ // command runs in workDir.
+ cmd.Dir = resolveRunDir(workDir, stringArg(call.arguments, "Cwd"))
out, err := cmd.CombinedOutput()
@@ -266,6 +268,28 @@ func execRunCommand(ctx context.Context, call capturedToolCall) any {
return map[string]any{"Output": string(out), "ExitCode": exitCode}
}
+// resolveRunDir picks the directory run_command executes in.
+//
+// - No cwd arg: run in workDir (or the process cwd if workDir is empty).
+// - Absolute cwd: honored as-is (the agent asked for a specific location).
+// - Relative cwd: resolved against workDir, keeping the agent scoped to its
+// workspace rather than the process's ambient cwd.
+//
+// Returning "" makes exec use the process's current directory, matching the
+// prior behavior when no working directory is configured.
+func resolveRunDir(workDir, cwd string) string {
+ switch {
+ case cwd == "":
+ return workDir
+ case filepath.IsAbs(cwd):
+ return cwd
+ case workDir == "":
+ return cwd
+ default:
+ return filepath.Join(workDir, cwd)
+ }
+}
+
func execListDir(call capturedToolCall) any {
dir := stringArg(call.arguments, "DirectoryPath")
if dir == "" {
diff --git a/internal/harness/antigravityinteractions/antigravityinteractions_tools_test.go b/internal/harness/antigravityinteractions/antigravityinteractions_tools_test.go
index e38f3a3..38bc9ce 100644
--- a/internal/harness/antigravityinteractions/antigravityinteractions_tools_test.go
+++ b/internal/harness/antigravityinteractions/antigravityinteractions_tools_test.go
@@ -15,6 +15,7 @@
package antigravityinteractions
import (
+ "context"
"fmt"
"os"
"path/filepath"
@@ -341,3 +342,84 @@ func TestIntArgOK(t *testing.T) {
}
}
}
+
+func TestResolveRunDir(t *testing.T) {
+ cases := []struct {
+ name string
+ workDir string
+ cwd string
+ want string
+ }{
+ {"no cwd -> workDir", "/workspace", "", "/workspace"},
+ {"relative cwd joined to workDir", "/workspace", "sub/dir", "/workspace/sub/dir"},
+ {"absolute cwd honored as-is", "/workspace", "/etc", "/etc"},
+ {"no workDir, no cwd -> empty (process cwd)", "", "", ""},
+ {"no workDir, relative cwd -> cwd", "", "sub", "sub"},
+ {"no workDir, absolute cwd -> cwd", "", "/etc", "/etc"},
+ }
+ for _, c := range cases {
+ if got := resolveRunDir(c.workDir, c.cwd); got != c.want {
+ t.Errorf("%s: resolveRunDir(%q,%q) = %q, want %q", c.name, c.workDir, c.cwd, got, c.want)
+ }
+ }
+}
+
+func TestExecRunCommand_RunsInWorkDir(t *testing.T) {
+ // Create a workspace with a marker file; `ls` from workDir (no Cwd arg) must
+ // list it, proving execution is scoped to workDir and not the process cwd.
+ work := t.TempDir()
+ if err := os.WriteFile(filepath.Join(work, "marker.txt"), []byte("x"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ t.Run("no cwd runs in workDir", func(t *testing.T) {
+ res := execRunCommand(context.Background(),
+ capturedToolCall{arguments: map[string]any{"CommandLine": "ls"}},
+ work).(map[string]any)
+ if code := res["ExitCode"]; code != 0 {
+ t.Fatalf("ExitCode = %v, want 0 (output: %v)", code, res["Output"])
+ }
+ if out, _ := res["Output"].(string); !strings.Contains(out, "marker.txt") {
+ t.Errorf("Output = %q, want it to list marker.txt (ran in wrong dir)", out)
+ }
+ })
+
+ t.Run("pwd reports workDir", func(t *testing.T) {
+ res := execRunCommand(context.Background(),
+ capturedToolCall{arguments: map[string]any{"CommandLine": "pwd"}},
+ work).(map[string]any)
+ out, _ := res["Output"].(string)
+ // macOS /tmp is a symlink to /private/tmp, so compare by suffix/resolved.
+ if got := strings.TrimSpace(out); got != work && !strings.HasSuffix(got, work) {
+ resolved, _ := filepath.EvalSymlinks(work)
+ if got != resolved {
+ t.Errorf("pwd = %q, want %q", got, work)
+ }
+ }
+ })
+
+ t.Run("relative cwd resolves under workDir", func(t *testing.T) {
+ if err := os.Mkdir(filepath.Join(work, "sub"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(work, "sub", "inner.txt"), []byte("y"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ res := execRunCommand(context.Background(),
+ capturedToolCall{arguments: map[string]any{"CommandLine": "ls", "Cwd": "sub"}},
+ work).(map[string]any)
+ if out, _ := res["Output"].(string); !strings.Contains(out, "inner.txt") {
+ t.Errorf("Output = %q, want it to list inner.txt (relative Cwd not resolved under workDir)", out)
+ }
+ })
+}
+
+func TestWorkspaceSystemInstruction(t *testing.T) {
+ if got := WorkspaceSystemInstruction(""); got != "" {
+ t.Errorf("empty workDir = %q, want empty", got)
+ }
+ got := WorkspaceSystemInstruction("/workspace")
+ if !strings.Contains(got, "/workspace") {
+ t.Errorf("instruction = %q, want it to mention the working directory", got)
+ }
+}
diff --git a/internal/harness/antigravityinteractions/workspace.go b/internal/harness/antigravityinteractions/workspace.go
new file mode 100644
index 0000000..744f016
--- /dev/null
+++ b/internal/harness/antigravityinteractions/workspace.go
@@ -0,0 +1,37 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package antigravityinteractions
+
+import (
+ "fmt"
+ "strings"
+)
+
+// WorkspaceSystemInstruction builds a system-instruction snippet that orients
+// the agent about its working directory.
+//
+// This complements the executor making WorkDir authoritative (see
+// AntigravityInteractionsConfig.WorkDir): the executor guarantees commands run
+// in the right place, while this tells the agent so it emits sensible paths
+// (relative to the workspace, not the process root "/"). Returns "" when
+// workDir is empty.
+func WorkspaceSystemInstruction(workDir string) string {
+ if strings.TrimSpace(workDir) == "" {
+ return ""
+ }
+ return fmt.Sprintf("Your working directory is %s. Run commands and resolve "+
+ "relative paths there unless you have a specific reason to use an "+
+ "absolute path elsewhere.", workDir)
+}
diff --git a/manifests/ax-deployment.yaml b/manifests/ax-deployment.yaml
index fda4286..072682f 100644
--- a/manifests/ax-deployment.yaml
+++ b/manifests/ax-deployment.yaml
@@ -97,7 +97,9 @@ spec:
- name: GOOGLE_CLOUD_PROJECT
value: "${GOOGLE_CLOUD_PROJECT}"
- name: AX_HARNESS_WORKDIR
- value: "/workspace"
+ value: "/durable/workspace"
+ - name: AX_DURABLE_DIR
+ value: "/durable"
# Content of manifests/ax.yaml
- name: AX_CONFIG_CONTENT
value: "${AX_CONFIG_CONTENT}"
@@ -105,8 +107,16 @@ spec:
httpGet:
path: /readyz
port: 8081
+ volumeMounts:
+ - name: durable
+ mountPath: /durable
+ volumes:
+ - name: durable
+ durableDir: {}
snapshotsConfig:
location: gs://${AX_SNAPSHOTS_BUCKET}/axinteractions/
+ onPause: Data
+ onCommit: Data
---
# ---------------------------------------------------------------------------
diff --git a/python/antigravity/harness_server.py b/python/antigravity/harness_server.py
index 99dd51e..bd2ecd9 100644
--- a/python/antigravity/harness_server.py
+++ b/python/antigravity/harness_server.py
@@ -25,7 +25,6 @@ import os
import pathlib
import re
import sys
-from typing import TypedDict
import grpc
from grpc_health.v1 import health, health_pb2, health_pb2_grpc
from google.protobuf.struct_pb2 import Struct
@@ -50,16 +49,28 @@ class HarnessConfigError(ValueError):
"""Raised when request harness_config is not a valid overlay."""
-class VertexKwargs(TypedDict, total=False):
- """Typed subset of LocalAgentConfig kwargs needed to enable Vertex AI.
+class ConversationIdError(ValueError):
+ """Raised when a request's conversation_id is unusable as a save_dir name."""
- `total=False` so {} is a valid value (returned when env does not request
- Vertex). When populated, all three keys are present.
- """
- vertex: bool
- project: str
- location: str
+def _validate_conversation_id(conversation_id: str) -> None:
+ """Guards conversation_id for safe use as a save_dir path component.
+
+ Rejects empty ids and path separators / "." / ".." so a request cannot
+ escape state_dir. The id-format contract (length, charset) is left to the
+ Antigravity harness (forwarded cascade_id) to avoid the layers drifting.
+ """
+ if not conversation_id:
+ raise ConversationIdError("conversation_id must be set")
+ if "/" in conversation_id or "\\" in conversation_id:
+ raise ConversationIdError(
+ "conversation_id must not contain a path separator, got "
+ f"{conversation_id!r}"
+ )
+ if conversation_id in (".", ".."):
+ raise ConversationIdError(
+ f"conversation_id must not be a path component, got {conversation_id!r}"
+ )
def _env_use_vertex() -> bool:
@@ -70,56 +81,17 @@ def _env_use_vertex() -> bool:
) or os.environ.get("GOOGLE_GENAI_USE_ENTERPRISE", "").lower() in ("true", "1")
-def _vertex_kwargs_from_env() -> VertexKwargs:
- """Returns LocalAgentConfig kwargs from GOOGLE_CLOUD_{PROJECT,LOCATION} env.
-
- Temporary override until AGY supports reading these env vars natively.
- Returns {} when env does not request Vertex (caller's programmatic config
- stands as-is). When env requests Vertex, returns VertexKwargs populated
- for passing to LocalAgentConfig.__init__ so AGY's @model_validator picks
- them up.
-
- Raises ValueError if env requests Vertex but project/location are missing.
-
- TODO: remove once AGY reads these env vars natively.
- """
- if not _env_use_vertex():
- return {}
-
- project = os.environ.get("GOOGLE_CLOUD_PROJECT", "")
- location = os.environ.get("GOOGLE_CLOUD_LOCATION", "")
-
- missing = [
- name
- for name, value in (
- ("project (set GOOGLE_CLOUD_PROJECT)", project),
- ("location (set GOOGLE_CLOUD_LOCATION)", location),
- )
- if not value
- ]
- if missing:
- raise ValueError(
- "Vertex AI backend requested but missing required config: "
- + ", ".join(missing)
- )
-
- print(f"Vertex AI backend configured: project={project} location={location}")
- return {"vertex": True, "project": project, "location": location}
-
-
def _build_default_config() -> LocalAgentConfig:
"""Builds the default agent config the sidecar serves on startup.
- Vertex configuration is read from env via `_vertex_kwargs_from_env`.
+ Credentials/backend come from the standard GenAI env vars, which the
+ AGY SDK reads natively as of google-antigravity 0.1.7.
TODO(#194): per-request `harness_config` will override fields of this
default on a per-conversation basis. Until then, every conversation uses
this config.
"""
- return LocalAgentConfig(
- system_instructions="You are a helpful agent.",
- **_vertex_kwargs_from_env(),
- )
+ return LocalAgentConfig(system_instructions="You are a helpful agent.")
def _has_credentials(config: AgentConfig | None) -> bool:
@@ -128,26 +100,25 @@ def _has_credentials(config: AgentConfig | None) -> bool:
Mirrors AGY's own validation. AGY accepts exactly these sources:
1. GEMINI_API_KEY environment variable (read directly by AGY).
2. config.api_key set programmatically (AI Studio path).
- 3. config.vertex=True + config.{project,location} set (Vertex path).
- 4. config.vertex=True + config.api_key set (Vertex Express Mode;
- covered by case 2).
+ 3. Vertex requested (config.vertex or GOOGLE_GENAI_USE_VERTEXAI /
+ GOOGLE_GENAI_USE_ENTERPRISE) + GOOGLE_CLOUD_{PROJECT,LOCATION}.
+ 4. Vertex requested + config.api_key set (Express Mode; covered by 2).
- Anything else (e.g. vertex=True without project/location) is rejected
- by AGY at request time, so we reject it here at startup too.
"""
# Check env - AGY reads GEMINI_API_KEY directly from os.environ.
if os.environ.get("GEMINI_API_KEY"):
return True
- # Check passed in config
- if config:
- if getattr(config, "api_key", None):
+ # AI Studio path via programmatic api_key.
+ if config and getattr(config, "api_key", None):
+ return True
+
+ # Vertex path: requested via config.vertex or env, project+location via env.
+ if _env_use_vertex() or bool(getattr(config, "vertex", False)):
+ if os.environ.get("GOOGLE_CLOUD_PROJECT") and os.environ.get(
+ "GOOGLE_CLOUD_LOCATION"
+ ):
return True
- if getattr(config, "vertex", False):
- # Vertex requires project + location, unless an api_key (Express
- # Mode) is set - but Express Mode would have returned True above.
- if getattr(config, "project", None) and getattr(config, "location", None):
- return True
return False
@@ -236,6 +207,24 @@ class AntigravityHarnessServiceServicer(ax_pb2_grpc.HarnessServiceServicer):
async def _run_turn(self, request):
print(f"[gRPC] Connect turn requested. conv_id={request.conversation_id}")
+ # Guard conversation_id for safe use as a save_dir path component
+ # below. The id-format contract (length, charset) is owned by the
+ # Antigravity harness via the forwarded cascade_id.
+ try:
+ _validate_conversation_id(request.conversation_id)
+ except ConversationIdError as exc:
+ yield ax_pb2.HarnessResponse(
+ conversation_id=request.conversation_id,
+ end=ax_pb2.HarnessEnd(
+ state=ax_pb2.STATE_FAILED,
+ error=ax_pb2.Error(
+ code=3, # INVALID_ARGUMENT
+ description=f"Invalid conversation_id: {exc}",
+ ),
+ ),
+ )
+ return
+
# 1. Retrieve and check messages
ax_messages = request.start.messages
if not ax_messages:
@@ -450,28 +439,6 @@ def _enhance_config_from_env(config) -> None:
config.skills_paths.append(skills_dir)
-def _resolve_localhost():
- """Ensure `localhost` resolves to 127.0.0.1.
-
- Substrate actors run under gVisor with no runtime-injected /etc/hosts.
- The antigravity SDK dials localharness at ws://localhost:<port>/
- and Python's resolver needs `localhost` in /etc/hosts.
- """
- try:
- try:
- with open("/etc/hosts", "r") as f:
- if "localhost" in f.read():
- return
- except FileNotFoundError:
- pass
- with open("/etc/hosts", "a") as f:
- f.write("127.0.0.1\tlocalhost\n")
- except OSError as e:
- print(
- f"WARNING: could not ensure localhost in /etc/hosts: {e}", file=sys.stderr
- )
-
-
def main():
parser = argparse.ArgumentParser(description="Antigravity gRPC Harness Server")
parser.add_argument(
@@ -501,10 +468,6 @@ def main():
print(f"ERROR: {e}", file=sys.stderr)
sys.exit(1)
- # This is a hack, on Agent Substrate /etc/hosts end up not
- # having this entry even if it's the OCI image.
- _resolve_localhost()
-
asyncio.run(
_serve(
args.host,
diff --git a/python/antigravity/harness_server_test.py b/python/antigravity/harness_server_test.py
index ab7af27..9591660 100644
--- a/python/antigravity/harness_server_test.py
+++ b/python/antigravity/harness_server_test.py
@@ -18,7 +18,9 @@ import pytest
import grpc
from python.proto import ax_pb2, ax_pb2_grpc, content_pb2
from python.antigravity.harness_server import AntigravityHarnessServiceServicer
+from python.antigravity.harness_server import ConversationIdError
from python.antigravity.harness_server import HarnessConfigError
+from python.antigravity.harness_server import _validate_conversation_id
from google.antigravity import LocalAgentConfig
@pytest.fixture
@@ -202,22 +204,27 @@ def test_has_credentials_missing(monkeypatch):
def test_has_credentials_vertex_requires_project_and_location(monkeypatch):
- """vertex=True alone is not enough; AGY requires project+location too."""
+ """Vertex needs project+location; as of AGY 0.1.7 these come from env."""
from python.antigravity.harness_server import _has_credentials
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
+ monkeypatch.setenv("GOOGLE_GENAI_USE_VERTEXAI", "True")
+ monkeypatch.delenv("GOOGLE_CLOUD_PROJECT", raising=False)
+ monkeypatch.delenv("GOOGLE_CLOUD_LOCATION", raising=False)
- cfg_vertex_only = LocalAgentConfig(system_instructions="test", vertex=True)
- assert _has_credentials(cfg_vertex_only) is False
+ cfg = LocalAgentConfig(system_instructions="test")
+ assert _has_credentials(cfg) is False
- cfg_vertex_proj_only = LocalAgentConfig(system_instructions="test", vertex=True, project="p")
- assert _has_credentials(cfg_vertex_proj_only) is False
+ monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "p")
+ assert _has_credentials(cfg) is False
- cfg_vertex_loc_only = LocalAgentConfig(system_instructions="test", vertex=True, location="us-central1")
- assert _has_credentials(cfg_vertex_loc_only) is False
+ monkeypatch.delenv("GOOGLE_CLOUD_PROJECT", raising=False)
+ monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "us-central1")
+ assert _has_credentials(cfg) is False
- cfg_vertex_full = LocalAgentConfig(system_instructions="test", vertex=True, project="p", location="us-central1")
- assert _has_credentials(cfg_vertex_full) is True
+ monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "p")
+ monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "us-central1")
+ assert _has_credentials(cfg) is True
def test_has_credentials_vertex_express_mode(monkeypatch):
@@ -398,73 +405,25 @@ def test_grpc_connect_buffering(mock_config, monkeypatch, tmp_path):
asyncio.run(_run())
-def test_vertex_kwargs_from_env_returns_kwargs(monkeypatch):
- """GOOGLE_GENAI_USE_VERTEXAI + GOOGLE_CLOUD_{PROJECT,LOCATION} -> kwargs dict."""
- from python.antigravity.harness_server import _vertex_kwargs_from_env
- monkeypatch.setenv("GOOGLE_GENAI_USE_VERTEXAI", "True")
- monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "env-project")
- monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "us-east1")
- assert _vertex_kwargs_from_env() == {
- "vertex": True,
- "project": "env-project",
- "location": "us-east1",
- }
-
-
-def test_vertex_kwargs_from_env_no_op_without_vertex(monkeypatch):
- """Without GOOGLE_GENAI_USE_VERTEXAI, returns empty dict."""
- from python.antigravity.harness_server import _vertex_kwargs_from_env
- monkeypatch.delenv("GOOGLE_GENAI_USE_VERTEXAI", raising=False)
- monkeypatch.delenv("GOOGLE_GENAI_USE_ENTERPRISE", raising=False)
- monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "should-be-ignored")
- monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "should-be-ignored")
- assert _vertex_kwargs_from_env() == {}
-
+def test_build_default_config_routes_to_vertex_via_env(monkeypatch):
+ """Bare default config + Vertex env vars routes to Vertex (AGY 0.1.7).
-def test_vertex_kwargs_from_env_raises_when_project_missing(monkeypatch):
- """Vertex requested with no project -> ValueError naming the env var."""
- from python.antigravity.harness_server import _vertex_kwargs_from_env
- monkeypatch.setenv("GOOGLE_GENAI_USE_VERTEXAI", "True")
- monkeypatch.delenv("GOOGLE_CLOUD_PROJECT", raising=False)
- monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "us-east1")
- with pytest.raises(ValueError, match="GOOGLE_CLOUD_PROJECT"):
- _vertex_kwargs_from_env()
-
-
-def test_vertex_kwargs_from_env_raises_when_location_missing(monkeypatch):
- """Vertex requested with no location -> ValueError naming the env var."""
- from python.antigravity.harness_server import _vertex_kwargs_from_env
- monkeypatch.setenv("GOOGLE_GENAI_USE_VERTEXAI", "True")
- monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "env-project")
- monkeypatch.delenv("GOOGLE_CLOUD_LOCATION", raising=False)
- with pytest.raises(ValueError, match="GOOGLE_CLOUD_LOCATION"):
- _vertex_kwargs_from_env()
-
-
-def test_vertex_kwargs_from_env_enterprise_alias(monkeypatch):
- """GOOGLE_GENAI_USE_ENTERPRISE is an alias for VERTEXAI."""
- from python.antigravity.harness_server import _vertex_kwargs_from_env
- monkeypatch.delenv("GOOGLE_GENAI_USE_VERTEXAI", raising=False)
- monkeypatch.setenv("GOOGLE_GENAI_USE_ENTERPRISE", "true")
- monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "ent-project")
- monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "us-central1")
- assert _vertex_kwargs_from_env() == {
- "vertex": True,
- "project": "ent-project",
- "location": "us-central1",
- }
-
-
-def test_build_default_config_picks_up_vertex_env(monkeypatch):
- """End-to-end: env vars flow through _build_default_config into LocalAgentConfig."""
+ The SDK hydrates vertex onto the config and project/location onto the
+ VertexEndpoint, so we assert the resolved endpoint rather than
+ config.{project,location}.
+ """
from python.antigravity.harness_server import _build_default_config
+ from google.antigravity import types
+
monkeypatch.setenv("GOOGLE_GENAI_USE_VERTEXAI", "True")
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "env-project")
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "us-east1")
cfg = _build_default_config()
assert cfg.vertex is True
- assert cfg.project == "env-project"
- assert cfg.location == "us-east1"
+ endpoint = cfg._build_shorthand_endpoint()
+ assert isinstance(endpoint, types.VertexEndpoint)
+ assert endpoint.project == "env-project"
+ assert endpoint.location == "us-east1"
def test_servicer_requires_default_config():
@@ -618,3 +577,76 @@ def test_harness_config_unknown_field_names_are_reported(mock_config, tmp_path):
assert "unknown config field(s): aaa_bad, zzz_bad" in msg
assert "system_instructions" not in msg
+
+
[email protected]("conv_id", [
+ "conv-1", # short ids are fine here; the harness owns the format contract
+ "conv-test",
+ "11111111-2222-3333-4444-555555555555",
+ "a", # single char, still a safe dir name
+])
+def test_validate_conversation_id_accepts_path_safe(conv_id):
+ # Should not raise: these are all usable as a save_dir path component.
+ _validate_conversation_id(conv_id)
+
+
[email protected](("conv_id", "error"), [
+ ("", "must be set"),
+ ("..", "path component"),
+ (".", "path component"),
+ ("../escape", "path separator"),
+ ("a/b", "path separator"),
+ ("nested/../conv", "path separator"),
+ ("back\\slash", "path separator"),
+])
+def test_validate_conversation_id_rejects_unsafe(conv_id, error):
+ with pytest.raises(ConversationIdError, match=error):
+ _validate_conversation_id(conv_id)
+
+
+def test_run_turn_unsafe_conversation_id_maps_to_invalid_argument(mock_config, tmp_path):
+ # An unsafe conversation_id is rejected at the boundary: the turn yields a
+ # single STATE_FAILED end frame with INVALID_ARGUMENT, before any agent runs.
+ async def _run():
+ servicer = AntigravityHarnessServiceServicer(mock_config, tmp_path)
+ req = ax_pb2.HarnessRequest(
+ conversation_id="../escape",
+ harness_id="antigravity",
+ start=ax_pb2.HarnessStart(
+ messages=[ax_pb2.Message(
+ role="user",
+ content=content_pb2.Content(text=content_pb2.TextContent(text="hi")),
+ )],
+ ),
+ )
+ responses = [r async for r in servicer._run_turn(req)]
+ assert len(responses) == 1
+ assert responses[0].end.state == ax_pb2.STATE_FAILED
+ assert responses[0].end.error.code == 3
+ assert "Invalid conversation_id" in responses[0].end.error.description
+
+ asyncio.run(_run())
+
+
+def test_run_turn_rejects_conversation_id_before_creating_save_dir(mock_config, tmp_path):
+ # Validation must happen before conversation_id is used as a storage
+ # directory name, so a rejected id leaves no directory behind under (or
+ # outside) state_dir.
+ async def _run():
+ servicer = AntigravityHarnessServiceServicer(mock_config, tmp_path)
+ req = ax_pb2.HarnessRequest(
+ conversation_id="../escape",
+ harness_id="antigravity",
+ start=ax_pb2.HarnessStart(
+ messages=[ax_pb2.Message(
+ role="user",
+ content=content_pb2.Content(text=content_pb2.TextContent(text="hi")),
+ )],
+ ),
+ )
+ responses = [r async for r in servicer._run_turn(req)]
+ assert len(responses) == 1
+ assert responses[0].end.state == ax_pb2.STATE_FAILED
+ assert list(tmp_path.iterdir()) == []
+
+ asyncio.run(_run())