Skip to content

armgit / ax

Public Imported from GitHub
0

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

Go

Embed python artifacts into ax (#276)

Jaana Dogan81c84f77b2b2
diff --git a/cmd/ax/harness.go b/cmd/ax/harness.go
index 8eaafae..19b62d8 100644
--- a/cmd/ax/harness.go
+++ b/cmd/ax/harness.go
@@ -87,14 +87,13 @@ func runHarness(cmd *cobra.Command, args []string) error {
"--host", harnessHost,
"--port", strconv.Itoa(harnessPort),
},
- Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
ReadyFunc: pythonsidecar.TCPReady(net.JoinHostPort("127.0.0.1", strconv.Itoa(harnessPort))),
}
sidecar := pythonsidecar.New(cfg)
- if err := sidecar.Start(cmd.Context()); err != nil {
+ if err := sidecar.Start(cmd.Context(), ""); err != nil {
return fmt.Errorf("failed to start antigravity harness server: %w", err)
}
log.Printf("forked antigravity harness server (pid %d) on %s:%d", sidecar.Pid(), harnessHost, harnessPort)
diff --git a/internal/harness/antigravity/antigravity.go b/internal/harness/antigravity/antigravity.go
index e1324d4..4f9829f 100644
--- a/internal/harness/antigravity/antigravity.go
+++ b/internal/harness/antigravity/antigravity.go
@@ -32,6 +32,7 @@ import (
"github.com/google/ax/internal/harness"
"github.com/google/ax/internal/pythonsidecar"
"github.com/google/ax/proto"
+ "github.com/google/ax/python"
"github.com/google/uuid"
)
@@ -66,13 +67,16 @@ func New(ctx context.Context, address string, autoStart bool) (*AntigravityHarne
"--host", host,
"--port", port,
},
- Stdin: os.Stdin,
- Stdout: os.Stdout,
- Stderr: os.Stderr,
ReadyFunc: pythonsidecar.TCPReady(address),
}
sidecar := pythonsidecar.New(cfg)
- if err := sidecar.Start(ctx); err != nil {
+ path, err := pythonsidecar.Setup(ctx, pythonsidecar.SetupOptions{
+ FS: python.FS,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("failed to setup antigravity harness server assets: %w", err)
+ }
+ if err := sidecar.Start(ctx, path); err != nil {
return nil, fmt.Errorf("failed to start antigravity harness server: %w", err)
}
h.sidecar = sidecar
diff --git a/internal/harness/antigravity/antigravity_test.go b/internal/harness/antigravity/antigravity_test.go
index d7111b5..39cfae1 100644
--- a/internal/harness/antigravity/antigravity_test.go
+++ b/internal/harness/antigravity/antigravity_test.go
@@ -17,10 +17,6 @@ package antigravity
import (
"bytes"
"context"
- "fmt"
- "net"
- "os"
- "path/filepath"
"strings"
"testing"
@@ -110,59 +106,3 @@ func TestNew_AutoStartFalse_NilSidecar(t *testing.T) {
t.Errorf("expected sidecar to be nil, got %v", h.sidecar)
}
}
-
-// TestNew_AutoStartTrue_StubServer_ForksSidecar drives the real fork +
-// TCPReady path with a tiny stub python.antigravity.harness_server on
-// PYTHONPATH, so we don't need the AGY SDK installed to test the wiring.
-// sidecar.Stop stops the forked process.
-func TestNew_AutoStartTrue_StubServer_ForksSidecar(t *testing.T) {
- stubPythonAntigravityModule(t)
-
- addr := fmt.Sprintf("127.0.0.1:%d", getFreePort(t))
- h, err := New(context.Background(), addr, true)
- if err != nil {
- t.Fatalf("New(autoStart=true): %v", err)
- }
- if h.sidecar == nil {
- t.Fatal("expected sidecar to be forked, got nil")
- }
- if !h.sidecar.IsRunning() {
- t.Fatal("expected sidecar to be running after New")
- }
- if err := h.sidecar.Stop(); err != nil {
- t.Errorf("sidecar.Stop: %v", err)
- }
- if h.sidecar.IsRunning() {
- t.Error("expected sidecar to be stopped")
- }
-}
-
-// stubPythonAntigravityModule writes a minimal python/antigravity/harness_server.py on PYTHONPATH that runs a stdlib socketserver.TCPServer so pythonsidecar.TCPReady succeeds without needing the real AGY SDK.
-func stubPythonAntigravityModule(t *testing.T) {
- t.Helper()
- root := t.TempDir()
- pkg := filepath.Join(root, "python", "antigravity")
- if err := os.MkdirAll(pkg, 0755); err != nil {
- t.Fatalf("mkdir stub: %v", err)
- }
- src := `import socketserver, sys
-port = int(sys.argv[sys.argv.index("--port")+1])
-socketserver.TCPServer.allow_reuse_address = True
-socketserver.TCPServer(("127.0.0.1", port), socketserver.BaseRequestHandler).serve_forever()
-`
- if err := os.WriteFile(filepath.Join(pkg, "harness_server.py"), []byte(src), 0644); err != nil {
- t.Fatalf("write stub: %v", err)
- }
- t.Setenv("PYTHONPATH", root)
-}
-
-func getFreePort(t *testing.T) int {
- t.Helper()
- l, err := net.Listen("tcp", "127.0.0.1:0")
- if err != nil {
- t.Fatalf("failed to get free port: %v", err)
- }
- port := l.Addr().(*net.TCPAddr).Port
- _ = l.Close()
- return port
-}
diff --git a/internal/pythonsidecar/setup.go b/internal/pythonsidecar/setup.go
new file mode 100644
index 0000000..777c184
--- /dev/null
+++ b/internal/pythonsidecar/setup.go
@@ -0,0 +1,133 @@
+// 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 pythonsidecar
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "io/fs"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+)
+
+// SetupOptions configures asset extraction and environment setup for a Python sidecar.
+type SetupOptions struct {
+ // FS is the embedded filesystem containing Python assets (e.g., python.FS). (Required)
+ FS fs.FS
+ // TargetDir is the directory on disk where assets will be extracted.
+ // If empty, it defaults to filepath.Join(os.UserHomeDir(), ".ax"). (Optional)
+ TargetDir string
+}
+
+// Setup extracts the embedded filesystem assets to TargetDir.
+// It returns TargetDir, which can be set as PythonPath in Config.
+func Setup(ctx context.Context, opts SetupOptions) (string, error) {
+ if opts.FS == nil {
+ return "", fmt.Errorf("SetupOptions.FS cannot be nil")
+ }
+
+ targetDir := opts.TargetDir
+ if targetDir == "" {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", fmt.Errorf("resolving home directory for python target dir: %w", err)
+ }
+ targetDir = filepath.Join(home, ".ax")
+ }
+
+ extractDir := filepath.Join(targetDir, "python")
+ reqPath := filepath.Join(extractDir, "antigravity", "requirements.txt")
+
+ result := targetDir + string(os.PathListSeparator) + extractDir
+
+ if err := extractFS(ctx, opts.FS, extractDir); err != nil {
+ return "", fmt.Errorf("failed to extract embedded assets: %w", err)
+ }
+
+ pkgPath, err := install(ctx, reqPath)
+ if err != nil {
+ return "", err
+ }
+
+ return result + string(os.PathListSeparator) + pkgPath, nil
+}
+
+func extractFS(ctx context.Context, filesystem fs.FS, destDir string) error {
+ return fs.WalkDir(filesystem, ".", func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+
+ if d.IsDir() {
+ return nil
+ }
+
+ destPath := filepath.Join(destDir, filepath.FromSlash(path))
+ rel, err := filepath.Rel(destDir, destPath)
+ if err != nil || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) || rel == ".." {
+ return fmt.Errorf("illegal file path in embedded FS: %s", path)
+ }
+
+ if err := os.MkdirAll(filepath.Dir(destPath), 0755); err != nil {
+ return fmt.Errorf("creating directory for %s: %w", destPath, err)
+ }
+
+ src, err := filesystem.Open(path)
+ if err != nil {
+ return fmt.Errorf("opening embedded file %s: %w", path, err)
+ }
+ defer src.Close()
+
+ info, err := d.Info()
+ mode := os.FileMode(0644)
+ if err == nil && info.Mode().Perm() != 0 {
+ mode = info.Mode().Perm() | 0200
+ }
+
+ _ = os.Chmod(destPath, 0644)
+
+ dst, err := os.OpenFile(destPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode)
+ if err != nil {
+ return fmt.Errorf("creating destination file %s: %w", destPath, err)
+ }
+
+ if _, err := io.Copy(dst, src); err != nil {
+ _ = dst.Close()
+ return fmt.Errorf("writing file %s: %w", destPath, err)
+ }
+
+ if err := dst.Close(); err != nil {
+ return fmt.Errorf("closing file %s: %w", destPath, err)
+ }
+
+ return nil
+ })
+}
+
+func install(ctx context.Context, reqPath string) (string, error) {
+ pkgDir := filepath.Join(filepath.Dir(reqPath), "site-packages")
+ cmd := exec.CommandContext(ctx, "python3", "-m", "pip", "install", "--extra-index-url", "https://pypi.org/simple", "--target", pkgDir, "-r", reqPath)
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ return "", fmt.Errorf("pip install failed for %s: %w\nOutput:\n%s", reqPath, err, string(out))
+ }
+ return pkgDir, nil
+}
diff --git a/internal/pythonsidecar/setup_test.go b/internal/pythonsidecar/setup_test.go
new file mode 100644
index 0000000..77a8d6a
--- /dev/null
+++ b/internal/pythonsidecar/setup_test.go
@@ -0,0 +1,114 @@
+// 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 pythonsidecar_test
+
+import (
+ "bytes"
+ "context"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "testing/fstest"
+ "time"
+
+ "github.com/google/ax/internal/pythonsidecar"
+ "github.com/google/ax/python"
+)
+
+func TestSetup_EmbeddedFS(t *testing.T) {
+ if _, err := fs.Stat(python.FS, "antigravity/__pycache__"); err == nil {
+ t.Errorf("expected antigravity/__pycache__ to be ignored when embedding, but it was found")
+ }
+
+ testFS := fstest.MapFS{
+ "antigravity/harness_server.py": &fstest.MapFile{Data: []byte("print('hello')")},
+ "antigravity/requirements.txt": &fstest.MapFile{Data: []byte("# empty requirements for test\n")},
+ "proto/ax_pb2.py": &fstest.MapFile{Data: []byte("print('proto')")},
+ }
+
+ targetDir := filepath.Join(t.TempDir(), "target")
+ opts := pythonsidecar.SetupOptions{
+ FS: testFS,
+ TargetDir: targetDir,
+ }
+
+ gotDir, err := pythonsidecar.Setup(context.Background(), opts)
+ if err != nil {
+ t.Fatalf("Setup() failed: %v", err)
+ }
+ if !strings.HasPrefix(gotDir, targetDir) {
+ t.Errorf("expected gotDir to start with targetDir=%q, got %q", targetDir, gotDir)
+ }
+ if !strings.Contains(gotDir, "python") {
+ t.Errorf("expected gotDir to contain extracted python directory in PYTHONPATH, got %q", gotDir)
+ }
+
+ // Verify files were extracted under TargetDir/python
+ harnessPath := filepath.Join(targetDir, "python", "antigravity", "harness_server.py")
+ if _, err := os.Stat(harnessPath); err != nil {
+ t.Errorf("expected file %s to exist, got stat error: %v", harnessPath, err)
+ }
+ protoPath := filepath.Join(targetDir, "python", "proto", "ax_pb2.py")
+ if _, err := os.Stat(protoPath); err != nil {
+ t.Errorf("expected file %s to exist, got stat error: %v", protoPath, err)
+ }
+
+ // Verify that subsequent Setup calls when TargetDir exists succeed without re-extracting
+ if _, err := pythonsidecar.Setup(context.Background(), opts); err != nil {
+ t.Fatalf("subsequent Setup() failed when TargetDir exists: %v", err)
+ }
+}
+
+func TestSidecar_PythonPath(t *testing.T) {
+ tmpDir := t.TempDir()
+ customPath := filepath.Join(tmpDir, "custom_python_path")
+ if err := os.MkdirAll(customPath, 0755); err != nil {
+ t.Fatalf("failed to create custom path: %v", err)
+ }
+
+ modulePath := filepath.Join(customPath, "path_check.py")
+ moduleContent := `
+import sys, os
+print("SYSPATH:" + str(sys.path))
+sys.exit(0)
+`
+ if err := os.WriteFile(modulePath, []byte(moduleContent), 0644); err != nil {
+ t.Fatalf("failed to write path_check module: %v", err)
+ }
+
+ var stdout bytes.Buffer
+ cfg := pythonsidecar.Config{
+ Module: "path_check",
+ Stdout: &stdout,
+ }
+
+ s := pythonsidecar.New(cfg)
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ if err := s.Start(ctx, customPath); err != nil {
+ t.Fatalf("Start() failed: %v", err)
+ }
+ if err := s.Wait(); err != nil {
+ t.Fatalf("Wait() failed: %v", err)
+ }
+
+ out := stdout.String()
+ if !strings.Contains(out, customPath) {
+ t.Errorf("expected sys.path to contain customPath, got output:\n%s", out)
+ }
+}
diff --git a/internal/pythonsidecar/sidecar.go b/internal/pythonsidecar/sidecar.go
index f4ffb0d..d02799b 100644
--- a/internal/pythonsidecar/sidecar.go
+++ b/internal/pythonsidecar/sidecar.go
@@ -21,7 +21,9 @@ import (
"fmt"
"io"
"net"
+ "os"
"os/exec"
+ "strings"
"sync"
"syscall"
"time"
@@ -33,8 +35,6 @@ type Config struct {
Module string
// Args contains any additional arguments to pass to the module. (Optional)
Args []string
- // Stdin redirects the sidecar's standard input. (Optional)
- Stdin io.Reader
// Stdout redirects the sidecar's standard output. (Optional)
Stdout io.Writer
// Stderr redirects the sidecar's standard error. (Optional)
@@ -44,10 +44,7 @@ type Config struct {
ReadyFunc func(ctx context.Context) error
}
-// TODO: AntigravityHarness should use pythonsidecar.
// TODO: Use /var/ax_agy_harness_service for communication instead of TCP.
-// TODO: Use go:embed to embed python/ directory into the ax binary.
-// TODO: Add a Setup method to extract embedded assets, pip install, etc.
// Sidecar manages the lifecycle of the underlying Python process.
type Sidecar struct {
@@ -71,7 +68,7 @@ func New(cfg Config) *Sidecar {
// Start launches the Python process and monitors its lifecycle in the background.
// If ReadyFunc is configured, Start blocks until the server is ready or the context expires.
// If the process fails to start or become ready, an error is returned immediately.
-func (s *Sidecar) Start(ctx context.Context) error {
+func (s *Sidecar) Start(ctx context.Context, pythonPath string) error {
s.mu.Lock()
if s.running {
s.mu.Unlock()
@@ -83,15 +80,32 @@ func (s *Sidecar) Start(ctx context.Context) error {
return fmt.Errorf("Module cannot be empty")
}
- // Prepare arguments: python3 -u -m module [args...]
+ // Prepare arguments: python -u -m module [args...]
// -u forces unbuffered stdout/stderr so logs stream to Go instantly
fullArgs := append([]string{"-u", "-m", s.cfg.Module}, s.cfg.Args...)
cmd := exec.CommandContext(ctx, "python3", fullArgs...)
-
- if s.cfg.Stdin != nil {
- cmd.Stdin = s.cfg.Stdin
+ if pythonPath != "" {
+ env := append([]string(nil), os.Environ()...)
+ var found bool
+ for i, kv := range env {
+ if strings.HasPrefix(kv, "PYTHONPATH=") {
+ existing := strings.TrimPrefix(kv, "PYTHONPATH=")
+ if existing != "" {
+ env[i] = "PYTHONPATH=" + pythonPath + string(os.PathListSeparator) + existing
+ } else {
+ env[i] = "PYTHONPATH=" + pythonPath
+ }
+ found = true
+ break
+ }
+ }
+ if !found {
+ env = append(env, "PYTHONPATH="+pythonPath)
+ }
+ cmd.Env = env
}
+
if s.cfg.Stdout != nil {
cmd.Stdout = s.cfg.Stdout
}
diff --git a/internal/pythonsidecar/sidecar_test.go b/internal/pythonsidecar/sidecar_test.go
index f147feb..3052f41 100644
--- a/internal/pythonsidecar/sidecar_test.go
+++ b/internal/pythonsidecar/sidecar_test.go
@@ -45,7 +45,7 @@ func TestSidecar_ConfigValidation(t *testing.T) {
t.Run("empty Module", func(t *testing.T) {
s := pythonsidecar.New(pythonsidecar.Config{})
- err := s.Start(ctx)
+ err := s.Start(ctx, "")
if err == nil || !strings.Contains(err.Error(), "Module cannot be empty") {
t.Fatalf("expected error about empty Module, got %v", err)
}
@@ -65,7 +65,6 @@ sys.exit(0)
t.Fatalf("failed to write module: %v", err)
}
- t.Setenv("PYTHONPATH", tmpDir)
var stdout, stderr bytes.Buffer
cfg := pythonsidecar.Config{
Module: "test_module",
@@ -77,7 +76,7 @@ sys.exit(0)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
- if err := s.Start(ctx); err != nil {
+ if err := s.Start(ctx, tmpDir); err != nil {
t.Fatalf("Start() failed: %v", err)
}
@@ -96,7 +95,6 @@ sys.exit(0)
}
}
-
func TestSidecar_ModuleServerWithTCPReady(t *testing.T) {
port := getFreePort(t)
addr := fmt.Sprintf("127.0.0.1:%d", port)
@@ -111,7 +109,7 @@ func TestSidecar_ModuleServerWithTCPReady(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
- if err := s.Start(ctx); err != nil {
+ if err := s.Start(ctx, ""); err != nil {
t.Fatalf("Start() with TCPReady failed: %v", err)
}
@@ -147,7 +145,7 @@ func TestSidecar_ReadinessFailureOnPrematureExit(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
- err := s.Start(ctx)
+ err := s.Start(ctx, "")
if err == nil {
t.Fatalf("expected Start() to fail when process exits prematurely")
}
diff --git a/python/python.go b/python/python.go
new file mode 100644
index 0000000..faa502e
--- /dev/null
+++ b/python/python.go
@@ -0,0 +1,24 @@
+// 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 python embeds the Python directory assets (such as antigravity and proto modules)
+// for use by the sidecar and harnesses.
+package python
+
+import "embed"
+
+// FS contains the embedded python/ directory assets.
+//
+//go:embed antigravity proto antigravity/_*.py proto/_*.py
+var FS embed.FS