Skip to content

armgit / ax

Public Imported from GitHub
0

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

Go

Feature/gke sandbox agent (#81)

JoyceLiu786146bba98e
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..14a1425
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,8 @@
+.git
+.idea
+.vscode
+*.log
+eventlog/
+tmp/
+node_modules/
+bin/
diff --git a/.gitignore b/.gitignore
index 08390a3..b416f85 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,3 +4,7 @@ eventlog/*
local_agent
remote_agent
*.log
+gar-bin
+google-cloud-cli-darwin-arm.tar.gz
+google-cloud-sdk/
+test-sandbox-config.yaml
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..aedd6c2
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,47 @@
+# This Dockerfile builds the container image for the 'uppercase' Sandbox Agent.
+# The resulting image is pushed to Artifact Registry and referenced by the
+# SandboxTemplate manifest to be executed dynamically via GKE Agent Sandbox.
+#
+# For more details on GKE Agent Sandbox container requirements, see:
+# https://docs.cloud.google.com/kubernetes-engine/docs/how-to/agent-sandbox
+
+# Build stage
+# TODO: consider other options instead of Alpine
+FROM golang:alpine AS builder
+
+# Install build dependencies
+RUN apk add --no-cache git make build-base
+
+WORKDIR /app
+
+# Download dependencies first to cache them
+COPY go.mod go.sum ./
+RUN go mod download
+
+# Copy source code
+COPY . .
+
+# Build the uppercase agent
+RUN go build -o /app/bin/uppercase ./examples/sandbox_agent
+
+# Runtime stage
+# TODO: consider other options instead of Alpine
+FROM alpine:3.19
+
+# Install certificates for secure gRPC and external calls
+RUN apk add --no-cache ca-certificates tzdata
+
+WORKDIR /app
+
+# Copy the built binary
+COPY --from=builder /app/bin/uppercase /usr/local/bin/uppercase
+
+# Create a non-root user matching expected Kubernetes security context best practices
+RUN addgroup -S gar && adduser -S gar -G gar
+USER gar
+
+# Expose standard remote agent port
+EXPOSE 8494
+
+# Set default command
+ENTRYPOINT ["/usr/local/bin/uppercase"]
diff --git a/Makefile b/Makefile
index 45d1e01..573a313 100644
--- a/Makefile
+++ b/Makefile
@@ -56,3 +56,8 @@ deps:
@go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
@go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
@echo "Dependencies installed!"
+
+# Build Sandbox Router Static Binary
+build-router:
+ @echo "Building sandbox-router Linux binary..."
+ @GOOS=linux CGO_ENABLED=0 GOARCH=amd64 go build -o sandbox-router ./cmd/sandbox-router
diff --git a/README.md b/README.md
index 24c56e5..87a9349 100644
--- a/README.md
+++ b/README.md
@@ -224,15 +224,23 @@ health_check:
# Health check interval for agents
interval: 30s
-# Remote agents to register on startup
+# Agents to register on startup
agents:
- type: "remote"
- id: "text-processing-agent"
- name: "Text Processing Agent"
- description: "An agent for text processing"
- address: "localhost:50051"
- metadata:
- version: "1.0"
+ remote:
+ id: "text-processing-agent"
+ name: "Text Processing Agent"
+ description: "An agent for text processing"
+ address: "localhost:50051"
+ metadata:
+ version: "1.0"
+ - type: "sandbox"
+ sandbox:
+ id: "uppercase-sandbox-agent"
+ name: "Sandbox Uppercase Agent"
+ description: "A secure, ephemeral cloud container for executing uppercase transformations"
+ sandbox_template_ref: "uppercase-agent-template"
+
```
Example:
@@ -300,6 +308,110 @@ See `examples/remote_agent/main.go` for a complete implementation.
See `examples/remote_agent/main.go` for a complete implementation.
+### Sandbox Agent (GKE Integration)
+
+GAR supports dynamically provisioning secure, isolated agents on Google Kubernetes Engine (GKE) via the [Agent Sandbox](https://github.com/kubernetes-sigs/agent-sandbox) feature. When a component requires a Sandbox Agent, the GAR server requests a temporary remote agent container in the cluster, establishes a secure connection locally (using port-forwarding via a proxy service), and cleans up the sandbox claim automatically upon closing.
+
+#### Architecture
+Traffic flows from Localhost -> `kubectl port-forward` -> Router Service -> Sandbox Pod. This requires no public IP and allows your local development environment to orchestrate sandboxes running on remote GKE clusters, Kind, or Minikube.
+
+#### Prerequisites
+- A running Kubernetes cluster.
+- The [Agent Sandbox Controller](https://github.com/kubernetes-sigs/agent-sandbox?tab=readme-ov-file#installation) installed.
+- `kubectl` installed and configured locally.
+
+#### Setup: Deploying the Router
+Before using Sandbox Agents remotely, you must deploy the `sandbox-router` into your cluster. This router proxies traffic securely to the isolated gVisor pods (direct port-forwarding to gVisor pods is not supported by Kubernetes due to netstack isolation).
+
+1. Cross-compile the proxy binary via Make and inject it into an Alpine Pod:
+```bash
+# Build the router for linux and copy it into the cluster
+make build-router
+kubectl apply -f cmd/sandbox-router/sandbox-router.yaml
+kubectl wait --for=condition=Ready pod -l app=sandbox-router --timeout=60s
+POD_NAME=$(kubectl get pods -l app=sandbox-router -o jsonpath='{.items[0].metadata.name}')
+kubectl cp sandbox-router $POD_NAME:/app/sandbox-router
+kubectl exec $POD_NAME -- touch /app/.done
+```
+
+2. Expose it as a service:
+```bash
+kubectl expose deployment sandbox-router --port=8080 --target-port=8080
+```
+
+To use a Sandbox Agent, specify it in your `gar.yaml` configuration using the `sandbox` type:
+
+```yaml
+agents:
+ - type: "sandbox"
+ sandbox:
+ id: "my-sandbox-agent"
+ name: "Sandbox Worker"
+ description: "An ephemeral sandbox processor"
+ sandbox_template_ref: "your-gke-sandbox-template-name"
+ container_port: 8494
+```
+
+#### End-to-End Example (Uppercase Agent)
+
+GAR provides a complete example of a Sandbox Agent in `examples/sandbox_agent/`. It receives text input via gRPC and returns the same text converted to uppercase.
+
+You can test this agent end-to-end using the `gar` binary, which exercises the full `SandboxAgent` lifecycle (provisioning, port-forwarding, and remote execution).
+
+**1. Build the Agent Image**
+From the root of the GAR repository:
+```bash
+docker build -t gar-uppercase:latest -f examples/sandbox_agent/Dockerfile .
+```
+
+**2. Publish Image to Registry**
+When deploying to a cluster, you can host the agent container image in **any standard container registry** accessible by your Kubernetes cluster (e.g., Docker Hub, Google Artifact Registry, GitHub Container Registry).
+- For local testing (Minikube/Kind), load the image directly: `minikube image load gar-uppercase:latest`
+- For production, update the `image` field in `examples/sandbox_agent/sandbox-template.yaml` to your full registry path.
+
+Once the image is available, register the SandboxTemplate:
+```bash
+kubectl apply -f examples/sandbox_agent/sandbox-template.yaml
+```
+
+**3. Configure gar.yaml**
+Ensure your `gar.yaml` references this sandbox agent:
+```yaml
+agents:
+ - id: "uppercase-agent"
+ type: "sandbox"
+ sandbox:
+ sandbox_template_ref: "uppercase-agent-template"
+ container_port: 8494
+```
+
+**4. Run the GAR Server**
+```bash
+gar serve --config gar.yaml
+```
+
+**5. Trigger the Agent**
+In a separate terminal:
+```bash
+gar trigger --prompt "use the uppercase-agent to convert 'hello world'"
+```
+
+The system will dynamically create a `SandboxClaim`, establish a connection via `kubectl port-forward`, execute the code securely, and return the result.
+
+
+
+#### Viewing Sandbox Logs
+If you want to monitor the internal agent output or see if your gVisor sandbox received the physical gRPC requests:
+1. List the active sandbox Pods (named after your session IDs):
+ ```bash
+ kubectl get pods -n default
+ ```
+2. Fetch the logs for your specific sandbox claim:
+ ```bash
+ kubectl logs gar-claim-uppercase-<hash_id>
+ # To tail live logs: kubectl logs -f gar-claim-uppercase-<hash_id>
+ ```
+
### Remote Python Agent
Python agents can be built using the GAR agent framework. First, install dependencies and generate Python gRPC code:
@@ -337,3 +449,5 @@ gar trigger \
## License
Apache 2.0
+
+
diff --git a/agent/remote.go b/agent/remote.go
index 13b1b69..6fab77e 100644
--- a/agent/remote.go
+++ b/agent/remote.go
@@ -95,9 +95,8 @@ func (a *RemoteAgent) connect() error {
// Process handles processing of input content with the remote agent.
func (a *RemoteAgent) Process(ctx context.Context, sessionID string, incoming *proto.ProcessRequest, handler OutputHandler) error {
- // Add session_id to gRPC metadata
- md := metadata.Pairs("session-id", sessionID)
- ctx = metadata.NewOutgoingContext(ctx, md)
+ // Add session_id to gRPC metadata without overwriting existing metadata hooks (e.g. sandbox routers)
+ ctx = metadata.AppendToOutgoingContext(ctx, "session-id", sessionID)
stream, err := a.client.Process(ctx)
if err != nil {
diff --git a/agent/sandbox.go b/agent/sandbox.go
new file mode 100644
index 0000000..9fd6ab9
--- /dev/null
+++ b/agent/sandbox.go
@@ -0,0 +1,258 @@
+// 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 agent
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "net"
+ "os"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/google/gar/internal/sandboxclient"
+ "github.com/google/gar/proto"
+ "google.golang.org/grpc/metadata"
+)
+
+type SandboxAgent struct {
+ client *sandboxclient.Client
+ config SandboxAgentConfig
+ inCluster bool
+ poolName string
+
+ claimMu sync.Mutex
+ activeClaims map[string]struct{}
+}
+
+// SandboxAgentConfig configures a sandbox agent client.
+type SandboxAgentConfig struct {
+ ID string
+ SandboxTemplateRef string
+
+ ContainerPort int
+ WarmPoolSize int
+ UseRouter bool
+ RouterAddress string
+}
+
+// NewSandboxAgent creates a new sandbox agent logic coordinator.
+func NewSandboxAgent(ctx context.Context, config SandboxAgentConfig) (*SandboxAgent, error) {
+ namespace := "default"
+ //TODO(lhuan): allow setup in yaml
+ if ns := os.Getenv("POD_NAMESPACE"); ns != "" {
+ namespace = ns
+ }
+
+ client, err := sandboxclient.NewClient(namespace)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create sandbox client: %w", err)
+ }
+
+ return newSandboxAgentWithClient(ctx, client, config)
+}
+
+// newSandboxAgentWithClient allows customizing the client instantiation.
+func newSandboxAgentWithClient(ctx context.Context, client *sandboxclient.Client, config SandboxAgentConfig) (*SandboxAgent, error) {
+ agent := &SandboxAgent{
+ client: client,
+ config: config,
+ inCluster: os.Getenv("KUBERNETES_SERVICE_HOST") != "",
+ activeClaims: make(map[string]struct{}),
+ }
+
+ // Create a SandboxWarmPool if configured
+ if config.WarmPoolSize > 0 {
+ poolName := fmt.Sprintf("gar-pool-%s", config.ID)
+ agent.poolName = poolName
+
+ // TODO: This forced recreation can cause a race condition if multiple
+ // GAR controller instances are running in the same namespace with the
+ // same agent ID. Consider using a 'Get or Create' pattern with
+ // version/generation checks for multi-instance deployments.
+ _ = client.DeleteWarmPool(ctx, poolName)
+ if err := client.CreateWarmPool(ctx, poolName, config.SandboxTemplateRef, config.WarmPoolSize); err != nil {
+ return nil, fmt.Errorf("failed to create SandboxWarmPool: %w", err)
+ }
+ }
+
+ return agent, nil
+}
+
+// HealthCheck always returns nil for ephemeral agents since health is checked during Process.
+func (a *SandboxAgent) HealthCheck(ctx context.Context) error {
+// TODO: implement proper health check logic for sandbox agents.
+ return nil
+}
+
+func (a *SandboxAgent) Process(ctx context.Context, sessionID string, req *proto.ProcessRequest, handler OutputHandler) error {
+ // Use the sessionID deterministically so interactive sessions reuse the same sandbox pod,
+ // rather than spawning a new pod for every exchanged message.
+ safeSessionID := strings.ReplaceAll(sessionID, "-", "")
+ if len(safeSessionID) > 20 {
+ safeSessionID = safeSessionID[:20] // Keep it short for k8s names
+ }
+ claimName := fmt.Sprintf("gar-claim-%s-%s", a.config.ID, safeSessionID)
+
+ // 1. Create Ephemeral SandboxClaim (Ignore AlreadyExists errors if it's already created this session)
+ if err := a.client.CreateClaim(ctx, claimName, a.config.SandboxTemplateRef); err != nil {
+ if !strings.Contains(err.Error(), "already exists") {
+ return fmt.Errorf("failed to create SandboxClaim: %w", err)
+ }
+ }
+
+ // We track the claim so `Close()` deletes it at the end of the session.
+ // If we deleted it here, interactive shells would lose the pod.
+ a.claimMu.Lock()
+ a.activeClaims[claimName] = struct{}{}
+ a.claimMu.Unlock()
+
+ // Wait for Sandbox to bound and get the warm pool pod selector
+ selector, err := a.client.WaitForSandbox(ctx, claimName)
+ if err != nil {
+ return err
+ }
+
+ // Wait for the Sandbox to become Ready so its DNS record is populated
+ if err := a.client.WaitForSandboxReady(ctx, claimName); err != nil {
+ log.Printf("Warning: failed to wait for sandbox readiness: %v", err)
+ }
+
+ // 2. Setup Connection (Direct or Router)
+ targetPort := a.config.ContainerPort
+ if targetPort == 0 {
+ targetPort = 8494
+ }
+
+ var remoteAddr string
+ var pfCancel func()
+ var errPF error
+
+ namespace := "default"
+ if ns := os.Getenv("POD_NAMESPACE"); ns != "" {
+ namespace = ns
+ }
+
+ if a.config.UseRouter {
+ // Use Sandbox Router
+ routerAddr := a.config.RouterAddress
+ if routerAddr == "" {
+ routerAddr = fmt.Sprintf("sandbox-router-svc.%s.svc.cluster.local:8080", namespace)
+ }
+
+ if !a.inCluster {
+ // Local testing: port-forward the router service
+ localPort, err := findAvailablePort()
+ if err != nil {
+ return err
+ }
+ pfCancel, errPF = a.client.PortForwardRouter(ctx, localPort, 8080)
+ if errPF != nil {
+ return fmt.Errorf("router port-forward failed: %w", errPF)
+ }
+ remoteAddr = fmt.Sprintf("127.0.0.1:%d", localPort)
+ } else {
+ remoteAddr = routerAddr
+ }
+
+ // Add routing headers
+ ctx = metadata.AppendToOutgoingContext(ctx,
+ "x-sandbox-id", claimName,
+ "x-sandbox-namespace", namespace,
+ "x-sandbox-port", fmt.Sprintf("%d", targetPort),
+ )
+ } else {
+ // Direct to Pod
+ if !a.inCluster {
+ localPort, err := findAvailablePort()
+ if err != nil {
+ return err
+ }
+ pfCancel, errPF = a.client.PortForward(ctx, claimName, selector, localPort, targetPort)
+ if errPF != nil {
+ return fmt.Errorf("port-forward failed: %w", errPF)
+ }
+ remoteAddr = fmt.Sprintf("127.0.0.1:%d", localPort)
+ log.Printf("Sandbox port-forward established at: %s", remoteAddr)
+ } else {
+ // This case is rare for direct-to-pod in cluster (usually uses service)
+ // But for now, we'll assume the service is named after the claim
+ remoteAddr = fmt.Sprintf("%s.%s.svc.cluster.local:%d", claimName, namespace, targetPort)
+ }
+ }
+
+ if pfCancel != nil {
+ defer pfCancel()
+ }
+
+ // Connect to the agent (either direct or via router)
+ remoteAgent, err := NewRemoteAgent(RemoteAgentConfig{
+ Address: remoteAddr,
+ // TODO: allow setup reconnect and max retires in yaml.
+ // TODO: implement dynamic mTLS or PSK interceptors to secure the unauthenticated gRPC Sandbox transport
+ Reconnect: true,
+ MaxRetries: 3,
+ })
+ if err != nil {
+ return fmt.Errorf("failed to create remote agent connection: %w", err)
+ }
+ defer remoteAgent.Close()
+
+ // Forward the request!
+ return remoteAgent.Process(ctx, sessionID, req, handler)
+}
+
+func findAvailablePort() (int, error) {
+ addr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:0")
+ if err != nil {
+ return 0, fmt.Errorf("failed to resolve local address: %w", err)
+ }
+ l, err := net.ListenTCP("tcp", addr)
+ if err != nil {
+ return 0, fmt.Errorf("failed to bind to local port: %w", err)
+ }
+ defer l.Close()
+ return l.Addr().(*net.TCPAddr).Port, nil
+}
+
+// Close gracefully deletes the SandboxWarmPool if one was created,
+// and shreds all active SandboxClaims generated by this agent during interactive sessions.
+func (a *SandboxAgent) Close() error {
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ var errs []string
+
+ a.claimMu.Lock()
+ for claimName := range a.activeClaims {
+ if err := a.client.DeleteClaim(ctx, claimName); err != nil {
+ errs = append(errs, fmt.Sprintf("failed to delete claim %q: %v", claimName, err))
+ }
+ }
+ a.claimMu.Unlock()
+
+ if a.poolName != "" {
+ if err := a.client.DeleteWarmPool(ctx, a.poolName); err != nil {
+ errs = append(errs, fmt.Sprintf("failed to delete warm pool %q: %v", a.poolName, err))
+ }
+ }
+
+ if len(errs) > 0 {
+ return fmt.Errorf("cleanup errors: %s", strings.Join(errs, "; "))
+ }
+ return nil
+}
diff --git a/cmd/gar/serve.go b/cmd/gar/serve.go
index 050e2e1..10183e5 100644
--- a/cmd/gar/serve.go
+++ b/cmd/gar/serve.go
@@ -126,14 +126,16 @@ func newControllerFromConfig(ctx context.Context, cfg *config.Config) (*controll
}
for _, agentCfg := range cfg.Agents {
- switch agentCfg.Type {
- case "remote":
- cfg := agentCfg.RemoteAgentConfig
- if err := c.Registry().RegisterRemote(cfg); err != nil {
- return nil, fmt.Errorf("failed to register remote agent %s: %w", cfg.ID, err)
+ if agentCfg.SandboxAgentConfig != nil {
+ if err := c.Registry().RegisterSandbox(ctx, *agentCfg.SandboxAgentConfig); err != nil {
+ return nil, fmt.Errorf("failed to register sandbox agent %s: %w", agentCfg.SandboxAgentConfig.ID, err)
}
- default:
- return nil, fmt.Errorf("unknown agent type: %s", agentCfg.Type)
+ } else if agentCfg.RemoteAgentConfig != nil {
+ if err := c.Registry().RegisterRemote(*agentCfg.RemoteAgentConfig); err != nil {
+ return nil, fmt.Errorf("failed to register remote agent %s: %w", agentCfg.RemoteAgentConfig.ID, err)
+ }
+ } else {
+ return nil, fmt.Errorf("invalid agent configuration: must specify 'sandbox' or 'remote'")
}
}
diff --git a/cmd/sandbox-router/main.go b/cmd/sandbox-router/main.go
new file mode 100644
index 0000000..982e1af
--- /dev/null
+++ b/cmd/sandbox-router/main.go
@@ -0,0 +1,111 @@
+// 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 main
+
+import (
+ "crypto/tls"
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "net/http"
+ "net/http/httputil"
+ "net/url"
+ "os"
+
+ "golang.org/x/net/http2"
+ "golang.org/x/net/http2/h2c"
+)
+
+func main() {
+ port := os.Getenv("PORT")
+ if port == "" {
+ port = "8080"
+ }
+
+ director := func(req *http.Request) {
+ sandboxID := req.Header.Get("X-Sandbox-Id")
+ sandboxNamespace := req.Header.Get("X-Sandbox-Namespace")
+ sandboxPort := req.Header.Get("X-Sandbox-Port")
+
+ if sandboxID == "" {
+ sandboxID = req.Header.Get("x-sandbox-id")
+ }
+ if sandboxNamespace == "" {
+ sandboxNamespace = req.Header.Get("x-sandbox-namespace")
+ }
+ if sandboxPort == "" {
+ sandboxPort = req.Header.Get("x-sandbox-port")
+ }
+
+ if sandboxID == "" || sandboxNamespace == "" || sandboxPort == "" {
+ log.Printf("Missing required headers: ID=%v, Namespace=%v, Port=%v", sandboxID, sandboxNamespace, sandboxPort)
+ return
+ }
+
+ targetURL := fmt.Sprintf("http://%s.%s.svc.cluster.local:%s", sandboxID, sandboxNamespace, sandboxPort)
+ target, err := url.Parse(targetURL)
+ if err != nil {
+ log.Printf("Failed to parse target URL %s: %v", targetURL, err)
+ return
+ }
+
+ log.Printf("Proxying request %s to %s", req.URL.Path, targetURL)
+
+ req.URL.Scheme = target.Scheme
+ req.URL.Host = target.Host
+ req.Host = target.Host
+ }
+
+ proxy := &httputil.ReverseProxy{
+ Director: director,
+ Transport: &http2.Transport{
+ AllowHTTP: true,
+ DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
+ return net.Dial(network, addr)
+ },
+ },
+ ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
+ log.Printf("Proxy error for %s: %v", r.URL.Path, err)
+ http.Error(w, "Proxy error: "+err.Error(), http.StatusBadGateway)
+ },
+ ModifyResponse: func(res *http.Response) error {
+ if res.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(res.Body)
+ log.Printf("Backend returned error %d: %s", res.StatusCode, string(body))
+ }
+ return nil
+ },
+ }
+
+ handler := func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/healthz" {
+ w.WriteHeader(http.StatusOK)
+ w.Write([]byte("ok\n"))
+ return
+ }
+ proxy.ServeHTTP(w, r)
+ }
+
+ server := &http.Server{
+ Addr: ":" + port,
+ Handler: h2c.NewHandler(http.HandlerFunc(handler), &http2.Server{}),
+ }
+
+ log.Printf("Starting sandbox router on port %s...", port)
+ if err := server.ListenAndServe(); err != nil {
+ log.Fatalf("Server failed: %v", err)
+ }
+}
diff --git a/cmd/sandbox-router/sandbox-router.yaml b/cmd/sandbox-router/sandbox-router.yaml
new file mode 100644
index 0000000..b92c9ef
--- /dev/null
+++ b/cmd/sandbox-router/sandbox-router.yaml
@@ -0,0 +1,35 @@
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: sandbox-router
+ labels:
+ app: sandbox-router
+spec:
+ replicas: 1
+ selector:
+ matchLabels:
+ app: sandbox-router
+ template:
+ metadata:
+ labels:
+ app: sandbox-router
+ spec:
+ containers:
+ - name: router
+ # TODO: consider other options instead of Alpine
+ image: alpine:latest
+ command: ["/bin/sh", "-c"]
+ args:
+ - |
+ while [ ! -f /app/.done ]; do sleep 1; done
+ echo "Starting router..."
+ chmod +x /app/sandbox-router
+ exec /app/sandbox-router
+ ports:
+ - containerPort: 8080
+ volumeMounts:
+ - name: app-vol
+ mountPath: /app
+ volumes:
+ - name: app-vol
+ emptyDir: {}
diff --git a/examples/remote_agent/main.go b/examples/remote_agent/main.go
index f0d9f0b..2c55769 100644
--- a/examples/remote_agent/main.go
+++ b/examples/remote_agent/main.go
@@ -20,7 +20,6 @@ import (
"io"
"log"
"net"
- "strings"
"google.golang.org/grpc"
@@ -50,11 +49,15 @@ func (s *server) Process(stream proto.AgentService_ProcessServer) error {
var contents []*proto.Content
for _, input := range incoming.Contents {
+ textContent := input.GetText()
+ if textContent == nil {
+ continue
+ }
contents = append(contents, &proto.Content{
Role: "assistant",
Content: &proto.Content_Text{
Text: &proto.TextContent{
- Text: strings.ToUpper(input.GetText().Text),
+ Text: "Remote Prefix: " + textContent.Text,
},
},
})
diff --git a/examples/sandbox_agent/Dockerfile b/examples/sandbox_agent/Dockerfile
new file mode 100644
index 0000000..aedd6c2
--- /dev/null
+++ b/examples/sandbox_agent/Dockerfile
@@ -0,0 +1,47 @@
+# This Dockerfile builds the container image for the 'uppercase' Sandbox Agent.
+# The resulting image is pushed to Artifact Registry and referenced by the
+# SandboxTemplate manifest to be executed dynamically via GKE Agent Sandbox.
+#
+# For more details on GKE Agent Sandbox container requirements, see:
+# https://docs.cloud.google.com/kubernetes-engine/docs/how-to/agent-sandbox
+
+# Build stage
+# TODO: consider other options instead of Alpine
+FROM golang:alpine AS builder
+
+# Install build dependencies
+RUN apk add --no-cache git make build-base
+
+WORKDIR /app
+
+# Download dependencies first to cache them
+COPY go.mod go.sum ./
+RUN go mod download
+
+# Copy source code
+COPY . .
+
+# Build the uppercase agent
+RUN go build -o /app/bin/uppercase ./examples/sandbox_agent
+
+# Runtime stage
+# TODO: consider other options instead of Alpine
+FROM alpine:3.19
+
+# Install certificates for secure gRPC and external calls
+RUN apk add --no-cache ca-certificates tzdata
+
+WORKDIR /app
+
+# Copy the built binary
+COPY --from=builder /app/bin/uppercase /usr/local/bin/uppercase
+
+# Create a non-root user matching expected Kubernetes security context best practices
+RUN addgroup -S gar && adduser -S gar -G gar
+USER gar
+
+# Expose standard remote agent port
+EXPOSE 8494
+
+# Set default command
+ENTRYPOINT ["/usr/local/bin/uppercase"]
diff --git a/examples/sandbox_agent/main.go b/examples/sandbox_agent/main.go
new file mode 100644
index 0000000..2624f09
--- /dev/null
+++ b/examples/sandbox_agent/main.go
@@ -0,0 +1,108 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "os"
+ "os/signal"
+ "strings"
+ "syscall"
+
+ "github.com/google/gar/proto"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/reflection"
+)
+
+type server struct {
+ proto.UnimplementedAgentServiceServer
+}
+
+func (s *server) HealthCheck(ctx context.Context, req *proto.HealthCheckRequest) (*proto.HealthCheckResponse, error) {
+ return &proto.HealthCheckResponse{Healthy: true, Message: "upper_case_agent is running"}, nil
+}
+
+func (s *server) Process(stream grpc.BidiStreamingServer[proto.ProcessRequest, proto.ProcessResponse]) error {
+ for {
+ // Read input from the orchestrator
+ req, err := stream.Recv()
+ if err == io.EOF {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+
+ var outputs []*proto.Content
+ for _, content := range req.Contents {
+ // Only process text messages
+ if textContent := content.GetText(); textContent != nil {
+ // Convert to upper case dynamically!
+ upper := strings.ToUpper(textContent.Text)
+
+ log.Printf("📥 Received request text: %q", textContent.Text)
+ log.Printf("📤 Sending response: %q", upper)
+
+ outputs = append(outputs, &proto.Content{
+ Role: "agent",
+ Content: &proto.Content_Text{
+ Text: &proto.TextContent{
+ Text: "hey im your sandbox agent",
+ },
+ },
+ })
+ outputs = append(outputs, &proto.Content{
+ Role: "agent",
+ Content: &proto.Content_Text{
+ Text: &proto.TextContent{
+ Text: fmt.Sprintf("HERE IS YOUR UPPERCASE TEXT: %s", upper),
+ },
+ },
+ })
+ }
+ }
+
+ if len(outputs) > 0 {
+ // Send response back via gRPC
+ if err := stream.Send(&proto.ProcessResponse{
+ Contents: outputs,
+ }); err != nil {
+ return err
+ }
+ }
+ }
+}
+
+func main() {
+ port := os.Getenv("PORT")
+ if port == "" {
+ port = "50051" // Default port for local testing
+ }
+
+ // 1. Listen on port
+ lis, err := net.Listen("tcp", ":"+port)
+ if err != nil {
+ log.Fatalf("failed to listen on %s: %v", port, err)
+ }
+
+ // 2. Create gRPC server
+ s := grpc.NewServer()
+ proto.RegisterAgentServiceServer(s, &server{})
+ reflection.Register(s)
+
+ // 3. Graceful shutdown handler
+ sigChan := make(chan os.Signal, 1)
+ signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
+ go func() {
+ <-sigChan
+ log.Println("Shutting down upper_case_agent...")
+ s.GracefulStop()
+ }()
+
+ log.Printf("🟢 upper_case_agent listening on :%s", port)
+ if err := s.Serve(lis); err != nil {
+ log.Fatalf("failed to serve: %v", err)
+ }
+}
diff --git a/examples/sandbox_agent/sandbox-template.yaml b/examples/sandbox_agent/sandbox-template.yaml
new file mode 100644
index 0000000..a9a820f
--- /dev/null
+++ b/examples/sandbox_agent/sandbox-template.yaml
@@ -0,0 +1,28 @@
+# This is the Kubernetes manifest defining the execution environment for the agent.
+# It is applied strictly to the GKE Agent Sandbox controllers to define the Sandbox.
+# For more details on GKE Agent Sandbox container requirements, see:
+# https://docs.cloud.google.com/kubernetes-engine/docs/how-to/agent-sandbox
+apiVersion: extensions.agents.x-k8s.io/v1alpha1
+kind: SandboxTemplate
+metadata:
+ name: uppercase-agent-template
+ namespace: default
+spec:
+ podTemplate:
+ spec:
+ runtimeClassName: gvisor
+ containers:
+ - name: agent
+ image: us-central1-docker.pkg.dev/a2a-ae-fishfood-eoeg5x/gar-repo/gar-uppercase:latest
+ imagePullPolicy: Always
+ env:
+ - name: PORT
+ value: "8494"
+ ports:
+ - containerPort: 8494
+ name: grpc
+ readinessProbe:
+ tcpSocket:
+ port: 8494
+ initialDelaySeconds: 1
+ periodSeconds: 2
diff --git a/gar.yaml b/gar.yaml
index 954e81f..445a54d 100644
--- a/gar.yaml
+++ b/gar.yaml
@@ -68,3 +68,23 @@ planner:
# address: "localhost:50051"
# metadata:
# version: "1.0"
+
+agents:
+ - type: "remote"
+ remote:
+ id: "remote-text-processor"
+ name: "Remote Text Processor"
+ description: "Converts text to lowercase."
+ address: "localhost:50051"
+ metadata:
+ version: "1.0"
+ - type: "sandbox"
+ sandbox:
+ id: "uppercase"
+ name: "Upper Case Agent"
+ description: "Converts text to uppercase."
+ sandbox_template_ref: "uppercase-agent-template"
+ container_port: 8494
+ use_router: true
+ metadata:
+ version: "1.0"
diff --git a/go.mod b/go.mod
index 3b2604c..9939cd5 100644
--- a/go.mod
+++ b/go.mod
@@ -1,16 +1,19 @@
module github.com/google/gar
-go 1.24.0
+go 1.25.0
require (
github.com/charmbracelet/huh v0.8.0
github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834
github.com/google/uuid v1.6.0
github.com/spf13/cobra v1.10.2
+ golang.org/x/net v0.48.0
google.golang.org/genai v1.43.0
google.golang.org/grpc v1.78.0
google.golang.org/protobuf v1.36.11
gopkg.in/yaml.v3 v3.0.1
+ k8s.io/apimachinery v0.35.2
+ k8s.io/client-go v0.35.2
)
require (
@@ -29,32 +32,50 @@ require (
github.com/charmbracelet/x/term v0.2.1 // indirect
github.com/clipperhouse/stringish v0.1.1 // indirect
github.com/clipperhouse/uax29/v2 v2.3.0 // indirect
+ github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
+ github.com/fxamacker/cbor/v2 v2.9.0 // indirect
+ github.com/go-logr/logr v1.4.3 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/s2a-go v0.1.8 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.3.4 // indirect
- github.com/gorilla/websocket v1.5.3 // indirect
+ github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
+ github.com/json-iterator/go v1.1.12 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-localereader v0.0.1 // indirect
github.com/mattn/go-runewidth v0.0.19 // indirect
github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect
+ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
+ github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/muesli/termenv v0.16.0 // indirect
+ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
- github.com/rogpeppe/go-internal v1.14.1 // indirect
github.com/spf13/pflag v1.0.10 // indirect
+ github.com/x448/float16 v0.8.4 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
go.opencensus.io v0.24.0 // indirect
+ go.yaml.in/yaml/v2 v2.4.3 // indirect
golang.org/x/crypto v0.46.0 // indirect
- golang.org/x/net v0.48.0 // indirect
+ golang.org/x/oauth2 v0.32.0 // indirect
golang.org/x/sys v0.40.0 // indirect
+ golang.org/x/term v0.38.0 // indirect
golang.org/x/text v0.32.0 // indirect
+ golang.org/x/time v0.9.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
+ gopkg.in/inf.v0 v0.9.1 // indirect
+ k8s.io/klog/v2 v2.130.1 // indirect
+ k8s.io/kube-openapi v0.0.0-20250910181357-589584f1c912 // indirect
+ k8s.io/utils v0.0.0-20251002143259-bc988d571ff4 // indirect
+ sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect
+ sigs.k8s.io/randfill v1.0.0 // indirect
+ sigs.k8s.io/structured-merge-diff/v6 v6.3.0 // indirect
+ sigs.k8s.io/yaml v1.6.0 // indirect
)
diff --git a/go.sum b/go.sum
index 8d26566..73f39cf 100644
--- a/go.sum
+++ b/go.sum
@@ -56,19 +56,30 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
+github.com/emicklei/go-restful/v3 v3.12.2 h1:DhwDP0vY3k8ZzE0RunuJy8GhNpPL6zqLkDf9B/a0/xU=
+github.com/emicklei/go-restful/v3 v3.12.2/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
+github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM=
+github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
+github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
+github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
+github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE=
+github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k=
+github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
+github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=
@@ -85,6 +96,8 @@ github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QD
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
+github.com/google/gnostic-models v0.7.0 h1:qwTtogB15McXDaNqTZdzPJRHvaVJlAl+HVQnLmJEJxo=
+github.com/google/gnostic-models v0.7.0/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
@@ -93,6 +106,7 @@ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/s2a-go v0.1.8 h1:zZDs9gcbt9ZPLV0ndSyQk6Kacx2g/X+SKYovpnz3SMM=
github.com/google/s2a-go v0.1.8/go.mod h1:6iNWHTpQ+nfNRN5E00MSdfDwVesa8hhS32PhPO8deJA=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
@@ -100,10 +114,14 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/enterprise-certificate-proxy v0.3.4 h1:XYIDZApgAnrN1c855gTgghdIA6Stxb52D5RnLI1SLyw=
github.com/googleapis/enterprise-certificate-proxy v0.3.4/go.mod h1:YKe7cfqYXjKGpGvmSg28/fFvhNzinZQm8DGnaburhGA=
-github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
-github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
+github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5THxAzdVpqr6/geYxZytqFMBCOtn/ujyeo=
+github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
+github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
+github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
+github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
+github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
@@ -113,6 +131,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
+github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
+github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
@@ -121,13 +141,22 @@ github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byF
github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4=
github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE=
+github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
+github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
+github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=
+github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
+github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
+github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
@@ -144,9 +173,16 @@ github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3A
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
+github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
+github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
+github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
+github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
+github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
+github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
@@ -163,6 +199,9 @@ go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6
go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA=
go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE=
go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs=
+go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
+go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
+go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
@@ -183,6 +222,8 @@ golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwY
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
+golang.org/x/oauth2 v0.32.0 h1:jsCblLleRMDrxMN29H3z/k1KliIvpLgCkE6R8FXXNgY=
+golang.org/x/oauth2 v0.32.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -196,10 +237,14 @@ golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
+golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q=
+golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
+golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY=
+golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
@@ -238,8 +283,32 @@ google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
+gopkg.in/evanphx/json-patch.v4 v4.13.0 h1:czT3CmqEaQ1aanPc5SdlgQrrEIb8w/wwCvWWnfEbYzo=
+gopkg.in/evanphx/json-patch.v4 v4.13.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M=
+gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc=
+gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
+k8s.io/api v0.35.2 h1:tW7mWc2RpxW7HS4CoRXhtYHSzme1PN1UjGHJ1bdrtdw=
+k8s.io/api v0.35.2/go.mod h1:7AJfqGoAZcwSFhOjcGM7WV05QxMMgUaChNfLTXDRE60=
+k8s.io/apimachinery v0.35.2 h1:NqsM/mmZA7sHW02JZ9RTtk3wInRgbVxL8MPfzSANAK8=
+k8s.io/apimachinery v0.35.2/go.mod h1:jQCgFZFR1F4Ik7hvr2g84RTJSZegBc8yHgFWKn//hns=
+k8s.io/client-go v0.35.2 h1:YUfPefdGJA4aljDdayAXkc98DnPkIetMl4PrKX97W9o=
+k8s.io/client-go v0.35.2/go.mod h1:4QqEwh4oQpeK8AaefZ0jwTFJw/9kIjdQi0jpKeYvz7g=
+k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk=
+k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE=
+k8s.io/kube-openapi v0.0.0-20250910181357-589584f1c912 h1:Y3gxNAuB0OBLImH611+UDZcmKS3g6CthxToOb37KgwE=
+k8s.io/kube-openapi v0.0.0-20250910181357-589584f1c912/go.mod h1:kdmbQkyfwUagLfXIad1y2TdrjPFWp2Q89B3qkRwf/pQ=
+k8s.io/utils v0.0.0-20251002143259-bc988d571ff4 h1:SjGebBtkBqHFOli+05xYbK8YF1Dzkbzn+gDM4X9T4Ck=
+k8s.io/utils v0.0.0-20251002143259-bc988d571ff4/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0=
+sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg=
+sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg=
+sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU=
+sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY=
+sigs.k8s.io/structured-merge-diff/v6 v6.3.0 h1:jTijUJbW353oVOd9oTlifJqOGEkUw2jB/fXCbTiQEco=
+sigs.k8s.io/structured-merge-diff/v6 v6.3.0/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE=
+sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs=
+sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4=
diff --git a/internal/config/config.go b/internal/config/config.go
index a00faea..e18eeb5 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -35,8 +35,9 @@ type Config struct {
}
type Agent struct {
- Type string `yaml:"type"` // remote and more in the future...
- RemoteAgentConfig `yaml:",inline"`
+ Type string `yaml:"type,omitempty"` // local, remote, sandbox
+ RemoteAgentConfig *RemoteAgentConfig `yaml:"remote,omitempty"`
+ SandboxAgentConfig *SandboxAgentConfig `yaml:"sandbox,omitempty"`
}
// HealthCheckConfig defines the configuration for agent health checks.
@@ -86,6 +87,19 @@ type RemoteAgentConfig struct {
Metadata map[string]string `yaml:"metadata,omitempty"` // Optional metadata
}
+// SandboxAgentConfig configures a Kubernetes Sandbox agent to register on startup.
+type SandboxAgentConfig struct {
+ ID string `yaml:"id"` // Unique agent identifier
+ Name string `yaml:"name"` // Human-readable name
+ Description string `yaml:"description"` // Description of agent capabilities
+ SandboxTemplateRef string `yaml:"sandbox_template_ref"` // Name of the SandboxTemplate CR to use
+ // TODO: implement shutdown_time for automatic sandbox shutdown
+ ContainerPort int `yaml:"container_port,omitempty"`// Optional container port, defaults to 8494
+ WarmPoolSize int `yaml:"warm_pool_size,omitempty"`// Optional warm pool size for sandbox agents
+ UseRouter bool `yaml:"use_router,omitempty"` // Override port-forwarding to use Sandbox Router
+ Metadata map[string]string `yaml:"metadata,omitempty"` // Optional metadata
+}
+
type LocalAgentConfig struct {
ID string `yaml:"id"` // Unique agent identifier
Name string `yaml:"name"` // Human-readable name
diff --git a/internal/controller/health.go b/internal/controller/health.go
index d2bff85..c2c48f2 100644
--- a/internal/controller/health.go
+++ b/internal/controller/health.go
@@ -28,6 +28,7 @@ type HealthMonitor struct {
ticker *time.Ticker
stop chan struct{}
wg sync.WaitGroup
+ stopOnce sync.Once
}
// NewHealthMonitor creates a new health monitor.
@@ -50,7 +51,9 @@ func (hm *HealthMonitor) Start() {
func (hm *HealthMonitor) Stop() {
if hm.ticker != nil {
hm.ticker.Stop()
- close(hm.stop)
+ hm.stopOnce.Do(func() {
+ close(hm.stop)
+ })
hm.wg.Wait()
}
}
diff --git a/internal/controller/registry.go b/internal/controller/registry.go
index 0d0b8f7..c2539bd 100644
--- a/internal/controller/registry.go
+++ b/internal/controller/registry.go
@@ -28,8 +28,9 @@ import (
type AgentType string
const (
- AgentTypeLocal AgentType = "local"
- AgentTypeRemote AgentType = "remote"
+ AgentTypeLocal AgentType = "local"
+ AgentTypeRemote AgentType = "remote"
+ AgentTypeSandbox AgentType = "sandbox"
)
// AgentInfo contains metadata about a registered agent.
@@ -135,6 +136,44 @@ func (r *Registry) RegisterRemote(cfg config.RemoteAgentConfig) error {
return nil
}
+// RegisterSandbox registers a sandbox agent by dynamically provisioning a Sandbox on GKE.
+func (r *Registry) RegisterSandbox(ctx context.Context, cfg config.SandboxAgentConfig) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+
+ if err := validateID(cfg.ID); err != nil {
+ return err
+ }
+
+ if _, ok := r.agents[cfg.ID]; ok {
+ return fmt.Errorf("agent %s already registered", cfg.ID)
+ }
+
+ sandboxAgent, err := agent.NewSandboxAgent(ctx, agent.SandboxAgentConfig{
+ ID: cfg.ID,
+ SandboxTemplateRef: cfg.SandboxTemplateRef,
+ WarmPoolSize: cfg.WarmPoolSize,
+ ContainerPort: cfg.ContainerPort,
+ UseRouter: cfg.UseRouter,
+ })
+ if err != nil {
+ return fmt.Errorf("failed to provision sandbox agent: %w", err)
+ }
+
+ r.agents[cfg.ID] = sandboxAgent
+ r.agentInfo[cfg.ID] = &AgentInfo{
+ ID: cfg.ID,
+ Name: cfg.Name,
+ Description: cfg.Description,
+ Type: AgentTypeSandbox,
+ Healthy: true,
+ LastHealthCheck: time.Time{},
+ Metadata: cfg.Metadata,
+ }
+
+ return nil
+}
+
// Unregister removes an agent from the registry.
func (r *Registry) Unregister(id string) error {
r.mu.Lock()
diff --git a/internal/sandboxclient/client.go b/internal/sandboxclient/client.go
new file mode 100644
index 0000000..5a7e943
--- /dev/null
+++ b/internal/sandboxclient/client.go
@@ -0,0 +1,236 @@
+// 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 sandboxclient provides a high-level Go client for interacting with
+// the Kubernetes Agent Sandbox controllers, mirroring the official Python client.
+package sandboxclient
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "os/exec"
+ "strings"
+ "time"
+
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+ "k8s.io/apimachinery/pkg/runtime/schema"
+ "k8s.io/client-go/dynamic"
+ "k8s.io/client-go/rest"
+ "k8s.io/client-go/tools/clientcmd"
+)
+
+var (
+ SandboxGVR = schema.GroupVersionResource{
+ Group: "agents.x-k8s.io",
+ Version: "v1alpha1",
+ Resource: "sandboxes",
+ }
+ SandboxClaimGVR = schema.GroupVersionResource{
+ Group: "extensions.agents.x-k8s.io",
+ Version: "v1alpha1",
+ Resource: "sandboxclaims",
+ }
+ SandboxWarmPoolGVR = schema.GroupVersionResource{
+ Group: "extensions.agents.x-k8s.io",
+ Version: "v1alpha1",
+ Resource: "sandboxwarmpools",
+ }
+)
+
+// Client represents a high-level client for managing Sandbox resources in Kubernetes.
+type Client struct {
+ dynClient dynamic.Interface
+ namespace string
+}
+
+// NewClient creates a new Sandbox client using the local kubeconfig or cluster environment.
+func NewClient(namespace string) (*Client, error) {
+ // 1. Try in-cluster config first
+ config, err := rest.InClusterConfig()
+ if err != nil {
+ // 2. Fall back to local kubeconfig
+ kubeconfig := clientcmd.NewDefaultClientConfigLoadingRules().GetDefaultFilename()
+ config, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
+ if err != nil {
+ return nil, fmt.Errorf("failed to load kubernetes configuration: %w", err)
+ }
+ }
+
+ dynClient, err := dynamic.NewForConfig(config)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create dynamic client: %w", err)
+ }
+
+ return &Client{
+ dynClient: dynClient,
+ namespace: namespace,
+ }, nil
+}
+
+// CreateWarmPool creates a pre-warmed pool of sandbox environments.
+func (c *Client) CreateWarmPool(ctx context.Context, poolName, templateRef string, size int) error {
+ pool := &unstructured.Unstructured{
+ Object: map[string]interface{}{
+ "apiVersion": "extensions.agents.x-k8s.io/v1alpha1",
+ "kind": "SandboxWarmPool",
+ "metadata": map[string]interface{}{
+ "name": poolName,
+ "namespace": c.namespace,
+ },
+ "spec": map[string]interface{}{
+ "replicas": int64(size),
+ "sandboxTemplateRef": map[string]interface{}{
+ "name": templateRef,
+ },
+ },
+ },
+ }
+
+ _, err := c.dynClient.Resource(SandboxWarmPoolGVR).Namespace(c.namespace).Create(ctx, pool, metav1.CreateOptions{})
+ return err
+}
+
+// DeleteWarmPool removes a warm pool.
+func (c *Client) DeleteWarmPool(ctx context.Context, poolName string) error {
+ return c.dynClient.Resource(SandboxWarmPoolGVR).Namespace(c.namespace).Delete(ctx, poolName, metav1.DeleteOptions{})
+}
+
+// CreateClaim provisions an ephemeral sandbox execution environment.
+func (c *Client) CreateClaim(ctx context.Context, claimName, templateRef string) error {
+ claim := &unstructured.Unstructured{
+ Object: map[string]interface{}{
+ "apiVersion": "extensions.agents.x-k8s.io/v1alpha1",
+ "kind": "SandboxClaim",
+ "metadata": map[string]interface{}{
+ "name": claimName,
+ "namespace": c.namespace,
+ },
+ "spec": map[string]interface{}{
+ "sandboxTemplateRef": map[string]interface{}{
+ "name": templateRef,
+ },
+ },
+ },
+ }
+
+ _, err := c.dynClient.Resource(SandboxClaimGVR).Namespace(c.namespace).Create(ctx, claim, metav1.CreateOptions{})
+ return err
+}
+
+// DeleteClaim destroys an ephemeral sandbox execution environment.
+func (c *Client) DeleteClaim(ctx context.Context, claimName string) error {
+ return c.dynClient.Resource(SandboxClaimGVR).Namespace(c.namespace).Delete(ctx, claimName, metav1.DeleteOptions{})
+}
+
+// WaitForSandbox waits for the Sandbox resource to be ready and returns the pod selector.
+func (c *Client) WaitForSandbox(ctx context.Context, claimName string) (selector string, err error) {
+ for i := 0; i < 300; i++ {
+ select {
+ case <-ctx.Done():
+ return "", ctx.Err()
+ case <-time.After(1 * time.Second):
+ s, err := c.dynClient.Resource(SandboxGVR).Namespace(c.namespace).Get(ctx, claimName, metav1.GetOptions{})
+ if err != nil {
+ continue
+ }
+
+ sel, ok, _ := unstructured.NestedString(s.Object, "status", "selector")
+ if ok && sel != "" {
+ selector = sel
+ }
+
+ svc, found, _ := unstructured.NestedString(s.Object, "status", "service")
+ if found && svc != "" {
+ return selector, nil // Return once the service status is actively populated
+ }
+ }
+ }
+ return "", fmt.Errorf("timeout waiting for sandbox service IP for claim %s", claimName)
+}
+
+// WaitForSandboxReady waits for the Sandbox to become Ready.
+func (c *Client) WaitForSandboxReady(ctx context.Context, claimName string) error {
+ waitCmd := exec.CommandContext(ctx, "kubectl", "wait", "--for=condition=Ready", "--namespace", c.namespace, "sandbox.agents.x-k8s.io/"+claimName, "--timeout=120s")
+ if err := waitCmd.Run(); err != nil {
+ return fmt.Errorf("failed waiting for sandbox %s to be ready: %w", claimName, err)
+ }
+ return nil
+}
+
+// PortForward establishes a local connection to the remote sandbox pod over the given port.
+// It returns a cleanup function the caller MUST execute when finished, closing the port-forward pipeline.
+func (c *Client) PortForward(ctx context.Context, claimName, selector string, localPort, targetPort int) (cancelFunc func(), err error) {
+ pfCtx, pfCancel := context.WithCancel(context.Background())
+
+ // Wait for Sandbox to be ready first
+ waitCmd := exec.CommandContext(pfCtx, "kubectl", "wait", "--for=condition=Ready", "--namespace", c.namespace, "sandbox.agents.x-k8s.io/"+claimName, "--timeout=120s")
+ if err := waitCmd.Run(); err != nil {
+ pfCancel()
+ return nil, fmt.Errorf("failed waiting for sandbox %s to be ready: %w", claimName, err)
+ }
+
+ target := "svc/" + claimName
+ if selector != "" {
+ // Find the backing pod specifically to correctly link the port pipe with WarmPools
+ findPodCmd := exec.CommandContext(pfCtx, "kubectl", "get", "pods", "--namespace", c.namespace, "-l", selector, "--field-selector=status.phase=Running", "-o", "name")
+ out, err := findPodCmd.Output()
+ if err == nil {
+ podNames := strings.Split(strings.TrimSpace(string(out)), "\n")
+ if len(podNames) > 0 && podNames[0] != "" {
+ target = podNames[0]
+ }
+ }
+ }
+
+ cmd := exec.CommandContext(pfCtx, "kubectl", "port-forward", "--namespace", c.namespace, target, fmt.Sprintf("%d:%d", localPort, targetPort))
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ if err := cmd.Start(); err != nil {
+ pfCancel()
+ return nil, fmt.Errorf("failed to start port-forward: %w", err)
+ }
+
+ // Give port-forwarding a moment to establish
+ time.Sleep(10 * time.Second)
+
+ return pfCancel, nil
+}
+
+// PortForwardRouter establishes a local connection to the Sandbox Router service.
+// It returns a cleanup function the caller MUST execute when finished.
+func (c *Client) PortForwardRouter(ctx context.Context, localPort, targetPort int) (cancelFunc func(), err error) {
+ pfCtx, pfCancel := context.WithCancel(context.Background())
+
+ // Wait for Router service to be ready
+ waitCmd := exec.CommandContext(pfCtx, "kubectl", "wait", "--for=condition=Ready", "--namespace", c.namespace, "pod", "-l", "app=sandbox-router", "--timeout=120s")
+ if err := waitCmd.Run(); err != nil {
+ pfCancel()
+ return nil, fmt.Errorf("failed waiting for sandbox-router to be ready: %w", err)
+ }
+
+ cmd := exec.CommandContext(pfCtx, "kubectl", "port-forward", "--namespace", c.namespace, "svc/sandbox-router-svc", fmt.Sprintf("%d:%d", localPort, targetPort))
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ if err := cmd.Start(); err != nil {
+ pfCancel()
+ return nil, fmt.Errorf("failed to start router port-forward: %w", err)
+ }
+
+ // Give port-forwarding a moment to establish
+ time.Sleep(2 * time.Second)
+
+ return pfCancel, nil
+}
diff --git a/test_multi.go b/test_multi.go
new file mode 100644
index 0000000..6590eee
--- /dev/null
+++ b/test_multi.go
@@ -0,0 +1,207 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "strings"
+
+ "github.com/google/gar/agent"
+ "github.com/google/gar/internal/config"
+ "github.com/google/gar/internal/controller"
+ "github.com/google/gar/proto"
+ "github.com/google/uuid"
+)
+
+func main() {
+ ctx := context.Background()
+ input := "Send the word 'oRanGe' to the local-echo-agent. Take its exact output and send it to the remote-text-processor. Take its exact output and send it to the uppercase agent. Return the final output."
+ sessionID := uuid.New().String()
+
+ // 1. Create a local agent
+ echoAgent, err := createLocalAgent()
+ if err != nil {
+ log.Fatalf("Error creating local agent: %v\n", err)
+ }
+
+ // 2. Initialize controller
+ c, err := controller.New(ctx, controller.Config{
+ MaxSteps: 15,
+ HealthCheck: config.HealthCheckConfig{
+ Enabled: false, // disable to speed up
+ },
+ PlannerBuilder: func(ctx context.Context, r *controller.Registry) (agent.Agent, error) {
+ return &mockPlanner{}, nil
+ },
+ })
+ if err != nil {
+ log.Fatalf("Error creating controller: %v\n", err)
+ }
+ defer c.Close()
+
+ // 3. Register Local Agent
+ if err := c.Registry().RegisterLocal(config.LocalAgentConfig{
+ ID: "local-echo-agent",
+ Name: "Local Echo Agent",
+ Description: "Converts text to lowercase",
+ Agent: echoAgent,
+ }); err != nil {
+ log.Fatalf("Error registering local agent: %v\n", err)
+ }
+
+ // 4. Register Remote Agent
+ if err := c.Registry().RegisterRemote(config.RemoteAgentConfig{
+ ID: "remote-text-processor",
+ Name: "Remote Text Processor",
+ Description: "Adds the prefix 'Remote Prefix: ' to the text",
+ Address: "localhost:50051",
+ }); err != nil {
+ log.Fatalf("Error registering remote agent: %v\n", err)
+ }
+
+ // 5. Register Sandbox Agent
+ if err := c.Registry().RegisterSandbox(ctx, config.SandboxAgentConfig{
+ ID: "uppercase",
+ SandboxTemplateRef: "uppercase-agent-template",
+ ContainerPort: 8494,
+ UseRouter: true,
+ }); err != nil {
+ log.Fatalf("Error registering sandbox agent: %v\n", err)
+ }
+
+ inputs := []*proto.Content{
+ {
+ Role: "user",
+ Content: &proto.Content_Text{
+ Text: &proto.TextContent{
+ Text: input,
+ },
+ },
+ },
+ }
+
+ log.Printf("Session ID: %s\n", sessionID)
+
+ handler := agent.OutputHandler(func(outgoing *proto.ProcessResponse) error {
+ for _, c := range outgoing.Contents {
+ if textContent := c.GetText(); textContent != nil {
+ fmt.Printf("Output received: %s\n", textContent.Text)
+ }
+ }
+ return nil
+ })
+
+ req := &proto.ProcessRequest{
+ Contents: inputs,
+ }
+
+ for i := 0; i < 4; i++ {
+ log.Printf("\n--- Triggering step %d ---\n", i+1)
+ if err := c.TriggerSession(ctx, sessionID, req, handler); err != nil {
+ log.Fatalf("Error triggering session step %d: %v\n", i+1, err)
+ }
+ // Subsequent triggers just ask the planner to continue processing the existing history
+ req = &proto.ProcessRequest{}
+ }
+}
+
+func createLocalAgent() (*agent.LocalAgent, error) {
+ processFunc := func(ctx context.Context, sessionID string, incoming *proto.ProcessRequest, handler agent.OutputHandler) error {
+ for _, content := range incoming.Contents {
+ textContent := content.GetText()
+ if textContent == nil {
+ continue
+ }
+ if err := handler(&proto.ProcessResponse{
+ Contents: []*proto.Content{
+ {
+ Role: "assistant",
+ Content: &proto.Content_Text{
+ Text: &proto.TextContent{
+ Text: strings.ToLower(textContent.Text),
+ },
+ },
+ },
+ },
+ }); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+
+ return agent.NewLocalAgent(agent.LocalAgentConfig{
+ ProcessFunc: processFunc,
+ HealthCheckFunc: func(ctx context.Context) error { return nil },
+ })
+}
+
+type mockPlanner struct{}
+
+func (m *mockPlanner) ID() string { return "__planner" }
+func (m *mockPlanner) Name() string { return "Mock Planner" }
+func (m *mockPlanner) HealthCheck(ctx context.Context) error { return nil }
+func (m *mockPlanner) Close() error { return nil }
+func (m *mockPlanner) Process(ctx context.Context, sessionID string, incoming *proto.ProcessRequest, handler agent.OutputHandler) error {
+ var lastText string
+ for _, c := range incoming.Contents {
+ if t := c.GetText(); t != nil {
+ lastText = t.Text
+ }
+ }
+
+ // Step 1: User -> Local
+ if strings.HasPrefix(lastText, "Send the word") {
+ return handler(&proto.ProcessResponse{
+ AgentHandoff: "local-echo-agent",
+ Contents: []*proto.Content{{
+ Role: "assistant",
+ Content: &proto.Content_Text{
+ Text: &proto.TextContent{Text: "oRanGe"},
+ },
+ }},
+ })
+ }
+
+ // Step 2: Local -> Remote
+ if lastText == "orange" {
+ return handler(&proto.ProcessResponse{
+ AgentHandoff: "remote-text-processor",
+ Contents: []*proto.Content{{
+ Role: "assistant",
+ Content: &proto.Content_Text{
+ Text: &proto.TextContent{Text: lastText},
+ },
+ }},
+ })
+ }
+
+ // Step 3: Remote -> Sandbox
+ if strings.HasPrefix(lastText, "Remote Prefix:") {
+ return handler(&proto.ProcessResponse{
+ AgentHandoff: "uppercase",
+ Contents: []*proto.Content{{
+ Role: "assistant",
+ Content: &proto.Content_Text{
+ Text: &proto.TextContent{Text: lastText},
+ },
+ }},
+ })
+ }
+
+ // Final step: Sandbox -> Done
+ if strings.Contains(lastText, "UPPERCASE") {
+ return handler(&proto.ProcessResponse{
+ Contents: []*proto.Content{{
+ Role: "assistant",
+ Content: &proto.Content_Text{
+ Text: &proto.TextContent{
+ Text: "Final Result: " + lastText,
+ },
+ },
+ }},
+ })
+ }
+
+ return nil
+}