Skip to content

armgit / ax

Public Imported from GitHub
0

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

Go

Migrate controller and registry to internal/controller2 (#176)

Jaana Dogan9737fd7033db
diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml
index 4bf580c..3fd354f 100644
--- a/.github/workflows/go.yml
+++ b/.github/workflows/go.yml
@@ -61,13 +61,6 @@ jobs:
- name: Test
run: go test -v ./...
- - name: Build (harness)
- run: go build -tags harness -v ./...
-
- - name: Test (harness)
- run: go test -tags harness -v ./...
-
-
- name: Check for binary files in PR
run: |
# Get the list of files where Git shows no line count (binary)
diff --git a/Makefile b/Makefile
index ef5af9e..d81ca53 100644
--- a/Makefile
+++ b/Makefile
@@ -1,4 +1,4 @@
-.PHONY: all build build-harness proto test clean install install-harness install-ate images
+.PHONY: all build proto test clean install images
# Default container registry for docker
export KO_DOCKER_REPO ?= gcr.io/ax-container-images
@@ -15,12 +15,6 @@ build:
@go build -o bin/remote_agent ./examples/remote_agent
@echo "Build complete!"
-# (Dev-only) Build ax with the `harness` build tag.
-build-harness:
- @echo "Building ax (harness path)..."
- @mkdir -p bin
- @go build -tags harness -o bin/ax ./cmd/ax
- @echo "Build complete!"
# Generate protobuf code
proto:
@@ -35,8 +29,6 @@ proto:
test:
@echo "Running tests..."
@go test -v ./...
- @echo "Running tests (harness path)..."
- @go test -v -tags harness ./...
# Clean build artifacts
clean:
@@ -51,18 +43,6 @@ install:
@go install ./cmd/ax
@echo "Install complete!"
-# Install ax with the `harness` build tag.
-install-harness:
- @echo "Installing ax (harness path)..."
- @go install -tags harness ./cmd/ax
- @echo "Install complete!"
-
-# Install ax with ATE support to GOPATH/bin
-install-ate:
- @echo "Installing ax with ATE support..."
- @go install -tags ate ./cmd/ax
- @echo "Install complete!"
-
# Run remote agent example
run-remote:
@@ -86,8 +66,8 @@ ax-image:
ko build --base-import-paths ./cmd/ax
ax-server-image:
- @echo "Building ax-server (harness path) container image with ko..."
- GOFLAGS="-tags=harness" ko build --base-import-paths ./cmd/ax
+ @echo "Building ax-server container image with ko..."
+ ko build --base-import-paths ./cmd/ax
axepp-image:
@echo "Building axepp container image with ko..."
diff --git a/ax.yaml b/ax.yaml
index 814c32c..03b01ff 100644
--- a/ax.yaml
+++ b/ax.yaml
@@ -12,6 +12,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+# Sample LOCAL configuration for the AX *harness* build (compiled with -tags=harness).
+# Usage: ax serve --config ax.yaml
+# ax exec --config ax.yaml --input "hello" # uses harnesses.default
+
server:
address: ":8494"
@@ -19,30 +23,6 @@ eventlog:
sqlite:
filename: "eventlog/log.sqlite"
-planner:
- # Type of planner to use: "gemini" (default: "gemini")
- type: "gemini"
-
- # The Gemini planner uses Google's Gemini models for planning.
- gemini:
- model: "gemini-3.5-flash"
- timeout: "60s"
- # skills_dir: "./examples/skills"
-
-# Remote agents configuration (optional)
-# List of remote or sandbox agents to register on startup.
-registry:
- # remote_agents:
- # - id: "medical-deep-researcher"
- # name: "Medical Deep Researcher"
- # description: "Performs deep medical research using various resources like pubmed and clinicaltrials.gov"
- # address: "localhost:50051"
- # metadata:
- # version: "1.0"
-
- # - id: "weather-agent"
- # name: "Weather agent"
- # description: "Agent to answer questions about the weather in a city."
- # address: "localhost:50051"
- # metadata:
- # version: "1.0"
+harnesses:
+ antigravity:
+ default: true
diff --git a/cmd/ax/dashboard.go b/cmd/ax/dashboard.go
index 52b4276..fc62f57 100644
--- a/cmd/ax/dashboard.go
+++ b/cmd/ax/dashboard.go
@@ -30,7 +30,7 @@ import (
"time"
"github.com/google/ax/cmd/ax/internal/cliutil"
- "github.com/google/ax/internal/controller/executor"
+ "github.com/google/ax/internal/controller2/eventlog"
"github.com/google/ax/proto"
"github.com/spf13/cobra"
_ "modernc.org/sqlite"
@@ -373,8 +373,8 @@ func loadTraceData(ctx context.Context, cfg *cliutil.Config, convID string) (*Tr
}, nil
}
-func fetch(ctx context.Context, cfg *cliutil.Config, convID string) ([]*proto.ExecutionEvent, string, []string, error) {
- evLog, err := executor.OpenSQLiteEventLog(cfg.EventLog.SQLiteConfig.Filename)
+func fetch(ctx context.Context, cfg *cliutil.Config, convID string) ([]*proto.ConversationEvent, string, []string, error) {
+ evLog, err := eventlog.OpenSQLiteEventLog(cfg.EventLog.SQLiteConfig.Filename)
if err != nil {
return nil, "", nil, fmt.Errorf("could not open sqlite eventlog: %w", err)
}
@@ -398,26 +398,21 @@ func fetch(ctx context.Context, cfg *cliutil.Config, convID string) ([]*proto.Ex
return nil, "", nil, fmt.Errorf("no executions found for conversation: %s", convID)
}
- var allEvents []*proto.ExecutionEvent
- for _, eID := range execIDs {
- events, err := evLog.ExecEvents(ctx, eID)
- if err != nil {
- return nil, "", nil, fmt.Errorf("failed to query events for exec %s: %w", eID, err)
- }
- allEvents = append(allEvents, events...)
- }
-
// Use the first execID as the rootExecID as requested by user
rootExecID := execIDs[0]
- return allEvents, rootExecID, execIDs, nil
+ return convEvents, rootExecID, execIDs, nil
}
-func buildExecTraces(execIDs []string, events []*proto.ExecutionEvent) []ExecTrace {
+func buildExecTraces(execIDs []string, events []*proto.ConversationEvent) []ExecTrace {
execsMap := make(map[string][]ExecutionEvent)
+ harnessIDs := make(map[string]string)
for _, protoEv := range events {
exID := protoEv.ExecId
+ if protoEv.HarnessId != "" {
+ harnessIDs[exID] = protoEv.HarnessId
+ }
ev := extractExecutionEvent(exID, protoEv)
execsMap[exID] = append(execsMap[exID], ev)
}
@@ -425,13 +420,7 @@ func buildExecTraces(execIDs []string, events []*proto.ExecutionEvent) []ExecTra
var execs []ExecTrace
for _, execID := range execIDs {
if evs, ok := execsMap[execID]; ok {
- agentID := ""
- for _, ev := range evs {
- if ev.AgentID != "" {
- agentID = ev.AgentID
- break
- }
- }
+ agentID := harnessIDs[execID]
execs = append(execs, ExecTrace{
ExecID: execID,
AgentID: agentID,
@@ -473,18 +462,18 @@ func extractMsgs(protoContents []*proto.Message) []Content {
return results
}
-func extractExecutionEvent(execID string, protoEv *proto.ExecutionEvent) ExecutionEvent {
+func extractExecutionEvent(execID string, protoEv *proto.ConversationEvent) ExecutionEvent {
ev := ExecutionEvent{
ExecID: execID,
- AgentID: protoEv.AgentId,
- }
- if protoEv.Timestamp != nil {
- ev.Timestamp = protoEv.Timestamp.AsTime()
+ AgentID: protoEv.HarnessId,
}
ev.State = fmt.Sprint(protoEv.State)
- ev.Outputs = extractMsgs(protoEv.Outputs)
- ev.Inputs = extractMsgs(protoEv.Inputs)
+ if protoEv.HarnessId != "" {
+ ev.Inputs = extractMsgs(protoEv.Messages)
+ } else {
+ ev.Outputs = extractMsgs(protoEv.Messages)
+ }
return ev
}
diff --git a/cmd/ax/internal/cliutil/cliutil.go b/cmd/ax/internal/cliutil/cliutil.go
index a755803..a952a1b 100644
--- a/cmd/ax/internal/cliutil/cliutil.go
+++ b/cmd/ax/internal/cliutil/cliutil.go
@@ -1,5 +1,3 @@
-//go:build !harness
-
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
@@ -19,90 +17,105 @@ package cliutil
import (
"context"
"fmt"
- "time"
+ "os"
- "github.com/google/ax/internal/agent"
- "github.com/google/ax/internal/config"
- "github.com/google/ax/internal/controller"
- "github.com/google/ax/internal/controller/executor"
- "github.com/google/ax/internal/gemini"
+ "github.com/google/ax/internal/config2"
+ "github.com/google/ax/internal/controller2"
+ "github.com/google/ax/internal/controller2/eventlog"
+ "github.com/google/ax/internal/harness"
)
+const antigravityHarnessID = "antigravity"
+
// Controller is the active controller type for this build.
-type Controller = *controller.Controller
+type Controller = *controller2.Controller
// ExecHandler is the handler type accepted by Controller.Exec.
-type ExecHandler = controller.ExecHandler
+type ExecHandler = controller2.ExecHandler
// Config is the configuration type for this build.
-type Config = config.Config
+type Config = config2.Config
// LoadFromFile loads configuration from a YAML file.
func LoadFromFile(path string) (*Config, error) {
- return config.LoadFromFile(path)
+ return config2.LoadFromFile(path)
}
// DefaultConfig returns a configuration with default values set.
func DefaultConfig() *Config {
- return config.DefaultConfig()
+ return config2.DefaultConfig()
}
-// NewControllerFromConfig creates a new Controller instance based on the provided configuration.
-func NewControllerFromConfig(ctx context.Context, cfg *Config) (*controller.Controller, error) {
- // Validate planner type early
- switch cfg.Planner.Type {
- case "gemini":
- // valid
- default:
- return nil, fmt.Errorf("unknown planner type: %s", cfg.Planner.Type)
+// NewControllerFromConfig creates a controller2.Controller instance based on the provided configuration.
+func NewControllerFromConfig(ctx context.Context, cfg *Config) (*controller2.Controller, error) {
+ reg := controller2.NewRegistry()
+
+ // AX_SUBSTRATE selects how built-in harnesses run: locally (unset) or as
+ // substrate actors ("1").
+ substrateMode := os.Getenv("AX_SUBSTRATE") == "1"
+
+ // Built-in harnesses.
+ var defaultHarnessID string
+ var antigravityHarness harness.Harness
+ var err error
+ if !substrateMode {
+ address := cfg.Harnesses.Antigravity.Endpoint
+ if address == "" {
+ address = "127.0.0.1:50053"
+ }
+ antigravityHarness = harness.NewAntigravityHarness(address)
+ } else {
+ antigravityHarness, err = harness.NewSubstrateHarness(antigravityHarnessID, "", "", "", 80)
+ if err != nil {
+ return nil, fmt.Errorf("antigravity harness: %w", err)
+ }
}
-
- // Create event log builder
- eventLogBuilder := func() (executor.EventLog, error) {
- return executor.OpenSQLiteEventLog(cfg.EventLog.SQLiteConfig.Filename)
+ if err := reg.RegisterHarness(antigravityHarnessID, antigravityHarness); err != nil {
+ return nil, fmt.Errorf("register antigravity harness: %w", err)
}
-
- // Create planner builder
- plannerBuilder := func(ctx context.Context, r *controller.Registry) (agent.Agent, error) {
- switch cfg.Planner.Type {
- case "gemini":
- timeout, err := time.ParseDuration(cfg.Planner.Gemini.Timeout)
- if err != nil {
- return nil, fmt.Errorf("failed to parse duration: %v", err)
- }
- return gemini.NewGeminiPlannerAgent(ctx, r, gemini.GeminiPlannerConfig{
- GeminiConfig: &config.GeminiConfig{
- Model: cfg.Planner.Gemini.Model,
- MaxTokens: cfg.Planner.Gemini.MaxTokens,
- Temperature: cfg.Planner.Gemini.Temperature,
- Timeout: timeout,
- SystemPrompt: cfg.Planner.Gemini.SystemPrompt,
- },
- SkillsDir: cfg.Planner.Gemini.SkillsDir,
- })
- default:
- return nil, fmt.Errorf("unknown planner type: %s", cfg.Planner.Type)
- }
+ if cfg.Harnesses.Antigravity.Default {
+ defaultHarnessID = antigravityHarnessID
}
- // Build controller config
- controllerConfig := controller.Config{
- EventLogBuilder: eventLogBuilder,
- PlannerBuilder: plannerBuilder,
+ // Custom substrate harnesses.
+ if len(cfg.Harnesses.Substrate) > 0 && !substrateMode {
+ return nil, fmt.Errorf("custom substrate harnesses require AX_SUBSTRATE=1")
}
-
- // Create controller
- c, err := controller.New(ctx, controllerConfig)
- if err != nil {
- return nil, err
+ for _, sc := range cfg.Harnesses.Substrate {
+ h, err := sc.NewHarness("")
+ if err != nil {
+ return nil, fmt.Errorf("substrate harness %q: %w", sc.ID, err)
+ }
+ if err := reg.RegisterHarness(sc.ID, h); err != nil {
+ return nil, fmt.Errorf("register substrate harness %q: %w", sc.ID, err)
+ }
+ if sc.Default {
+ defaultHarnessID = sc.ID
+ }
}
- for _, agentCfg := range cfg.Registry.RemoteAgents {
- if err := c.Registry().RegisterRemote(ctx, agentCfg); err != nil {
- return nil, fmt.Errorf("failed to register remote agent %s: %w", agentCfg.ID, err)
+ // Register the configured default harness.
+ if defaultHarnessID != "" {
+ h, err := reg.Harness(defaultHarnessID)
+ if err != nil {
+ return nil, fmt.Errorf("default harness %q not found", defaultHarnessID)
+ }
+ if err := reg.RegisterHarness("", h); err != nil {
+ return nil, fmt.Errorf("register default harness %q: %w", defaultHarnessID, err)
}
}
-
- return c, nil
+ return controller2.New(ctx, controller2.Config{
+ Registry: reg,
+ EventLogBuilder: func() (eventlog.EventLog, error) {
+ if cfg.EventLog.PostgresConfig.DSN != "" {
+ dsn := os.ExpandEnv(cfg.EventLog.PostgresConfig.DSN)
+ if dsn == "" {
+ return nil, fmt.Errorf("eventlog: postgres dsn %q expanded to empty", cfg.EventLog.PostgresConfig.DSN)
+ }
+ return eventlog.OpenPostgresEventLog(dsn)
+ }
+ return eventlog.OpenSQLiteEventLog(cfg.EventLog.SQLiteConfig.Filename)
+ },
+ })
}
diff --git a/cmd/ax/internal/cliutil/cliutil_harness.go b/cmd/ax/internal/cliutil/cliutil_harness.go
deleted file mode 100644
index 03814d1..0000000
--- a/cmd/ax/internal/cliutil/cliutil_harness.go
+++ /dev/null
@@ -1,123 +0,0 @@
-//go:build harness
-
-// 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 cliutil
-
-import (
- "context"
- "fmt"
- "os"
-
- "github.com/google/ax/internal/config2"
- "github.com/google/ax/internal/controller2"
- "github.com/google/ax/internal/controller2/eventlog"
- "github.com/google/ax/internal/harness"
-)
-
-const antigravityHarnessID = "antigravity"
-
-// Controller is the active controller type for this build.
-type Controller = *controller2.Controller
-
-// ExecHandler is the handler type accepted by Controller.Exec.
-type ExecHandler = controller2.ExecHandler
-
-// Config is the configuration type for this build.
-type Config = config2.Config
-
-// LoadFromFile loads configuration from a YAML file.
-func LoadFromFile(path string) (*Config, error) {
- return config2.LoadFromFile(path)
-}
-
-// DefaultConfig returns a configuration with default values set.
-func DefaultConfig() *Config {
- return config2.DefaultConfig()
-}
-
-// NewControllerFromConfig creates a controller2.Controller instance based on the provided configuration.
-func NewControllerFromConfig(ctx context.Context, cfg *Config) (*controller2.Controller, error) {
- reg := controller2.NewRegistry()
-
- // AX_SUBSTRATE selects how built-in harnesses run: locally (unset) or as
- // substrate actors ("1").
- substrateMode := os.Getenv("AX_SUBSTRATE") == "1"
-
- // Built-in harnesses.
- var defaultHarnessID string
- var antigravityHarness harness.Harness
- var err error
- if !substrateMode {
- address := cfg.Harnesses.Antigravity.Endpoint
- if address == "" {
- address = "127.0.0.1:50053"
- }
- antigravityHarness = harness.NewAntigravityHarness(address)
- } else {
- antigravityHarness, err = harness.NewSubstrateHarness(antigravityHarnessID, "", "", "", 80)
- if err != nil {
- return nil, fmt.Errorf("antigravity harness: %w", err)
- }
- }
- if err := reg.RegisterHarness(antigravityHarnessID, antigravityHarness); err != nil {
- return nil, fmt.Errorf("register antigravity harness: %w", err)
- }
- if cfg.Harnesses.Antigravity.Default {
- defaultHarnessID = antigravityHarnessID
- }
-
- // Custom substrate harnesses.
- if len(cfg.Harnesses.Substrate) > 0 && !substrateMode {
- return nil, fmt.Errorf("custom substrate harnesses require AX_SUBSTRATE=1")
- }
- for _, sc := range cfg.Harnesses.Substrate {
- h, err := sc.NewHarness("")
- if err != nil {
- return nil, fmt.Errorf("substrate harness %q: %w", sc.ID, err)
- }
- if err := reg.RegisterHarness(sc.ID, h); err != nil {
- return nil, fmt.Errorf("register substrate harness %q: %w", sc.ID, err)
- }
- if sc.Default {
- defaultHarnessID = sc.ID
- }
- }
-
- // Register the configured default harness.
- if defaultHarnessID != "" {
- h, err := reg.Harness(defaultHarnessID)
- if err != nil {
- return nil, fmt.Errorf("default harness %q not found", defaultHarnessID)
- }
- if err := reg.RegisterHarness("", h); err != nil {
- return nil, fmt.Errorf("register default harness %q: %w", defaultHarnessID, err)
- }
- }
-
- return controller2.New(ctx, controller2.Config{
- Registry: reg,
- EventLogBuilder: func() (eventlog.EventLog, error) {
- if cfg.EventLog.PostgresConfig.DSN != "" {
- dsn := os.ExpandEnv(cfg.EventLog.PostgresConfig.DSN)
- if dsn == "" {
- return nil, fmt.Errorf("eventlog: postgres dsn %q expanded to empty", cfg.EventLog.PostgresConfig.DSN)
- }
- return eventlog.OpenPostgresEventLog(dsn)
- }
- return eventlog.OpenSQLiteEventLog(cfg.EventLog.SQLiteConfig.Filename)
- },
- })
-}
diff --git a/cmd/ax/internal/cliutil/cliutil_harness_test.go b/cmd/ax/internal/cliutil/cliutil_harness_test.go
deleted file mode 100644
index bc392fe..0000000
--- a/cmd/ax/internal/cliutil/cliutil_harness_test.go
+++ /dev/null
@@ -1,128 +0,0 @@
-//go:build harness
-
-// 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 cliutil
-
-import (
- "context"
- "path/filepath"
- "strings"
- "testing"
-
- "github.com/google/ax/internal/config2"
-)
-
-func TestNewControllerFromConfig_DefaultHarness(t *testing.T) {
- cfg := &config2.Config{
- EventLog: config2.EventLogConfig{
- SQLiteConfig: config2.SQLiteConfig{
- Filename: filepath.Join(t.TempDir(), "log.sqlite"),
- },
- },
- Harnesses: config2.HarnessesConfig{
- Antigravity: config2.AntigravityHarnessConfig{
- Default: true,
- Endpoint: "localhost:50053",
- },
- },
- }
-
- c, err := NewControllerFromConfig(context.Background(), cfg)
- if err != nil {
- t.Fatalf("NewControllerFromConfig: %v", err)
- }
- if c == nil {
- t.Fatal("expected non-nil controller")
- }
- c.Close()
-}
-
-func TestNewControllerFromConfig_BuiltinSubstrate(t *testing.T) {
- t.Setenv("AX_SUBSTRATE", "1")
-
- cfg := &config2.Config{
- EventLog: config2.EventLogConfig{
- SQLiteConfig: config2.SQLiteConfig{
- Filename: filepath.Join(t.TempDir(), "log.sqlite"),
- },
- },
- Harnesses: config2.HarnessesConfig{
- Antigravity: config2.AntigravityHarnessConfig{
- Default: true,
- },
- },
- }
-
- c, err := NewControllerFromConfig(context.Background(), cfg)
- if err != nil {
- t.Fatalf("NewControllerFromConfig: %v", err)
- }
- if c == nil {
- t.Fatal("expected non-nil controller")
- }
- c.Close()
-}
-
-func TestNewControllerFromConfig_CustomHarnessRequiresSubstrateMode(t *testing.T) {
- t.Setenv("AX_SUBSTRATE", "")
-
- cfg := &config2.Config{
- EventLog: config2.EventLogConfig{
- SQLiteConfig: config2.SQLiteConfig{
- Filename: filepath.Join(t.TempDir(), "log.sqlite"),
- },
- },
- Harnesses: config2.HarnessesConfig{
- Substrate: []config2.SubstrateHarnessConfig{
- {ID: "custom", Namespace: "team-ns", Template: "custom-template"},
- },
- },
- }
-
- _, err := NewControllerFromConfig(context.Background(), cfg)
- if err == nil {
- t.Fatal("expected error for custom substrate harness without AX_SUBSTRATE=1, got nil")
- }
- if !strings.Contains(err.Error(), "AX_SUBSTRATE=1") {
- t.Errorf("expected error to mention AX_SUBSTRATE=1, got: %v", err)
- }
-}
-
-func TestNewControllerFromConfig_CustomHarnessInSubstrateMode(t *testing.T) {
- t.Setenv("AX_SUBSTRATE", "1")
-
- cfg := &config2.Config{
- EventLog: config2.EventLogConfig{
- SQLiteConfig: config2.SQLiteConfig{
- Filename: filepath.Join(t.TempDir(), "log.sqlite"),
- },
- },
- Harnesses: config2.HarnessesConfig{
- Substrate: []config2.SubstrateHarnessConfig{
- {ID: "custom", Namespace: "team-ns", Template: "custom-template"},
- },
- },
- }
-
- c, err := NewControllerFromConfig(context.Background(), cfg)
- if err != nil {
- t.Fatalf("NewControllerFromConfig: %v", err)
- }
- if c == nil {
- t.Fatal("expected non-nil controller")
- }
- c.Close()
-}
diff --git a/cmd/ax/internal/cliutil/cliutil_test.go b/cmd/ax/internal/cliutil/cliutil_test.go
index 2b493f7..ca9f440 100644
--- a/cmd/ax/internal/cliutil/cliutil_test.go
+++ b/cmd/ax/internal/cliutil/cliutil_test.go
@@ -1,5 +1,3 @@
-//go:build !harness
-
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
@@ -18,20 +16,111 @@ package cliutil
import (
"context"
+ "path/filepath"
+ "strings"
"testing"
- "github.com/google/ax/internal/config"
+ "github.com/google/ax/internal/config2"
)
-func TestNewControllerFromConfig_UnknownPlanner(t *testing.T) {
- cfg := &config.Config{
- Planner: config.PlannerConfig{
- Type: "unknown",
+func TestNewControllerFromConfig_DefaultHarness(t *testing.T) {
+ cfg := &config2.Config{
+ EventLog: config2.EventLogConfig{
+ SQLiteConfig: config2.SQLiteConfig{
+ Filename: filepath.Join(t.TempDir(), "log.sqlite"),
+ },
+ },
+ Harnesses: config2.HarnessesConfig{
+ Antigravity: config2.AntigravityHarnessConfig{
+ Default: true,
+ Endpoint: "localhost:50053",
+ },
+ },
+ }
+
+ c, err := NewControllerFromConfig(context.Background(), cfg)
+ if err != nil {
+ t.Fatalf("NewControllerFromConfig: %v", err)
+ }
+ if c == nil {
+ t.Fatal("expected non-nil controller")
+ }
+ c.Close()
+}
+
+func TestNewControllerFromConfig_BuiltinSubstrate(t *testing.T) {
+ t.Setenv("AX_SUBSTRATE", "1")
+
+ cfg := &config2.Config{
+ EventLog: config2.EventLogConfig{
+ SQLiteConfig: config2.SQLiteConfig{
+ Filename: filepath.Join(t.TempDir(), "log.sqlite"),
+ },
+ },
+ Harnesses: config2.HarnessesConfig{
+ Antigravity: config2.AntigravityHarnessConfig{
+ Default: true,
+ },
+ },
+ }
+
+ c, err := NewControllerFromConfig(context.Background(), cfg)
+ if err != nil {
+ t.Fatalf("NewControllerFromConfig: %v", err)
+ }
+ if c == nil {
+ t.Fatal("expected non-nil controller")
+ }
+ c.Close()
+}
+
+func TestNewControllerFromConfig_CustomHarnessRequiresSubstrateMode(t *testing.T) {
+ t.Setenv("AX_SUBSTRATE", "")
+
+ cfg := &config2.Config{
+ EventLog: config2.EventLogConfig{
+ SQLiteConfig: config2.SQLiteConfig{
+ Filename: filepath.Join(t.TempDir(), "log.sqlite"),
+ },
+ },
+ Harnesses: config2.HarnessesConfig{
+ Substrate: []config2.SubstrateHarnessConfig{
+ {ID: "custom", Namespace: "team-ns", Template: "custom-template"},
+ },
},
}
_, err := NewControllerFromConfig(context.Background(), cfg)
if err == nil {
- t.Fatal("expected error for unknown planner type, got nil")
+ t.Fatal("expected error for custom substrate harness without AX_SUBSTRATE=1, got nil")
+ }
+ if !strings.Contains(err.Error(), "AX_SUBSTRATE=1") {
+ t.Errorf("expected error to mention AX_SUBSTRATE=1, got: %v", err)
+ }
+}
+
+func TestNewControllerFromConfig_CustomHarnessInSubstrateMode(t *testing.T) {
+ t.Setenv("AX_SUBSTRATE", "1")
+
+ cfg := &config2.Config{
+ EventLog: config2.EventLogConfig{
+ SQLiteConfig: config2.SQLiteConfig{
+ Filename: filepath.Join(t.TempDir(), "log.sqlite"),
+ },
+ },
+ Harnesses: config2.HarnessesConfig{
+ Substrate: []config2.SubstrateHarnessConfig{
+ {ID: "custom", Namespace: "team-ns", Template: "custom-template"},
+ },
+ },
+ }
+
+ c, err := NewControllerFromConfig(context.Background(), cfg)
+ if err != nil {
+ t.Fatalf("NewControllerFromConfig: %v", err)
+ }
+ if c == nil {
+ t.Fatal("expected non-nil controller")
}
+ c.Close()
}
diff --git a/go.mod b/go.mod
index 0e9177f..de994c6 100644
--- a/go.mod
+++ b/go.mod
@@ -11,7 +11,6 @@ require (
github.com/jackc/pgx/v5 v5.10.0
github.com/spf13/cobra v1.10.2
golang.org/x/oauth2 v0.36.0
- golang.org/x/sync v0.20.0
google.golang.org/genai v1.43.0
google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d
google.golang.org/grpc v1.81.0
@@ -72,6 +71,7 @@ require (
go.opentelemetry.io/otel/trace v1.43.0 // indirect
golang.org/x/crypto v0.51.0 // indirect
golang.org/x/net v0.55.0 // indirect
+ golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.45.0 // indirect
golang.org/x/text v0.37.0 // indirect
google.golang.org/api v0.274.0 // indirect
diff --git a/internal/ax2.yaml b/internal/ax2.yaml
deleted file mode 100644
index 5e3cd24..0000000
--- a/internal/ax2.yaml
+++ /dev/null
@@ -1,28 +0,0 @@
-# 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.
-
-# Sample LOCAL configuration for the AX *harness* build (compiled with -tags=harness).
-# Usage: ax serve --config internal/ax2.yaml
-# ax exec --config internal/ax2.yaml --input "hello" # uses harnesses.default
-
-server:
- address: ":8494"
-
-eventlog:
- sqlite:
- filename: "eventlog/log.sqlite"
-
-harnesses:
- antigravity:
- default: true
diff --git a/internal/config/config.go b/internal/config/config.go
deleted file mode 100644
index 341f487..0000000
--- a/internal/config/config.go
+++ /dev/null
@@ -1,170 +0,0 @@
-// 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 config provides configuration structures for AX server.
-package config
-
-import (
- "fmt"
- "os"
- "time"
-
- "github.com/google/ax/internal/agent"
- "gopkg.in/yaml.v3"
-)
-
-// Config represents the main configuration for AX server.
-type Config struct {
- Server ServerConfig `yaml:"server"`
- EventLog EventLogConfig `yaml:"eventlog"`
- Planner PlannerConfig `yaml:"planner,omitempty"`
- Registry RegistryConfig `yaml:"registry,omitempty"`
- Substrate SubstrateConfig `yaml:"substrate,omitempty"`
-}
-
-// RegistryConfig allows registring agents.
-type RegistryConfig struct {
- RemoteAgents []RemoteAgentConfig `yaml:"remote_agents,omitempty"`
-}
-
-// SubstrateConfig configures the Substrate integration.
-type SubstrateConfig struct {
- Endpoint string `yaml:"endpoint"`
-}
-
-// ServerConfig configures the gRPC server.
-type ServerConfig struct {
- Address string `yaml:"address"` // Server address to listen on (e.g., ":8494")
-}
-
-type SQLiteConfig struct {
- Filename string `yaml:"filename"` // SQLite file for event log storage
-}
-
-// EventLogConfig configures the event log storage.
-type EventLogConfig struct {
- SQLiteConfig SQLiteConfig `yaml:"sqlite"`
-}
-
-// PlannerConfig configures the planner.
-type PlannerConfig struct {
- Type string `yaml:"type"` // "gemini"
- Gemini GeminiPlannerConfig `yaml:"gemini,omitempty"`
-}
-
-// GeminiPlannerConfig configures the Gemini-based planner.
-// Note: API key is not configurable here for security reasons.
-// Set GEMINI_API_KEY environment variable instead.
-type GeminiPlannerConfig struct {
- Model string `yaml:"model,omitempty"` // Model name
- Temperature float32 `yaml:"temperature,omitempty"`
- MaxTokens int32 `yaml:"max_tokens,omitempty"`
- Timeout string `yaml:"timeout,omitempty"`
- SystemPrompt string `yaml:"system_prompt,omitempty"`
- SkillsDir string `yaml:"skills_dir,omitempty"` // Directory to discover skills from. If omitted, falls back to SKILLS_DIR env var or ~/.agents/skills.
-}
-
-func (c *GeminiPlannerConfig) setDefaults() {
- if c.Model == "" {
- c.Model = "gemini-3.5-flash"
- }
- if c.Timeout == "" {
- c.Timeout = "30s"
- }
-}
-
-// GeminiConfig is the configuration for a Gemini agent execution.
-type GeminiConfig struct {
- Model string `json:"model,omitempty" yaml:"model,omitempty"`
- SystemPrompt string `json:"system_prompt,omitempty" yaml:"system_prompt,omitempty"`
- MaxTokens int32 `json:"max_tokens,omitempty" yaml:"max_tokens,omitempty"`
- Temperature float32 `json:"temperature,omitempty" yaml:"temperature,omitempty"` // 0 means use model default
- Timeout time.Duration `json:"timeout,omitempty" yaml:"timeout,omitempty"`
- Tools []string `json:"tools,omitempty" yaml:"tools,omitempty"`
-}
-
-// RemoteAgentConfig configures a remote agent to register on startup.
-type RemoteAgentConfig struct {
- ID string `yaml:"id"` // Unique agent identifier
- Name string `yaml:"name"` // Human-readable name
- Description string `yaml:"description"` // Description
- Address string `yaml:"address"` // Remote agent address
- 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
- Description string `yaml:"description"` // Description of agent capabilities
- Metadata map[string]string `yaml:"metadata,omitempty"` // Optional metadata
- Agent agent.Agent // In-process agent instance (not in YAML)
-}
-
-// LoadFromFile loads configuration from a YAML file.
-func LoadFromFile(path string) (*Config, error) {
- data, err := os.ReadFile(path)
- if err != nil {
- return nil, fmt.Errorf("failed to read config file: %w", err)
- }
-
- var cfg Config
- if err := yaml.Unmarshal(data, &cfg); err != nil {
- return nil, fmt.Errorf("failed to parse config file: %w", err)
- }
-
- // Set defaults
- cfg.setDefaults()
-
- return &cfg, nil
-}
-
-// DefaultConfig returns a configuration with default values set.
-func DefaultConfig() *Config {
- var cfg Config
- cfg.setDefaults()
- return &cfg
-}
-
-// setDefaults sets default values for optional fields.
-func (c *Config) setDefaults() {
- // Server defaults
- if c.Server.Address == "" {
- c.Server.Address = ":8494"
- }
-
- if c.EventLog.SQLiteConfig.Filename == "" {
- c.EventLog.SQLiteConfig.Filename = "eventlog/log.sqlite"
- }
-
- // Planner defaults
- if c.Planner.Type == "" {
- c.Planner.Type = "gemini"
- }
- if c.Planner.Type == "gemini" {
- c.Planner.Gemini.setDefaults()
- }
-
-}
-
-// Validate validates the configuration.
-func (c *Config) Validate() error {
- if c.Server.Address == "" {
- return fmt.Errorf("server.address is required")
- }
- if c.EventLog.SQLiteConfig.Filename == "" {
- return fmt.Errorf("eventlog.sqlite.filename is required")
- }
-
- return nil
-}
diff --git a/internal/controller/controller.go b/internal/controller/controller.go
deleted file mode 100644
index 34ece25..0000000
--- a/internal/controller/controller.go
+++ /dev/null
@@ -1,283 +0,0 @@
-// 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 controller implements the single-writer orchestrator that coordinates
-// agentic loops, manages executions, and communicates with local and remote agents.
-package controller
-
-import (
- "context"
- "fmt"
- "maps"
-
- "github.com/google/ax/internal/agent"
- "github.com/google/ax/internal/controller/executor"
- "github.com/google/ax/internal/gemini"
- "github.com/google/ax/proto"
- "github.com/google/uuid"
-)
-
-const (
- plannerAgentID = "__planner"
- geminiAgentID = "gemini"
-)
-
-var reservedAgentIDs = map[string]struct{}{
- plannerAgentID: {},
- geminiAgentID: {},
-}
-
-type ExecHandler func(resp *proto.ExecResponse) error
-
-// Controller is the main controller that coordinates all components.
-// It acts as a single-writer system for managing agentic loops.
-type Controller struct {
- registry *Registry
- eventLog executor.EventLog
- plannerBuilder PlannerBuilder
-}
-
-// PlannerBuilder is a function that creates a PlanFunc given a Registry.
-type PlannerBuilder func(ctx context.Context, r *Registry) (agent.Agent, error)
-
-// Config configures the controller.
-type Config struct {
- EventLogBuilder executor.EventLogBuilder
- PlannerBuilder PlannerBuilder
-}
-
-// New creates a new controller instance.
-func New(ctx context.Context, cfg Config) (*Controller, error) {
- // Initialize agent registry
- registry := NewRegistry()
-
- // Determine plan function
- // If no planner builder is provided, use the default Gemini planner.
- if cfg.PlannerBuilder == nil {
- cfg.PlannerBuilder = func(ctx context.Context, r *Registry) (agent.Agent, error) {
- return gemini.NewGeminiPlannerAgent(ctx, r, gemini.GeminiPlannerConfig{})
- }
- }
-
- if cfg.EventLogBuilder == nil {
- return nil, fmt.Errorf("event log builder is required")
- }
- eventLog, err := cfg.EventLogBuilder()
- if err != nil {
- return nil, fmt.Errorf("failed to create event log: %w", err)
- }
-
- return &Controller{
- registry: registry,
- eventLog: eventLog,
- plannerBuilder: cfg.PlannerBuilder,
- }, nil
-}
-
-func (d *Controller) tryResuming(ctx context.Context, req *proto.ExecRequest, el executor.EventLog, registry map[string]agent.Agent, handler ExecHandler) (history []*proto.Message, done bool, err error) {
- events, err := el.Events(ctx, req.ConversationId)
- if err != nil {
- return nil, false, fmt.Errorf("failed to retrieve execution history: %w", err)
- }
- var pendingExecID string
- for _, ev := range events {
- if ev.ExecId != "" && ev.State == proto.State_STATE_PENDING {
- pendingExecID = ev.ExecId
- }
- if ev.ExecId == pendingExecID && ev.State == proto.State_STATE_COMPLETED {
- pendingExecID = ""
- }
- history = append(history, ev.Messages...)
- }
-
- if req.LastSeq != 0 {
- found := false
- for _, ev := range events {
- if ev.Seq == req.LastSeq {
- found = true
- }
- if ev.Seq > req.LastSeq {
- if err := handler(&proto.ExecResponse{
- Outputs: ev.Messages,
- Seq: ev.Seq,
- }); err != nil {
- return nil, false, err
- }
- }
- }
- if !found {
- return nil, false, fmt.Errorf("last_seq %d not found", req.LastSeq)
- }
- }
-
- if pendingExecID == "" {
- return history, false, nil
- }
-
- // Find the pending event.
- execEvents, err := el.ExecEvents(ctx, pendingExecID)
- if err != nil {
- return nil, false, fmt.Errorf("failed to retrieve execution events: %w", err)
- }
-
- // TODO(jbd): Merge ExecutionEvent and ConversationEvent?
- var pendingEvent *proto.ExecutionEvent
- for _, ev := range execEvents {
- if ev.State == proto.State_STATE_PENDING {
- pendingEvent = ev
- break
- }
- }
- if pendingEvent == nil {
- return nil, false, fmt.Errorf("failed to retrieve pending event: %w", err)
- }
- if err := d.execute(
- ctx,
- req.ConversationId,
- pendingExecID,
- pendingEvent.AgentId,
- pendingEvent.AgentConfig,
- history,
- req.Inputs,
- registry,
- handler,
- ); err != nil {
- return nil, false, err
- }
- return history, true, nil
-}
-
-// Exec executes a new agentic loop execution or resumes an existing one.
-// If id is empty, a UUID will be generated.
-// If the execution already exists, it will be resumed with optional new inputs.
-func (d *Controller) Exec(ctx context.Context, req *proto.ExecRequest, handler ExecHandler) error {
- if req.ConversationId == "" {
- return fmt.Errorf("conversation_id is required")
- }
-
- planner, err := d.plannerBuilder(ctx, d.registry)
- if err != nil {
- return fmt.Errorf("failed to create planner: %w", err)
- }
-
- registry := maps.Clone(d.registry.Map())
- registry[plannerAgentID] = planner
-
- // TODO(lhuan): consider remove this.
- registry[geminiAgentID] = gemini.NewGeminiAgent()
-
- if req.AgentId == "" {
- req.AgentId = plannerAgentID
- }
-
- // Replay the execution history if any.
- history, done, err := d.tryResuming(ctx, req, d.eventLog, registry, handler)
- if err != nil {
- return err
- }
- if done {
- // Nothing else to do, new inputs are used in the replay.
- return nil
- }
-
- return d.execute(
- ctx,
- req.ConversationId,
- uuid.NewString(),
- req.AgentId,
- req.AgentConfig,
- history,
- req.Inputs,
- registry,
- handler,
- )
-}
-
-func (d *Controller) execute(ctx context.Context, conversationID string, execID string, agentID string, agentConfig []byte, history []*proto.Message, newInputs []*proto.Message, registry map[string]agent.Agent, handler ExecHandler) error {
- e := executor.DefaultExecutor(d.eventLog, registry)
- outputCapturer := func(outgoing *proto.AgentOutputs) error {
- // Filter out internal-only messages.
- var outputs []*proto.Message
- for _, m := range outgoing.Messages {
- if m.GetInternalOnly() {
- continue
- }
- outputs = append(outputs, m)
- }
- if len(outputs) == 0 {
- return nil
- }
- msg := &proto.ConversationEvent{
- ConversationId: conversationID,
- ExecId: execID,
- Messages: outputs,
- State: proto.State_STATE_PENDING,
- }
- seq, err := d.eventLog.Append(ctx, msg)
- if err != nil {
- return err
- }
- return handler(&proto.ExecResponse{
- Outputs: msg.Messages,
- Seq: seq,
- })
- }
- if _, err := d.eventLog.Append(ctx, &proto.ConversationEvent{
- ConversationId: conversationID,
- ExecId: execID,
- Messages: newInputs,
- State: proto.State_STATE_PENDING,
- }); err != nil {
- return err
- }
- state, err := e.Exec(ctx, conversationID, execID, &proto.AgentStart{
- AgentId: agentID,
- AgentConfig: agentConfig,
- Messages: append(history, newInputs...),
- }, outputCapturer)
- if err != nil {
- return err
- }
- _, err = d.eventLog.Append(ctx, &proto.ConversationEvent{
- ConversationId: conversationID,
- ExecId: execID,
- State: state,
- })
- return err
-}
-
-// Delete deletes all events for a specific conversation ID.
-func (d *Controller) Delete(ctx context.Context, conversationID string) error {
- if conversationID == "" {
- return fmt.Errorf("conversation_id is required")
- }
-
- return d.eventLog.DeleteEvents(ctx, conversationID)
-}
-
-// Registry returns the agent registry.
-func (d *Controller) Registry() *Registry {
- return d.registry
-}
-
-// Close gracefully shuts down the controller.
-func (d *Controller) Close() error {
- if err := d.eventLog.Close(); err != nil {
- return fmt.Errorf("failed to close event log: %w", err)
- }
- if err := d.registry.Close(); err != nil {
- return fmt.Errorf("failed to close registry: %w", err)
- }
- return nil
-}
diff --git a/internal/controller/controller_test.go b/internal/controller/controller_test.go
deleted file mode 100644
index fa0b54d..0000000
--- a/internal/controller/controller_test.go
+++ /dev/null
@@ -1,506 +0,0 @@
-// 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 controller
-
-import (
- "context"
- "testing"
-
- "github.com/google/ax/internal/agent"
- "github.com/google/ax/internal/controller/executor"
- "github.com/google/ax/internal/controller/executor/executortest"
- "github.com/google/ax/proto"
-)
-
-type dummyAgent struct{}
-
-func (a *dummyAgent) Connect(ctx context.Context, conversationID string, execID string, start *proto.AgentStart, e agent.Executor, o agent.OutputHandler) error {
- return nil
-}
-
-func (a *dummyAgent) Close() error { return nil }
-
-func TestController_Exec_ResumptionAndIDGeneration(t *testing.T) {
- ctx := context.Background()
- cid := "test-conv"
-
- inputs := []*proto.Message{
- {
- Role: "user",
- Content: &proto.Content{
- Type: &proto.Content_Text{
- Text: &proto.TextContent{Text: "hello"},
- },
- },
- },
- }
-
- // Case 1: No history, new inputs. Should create a new execution with a UUID.
- log := &executortest.MemoryEventLog{}
- c, err := New(ctx, Config{
- EventLogBuilder: func() (executor.EventLog, error) {
- return log, nil
- },
- PlannerBuilder: func(ctx context.Context, r *Registry) (agent.Agent, error) {
- return &dummyAgent{}, nil
- },
- })
- if err != nil {
- t.Fatal(err)
- }
- defer c.Close()
-
- err = c.Exec(ctx, &proto.ExecRequest{
- ConversationId: cid,
- Inputs: inputs,
- }, nil)
- if err != nil {
- t.Fatal(err)
- }
- if len(log.AllEvents) == 0 {
- t.Fatal("expected events to be logged")
- }
- execID := log.AllEvents[0].ExecId
- if execID == "" || execID == cid {
- t.Fatalf("expected a new random execID, got %v", execID)
- }
-
- // Case 2: History exists, PENDING state, inputs empty. Should replay/resume.
- // Modify the event logged by logPending in Case 1 to use dummy-agent.
- log.AllEvents[len(log.AllEvents)-1].State = proto.State_STATE_PENDING
-
- err = c.Exec(ctx, &proto.ExecRequest{
- ConversationId: cid,
- Inputs: []*proto.Message{},
- }, nil)
- if err != nil {
- t.Fatal(err)
- }
- // Replay should have called `e.Exec` for that `execID`.
- lastEventID := log.AllEvents[len(log.AllEvents)-1].ExecId
- if lastEventID != execID {
- t.Fatalf("expected resumed execution ID %v, got %v", execID, lastEventID)
- }
-
- // Case 3: History exists, COMPLETED state, new inputs. Should create a NEW execution.
- for _, ev := range log.AllExecEvents {
- if ev.ExecId == execID {
- ev.State = proto.State_STATE_COMPLETED
- }
- }
- // Also populate messages in conversation log to simulate completion.
- log.AllEvents[len(log.AllEvents)-1].Messages = []*proto.Message{
- {Role: "user", Content: &proto.Content{Type: &proto.Content_Text{Text: &proto.TextContent{Text: "hello"}}}},
- }
- log.AllEvents[len(log.AllEvents)-1].State = proto.State_STATE_COMPLETED
-
- err = c.Exec(ctx, &proto.ExecRequest{
- ConversationId: cid,
- Inputs: inputs,
- }, nil)
- if err != nil {
- t.Fatal(err)
- }
-
- newExecID := log.AllEvents[len(log.AllEvents)-1].ExecId
- if newExecID == execID {
- t.Fatal("expected a NEW execution ID, but it was reused")
- }
-}
-
-func TestController_Exec_LastSeq_Empty(t *testing.T) {
- ctx := context.Background()
- cid := "test-conv-seq"
-
- log := &executortest.MemoryEventLog{}
- // Pre-populate history
- log.AllEvents = []*proto.ConversationEvent{
- {
- ConversationId: cid,
- Seq: 1,
- Messages: []*proto.Message{
- {Role: "user", Content: &proto.Content{Type: &proto.Content_Text{Text: &proto.TextContent{Text: "msg 1"}}}},
- },
- State: proto.State_STATE_COMPLETED,
- },
- {
- ConversationId: cid,
- Seq: 2,
- Messages: []*proto.Message{
- {Role: "assistant", Content: &proto.Content{Type: &proto.Content_Text{Text: &proto.TextContent{Text: "msg 2"}}}},
- },
- State: proto.State_STATE_COMPLETED,
- },
- }
-
- c, err := New(ctx, Config{
- EventLogBuilder: func() (executor.EventLog, error) {
- return log, nil
- },
- PlannerBuilder: func(ctx context.Context, r *Registry) (agent.Agent, error) {
- return &dummyAgent{}, nil
- },
- })
- if err != nil {
- t.Fatal(err)
- }
- defer c.Close()
-
- var msgs []*proto.Message
- handler := ExecHandler(func(resp *proto.ExecResponse) error {
- msgs = append(msgs, resp.Outputs...)
- return nil
- })
-
- err = c.Exec(ctx, &proto.ExecRequest{
- ConversationId: cid,
- }, handler)
- if err != nil {
- t.Fatal(err)
- }
- if len(msgs) != 0 {
- t.Fatalf("expected 0 messages, got %d", len(msgs))
- }
-}
-
-func TestController_Exec_LastSeq(t *testing.T) {
- ctx := context.Background()
- cid := "test-conv-seq"
-
- log := &executortest.MemoryEventLog{}
- // Pre-populate history
- log.AllEvents = []*proto.ConversationEvent{
- {
- ConversationId: cid,
- Seq: 1,
- Messages: []*proto.Message{
- {Role: "user", Content: &proto.Content{Type: &proto.Content_Text{Text: &proto.TextContent{Text: "msg 1"}}}},
- },
- State: proto.State_STATE_COMPLETED,
- },
- {
- ConversationId: cid,
- Seq: 2,
- Messages: []*proto.Message{
- {Role: "assistant", Content: &proto.Content{Type: &proto.Content_Text{Text: &proto.TextContent{Text: "msg 2"}}}},
- },
- State: proto.State_STATE_COMPLETED,
- },
- }
-
- c, err := New(ctx, Config{
- EventLogBuilder: func() (executor.EventLog, error) {
- return log, nil
- },
- PlannerBuilder: func(ctx context.Context, r *Registry) (agent.Agent, error) {
- return &dummyAgent{}, nil
- },
- })
- if err != nil {
- t.Fatal(err)
- }
- defer c.Close()
-
- var msgs []*proto.Message
- handler := ExecHandler(func(resp *proto.ExecResponse) error {
- msgs = append(msgs, resp.Outputs...)
- return nil
- })
-
- err = c.Exec(ctx, &proto.ExecRequest{
- ConversationId: cid,
- LastSeq: 1,
- }, handler)
- if err != nil {
- t.Fatal(err)
- }
-
- // We expect to receive messages from Seq 2 (since LastSeq is 1).
- if len(msgs) != 1 {
- t.Fatalf("expected 1 message, got %d", len(msgs))
- }
- if msgs[0].GetContent().GetText().GetText() != "msg 2" {
- t.Fatalf("expected 'msg 2', got %v", msgs[0].GetContent().GetText().GetText())
- }
-}
-
-func TestController_Exec_LastSeq_NotFound(t *testing.T) {
- ctx := context.Background()
- cid := "test-conv-seq-not-found"
-
- log := &executortest.MemoryEventLog{}
- // Pre-populate history
- log.AllEvents = []*proto.ConversationEvent{
- {
- ConversationId: cid,
- Seq: 1,
- Messages: []*proto.Message{
- {Role: "user", Content: &proto.Content{Type: &proto.Content_Text{Text: &proto.TextContent{Text: "msg 1"}}}},
- },
- State: proto.State_STATE_COMPLETED,
- },
- }
-
- c, err := New(ctx, Config{
- EventLogBuilder: func() (executor.EventLog, error) {
- return log, nil
- },
- PlannerBuilder: func(ctx context.Context, r *Registry) (agent.Agent, error) {
- return &dummyAgent{}, nil
- },
- })
- if err != nil {
- t.Fatal(err)
- }
- defer c.Close()
-
- handler := ExecHandler(func(resp *proto.ExecResponse) error {
- return nil
- })
-
- err = c.Exec(ctx, &proto.ExecRequest{
- ConversationId: cid,
- LastSeq: 99,
- }, handler)
- if err == nil {
- t.Fatal("expected error when LastSeq is not found, got nil")
- }
- if err.Error() != "last_seq 99 not found" {
- t.Fatalf("expected 'last_seq 99 not found', got %v", err)
- }
-}
-
-func TestController_Exec_WaitsForConfirmation(t *testing.T) {
- ctx := context.Background()
- cid := "test-conv-conf"
- execID := "test-exec-conf"
-
- log := &executortest.MemoryEventLog{}
-
- // 1. History has a pending execution.
- log.AllEvents = []*proto.ConversationEvent{
- {
- ConversationId: cid,
- ExecId: execID,
- State: proto.State_STATE_PENDING,
- Seq: 1,
- },
- }
-
- // 2. The execution history ends with a confirmation question.
- questionMsg := &proto.Message{
- Role: "assistant",
- Content: &proto.Content{
- Type: &proto.Content_Confirmation{
- Confirmation: &proto.ConfirmationContent{
- Question: "Are you sure?",
- },
- },
- },
- }
-
- log.AllExecEvents = []*proto.ExecutionEvent{
- {
- ExecId: execID,
- AgentId: "__planner",
- State: proto.State_STATE_PENDING,
- Outputs: []*proto.Message{
- questionMsg,
- },
- },
- }
-
- c, err := New(ctx, Config{
- EventLogBuilder: func() (executor.EventLog, error) {
- return log, nil
- },
- PlannerBuilder: func(ctx context.Context, r *Registry) (agent.Agent, error) {
- return &dummyAgent{}, nil
- },
- })
- if err != nil {
- t.Fatal(err)
- }
- defer c.Close()
-
- var msgs []*proto.Message
- handler := ExecHandler(func(resp *proto.ExecResponse) error {
- msgs = append(msgs, resp.Outputs...)
- return nil
- })
-
- // Call Exec without providing an answer.
- err = c.Exec(ctx, &proto.ExecRequest{
- ConversationId: cid,
- }, handler)
- if err != nil {
- t.Fatal(err)
- }
-
- // We expect to receive the confirmation question again.
- if len(msgs) != 1 {
- t.Fatalf("expected 1 message, got %d", len(msgs))
- }
- if msgs[0].GetContent().GetConfirmation().GetQuestion() != "Are you sure?" {
- t.Fatalf("expected 'Are you sure?', got %v", msgs[0].GetContent().GetConfirmation().GetQuestion())
- }
-}
-
-func TestController_Exec_InternalOnly(t *testing.T) {
- ctx := context.Background()
- cid := "test-conv-internal"
-
- log := &executortest.MemoryEventLog{}
-
- // Create an agent that emits one internal-only message and one regular message.
- a := &mockAgentFunc{
- connectFunc: func(ctx context.Context, conversationID string, execID string, start *proto.AgentStart, e agent.Executor, o agent.OutputHandler) error {
- // If we already have the public message in history, don't emit anything.
- for _, m := range start.Messages {
- if m.GetContent().GetText().GetText() == "public message" {
- return nil
- }
- }
- // Emit internal-only message
- if err := o(&proto.AgentOutputs{
- Messages: []*proto.Message{
- {
- Role: "assistant",
- InternalOnly: true,
- Content: &proto.Content{Type: &proto.Content_Text{Text: &proto.TextContent{Text: "internal message"}}},
- },
- },
- }); err != nil {
- return err
- }
- // Emit regular message
- return o(&proto.AgentOutputs{
- Messages: []*proto.Message{
- {Role: "assistant", Content: &proto.Content{Type: &proto.Content_Text{Text: &proto.TextContent{Text: "public message"}}}},
- },
- })
- },
- }
-
- c, err := New(ctx, Config{
- EventLogBuilder: func() (executor.EventLog, error) {
- return log, nil
- },
- PlannerBuilder: func(ctx context.Context, r *Registry) (agent.Agent, error) {
- return a, nil
- },
- })
- if err != nil {
- t.Fatal(err)
- }
- defer c.Close()
-
- var msgs []*proto.Message
- handler := ExecHandler(func(resp *proto.ExecResponse) error {
- msgs = append(msgs, resp.Outputs...)
- return nil
- })
-
- err = c.Exec(ctx, &proto.ExecRequest{
- ConversationId: cid,
- Inputs: []*proto.Message{
- {Role: "user", Content: &proto.Content{Type: &proto.Content_Text{Text: &proto.TextContent{Text: "hello"}}}},
- },
- }, handler)
- if err != nil {
- t.Fatal(err)
- }
-
- // Verify that ONLY the public message was emitted.
- if len(msgs) != 1 {
- t.Fatalf("expected 1 message emitted, got %d", len(msgs))
- }
- if msgs[0].GetContent().GetText().GetText() != "public message" {
- t.Fatalf("expected 'public message', got %v", msgs[0].GetContent().GetText().GetText())
- }
-
- // Verify that internal messages are NOT stored in ConversationEvent.
- if len(log.AllEvents) != 3 {
- t.Fatalf("expected 3 events in log.AllEvents, got %d", len(log.AllEvents))
- }
-
- // Event 0: Inputs
- // Event 1: Public message
- if log.AllEvents[1].Messages[0].GetContent().GetText().GetText() != "public message" {
- t.Fatalf("expected 'public message' in log.AllEvents, got %v", log.AllEvents[1].Messages[0].GetContent().GetText().GetText())
- }
-
- // Verify that BOTH messages ARE stored in ExecutionEvent.
- if len(log.AllExecEvents) != 3 {
- t.Fatalf("expected 3 events in log.AllExecEvents, got %d", len(log.AllExecEvents))
- }
-
- // Event 1 in execEvents should contain both outputs.
- outputs := log.AllExecEvents[1].Outputs
- if len(outputs) != 2 {
- t.Fatalf("expected 2 outputs in execEvent, got %d", len(outputs))
- }
- if outputs[0].GetContent().GetText().GetText() != "internal message" {
- t.Fatalf("expected 'internal message' in execEvent, got %v", outputs[0].GetContent().GetText().GetText())
- }
- if outputs[1].GetContent().GetText().GetText() != "public message" {
- t.Fatalf("expected 'public message' in execEvent, got %v", outputs[1].GetContent().GetText().GetText())
- }
-
- // Test resumption with LastSeq
- var resumedMsgs []*proto.Message
- resumedHandler := ExecHandler(func(resp *proto.ExecResponse) error {
- resumedMsgs = append(resumedMsgs, resp.Outputs...)
- return nil
- })
-
- c2, err := New(ctx, Config{
- EventLogBuilder: func() (executor.EventLog, error) {
- return log, nil
- },
- PlannerBuilder: func(ctx context.Context, r *Registry) (agent.Agent, error) {
- return a, nil
- },
- })
- if err != nil {
- t.Fatal(err)
- }
- defer c2.Close()
-
- err = c2.Exec(ctx, &proto.ExecRequest{
- ConversationId: cid,
- LastSeq: 1,
- }, resumedHandler)
- if err != nil {
- t.Fatal(err)
- }
-
- if len(resumedMsgs) != 1 {
- t.Fatalf("expected 1 message resumed, got %d", len(resumedMsgs))
- }
- if resumedMsgs[0].GetContent().GetText().GetText() != "public message" {
- t.Fatalf("expected 'public message' resumed, got %v", resumedMsgs[0].GetContent().GetText().GetText())
- }
-}
-
-type mockAgentFunc struct {
- connectFunc func(ctx context.Context, conversationID string, execID string, start *proto.AgentStart, e agent.Executor, o agent.OutputHandler) error
-}
-
-func (m *mockAgentFunc) Connect(ctx context.Context, conversationID string, execID string, start *proto.AgentStart, e agent.Executor, o agent.OutputHandler) error {
- return m.connectFunc(ctx, conversationID, execID, start, e, o)
-}
-
-func (m *mockAgentFunc) Close() error { return nil }
diff --git a/internal/controller/executor/agent_executor.go b/internal/controller/executor/agent_executor.go
deleted file mode 100644
index 82f6cc4..0000000
--- a/internal/controller/executor/agent_executor.go
+++ /dev/null
@@ -1,111 +0,0 @@
-// 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 executor
-
-import (
- "context"
- "errors"
-
- "github.com/google/ax/internal/agent"
- "github.com/google/ax/internal/historyutil"
- "github.com/google/ax/proto"
- "google.golang.org/protobuf/types/known/timestamppb"
-)
-
-// AgentExecutor returns an Executor suitable for invoking sub-agents from
-// within a planner or another agent's Connect method.
-//
-// Unlike DefaultExecutor (which is the controller's top-level conversation
-// runner), AgentExecutor:
-// - Does NOT load conversation history from the event log; the caller
-// passes the relevant messages in start.Messages.
-// - Does NOT short-circuit on WaitsForConfirmation or COMPLETED cache.
-// - DOES write execution-level logs (pending, outputs, completed) for
-// observability, but omits the WaitsForConfirmation/COMPLETED guards
-// that DefaultExecutor uses.
-// - Returns STATE_PENDING when the sub-agent's last output is an
-// unanswered confirmation question.
-func AgentExecutor(eventLog EventLog, registry map[string]agent.Agent) agent.Executor {
- return &agentExecutor{
- eventLog: eventLog,
- registry: registry,
- }
-}
-
-type agentExecutor struct {
- execID string
- eventLog EventLog
- registry map[string]agent.Agent
-}
-
-func (ae *agentExecutor) Exec(ctx context.Context, conversationID string, execID string, start *proto.AgentStart, o agent.OutputHandler) (proto.State, error) {
- execID = newExecID(ae.execID, execID)
- a, ok := ae.registry[start.AgentId]
- if !ok {
- return proto.State_STATE_UNSPECIFIED, errors.New("no agent found: " + start.AgentId)
- }
-
- // Log pending execution event with inputs for debuggability.
- if err := ae.eventLog.AppendExec(ctx, &proto.ExecutionEvent{
- Timestamp: timestamppb.Now(),
- ExecId: execID,
- AgentId: start.AgentId,
- Inputs: start.Messages,
- State: proto.State_STATE_PENDING,
- }); err != nil {
- return proto.State_STATE_UNSPECIFIED, err
- }
-
- var allOutputs []*proto.Message
- outputBuffer := func(outgoing *proto.AgentOutputs) error {
- allOutputs = append(allOutputs, outgoing.Messages...)
- if o != nil {
- return o(outgoing)
- }
- return nil
- }
-
- if err := a.Connect(ctx, conversationID, execID, start, &agentExecutor{execID: execID, eventLog: ae.eventLog, registry: ae.registry}, outputBuffer); err != nil {
- return proto.State_STATE_UNSPECIFIED, err
- }
-
- // Log outputs.
- if len(allOutputs) > 0 {
- if err := ae.eventLog.AppendExec(ctx, &proto.ExecutionEvent{
- Timestamp: timestamppb.Now(),
- ExecId: execID,
- AgentId: start.AgentId,
- Outputs: allOutputs,
- State: proto.State_STATE_PENDING,
- }); err != nil {
- return proto.State_STATE_UNSPECIFIED, err
- }
-
- if historyutil.WaitsForConfirmation(allOutputs) != nil {
- return proto.State_STATE_PENDING, nil
- }
- }
-
- // Log completed.
- if err := ae.eventLog.AppendExec(ctx, &proto.ExecutionEvent{
- Timestamp: timestamppb.Now(),
- ExecId: execID,
- AgentId: start.AgentId,
- State: proto.State_STATE_COMPLETED,
- }); err != nil {
- return proto.State_STATE_UNSPECIFIED, err
- }
- return proto.State_STATE_COMPLETED, nil
-}
diff --git a/internal/controller/executor/agent_executor_test.go b/internal/controller/executor/agent_executor_test.go
deleted file mode 100644
index ed9aa82..0000000
--- a/internal/controller/executor/agent_executor_test.go
+++ /dev/null
@@ -1,349 +0,0 @@
-// 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 executor
-
-import (
- "context"
- "sync/atomic"
- "testing"
-
- "github.com/google/ax/internal/agent"
- "github.com/google/ax/internal/controller/executor/executortest"
- "github.com/google/ax/proto"
-)
-
-func TestAgentExecutor_BasicExec(t *testing.T) {
- ctx := context.Background()
- eventLog := &executortest.MemoryEventLog{}
-
- registry := map[string]agent.Agent{
- "echo": AgentFunc(func(inputs []*proto.Message, tm agent.Executor, o agent.OutputHandler) {
- if o != nil {
- o(&proto.AgentOutputs{
- Messages: []*proto.Message{text("assistant", "hello from echo")},
- })
- }
- }),
- }
-
- ae := AgentExecutor(eventLog, registry)
- var received []*proto.Message
- handler := func(outgoing *proto.AgentOutputs) error {
- received = append(received, outgoing.Messages...)
- return nil
- }
-
- state, err := ae.Exec(ctx, "conv-1", "exec-1", &proto.AgentStart{
- AgentId: "echo",
- Messages: []*proto.Message{text("user", "hi")},
- }, handler)
- if err != nil {
- t.Fatal(err)
- }
-
- if state != proto.State_STATE_COMPLETED {
- t.Fatalf("expected STATE_COMPLETED, got %v", state)
- }
- if len(received) != 1 {
- t.Fatalf("expected 1 output message, got %d", len(received))
- }
- if received[0].GetContent().GetText().GetText() != "hello from echo" {
- t.Fatalf("expected 'hello from echo', got %v", received[0].GetContent().GetText().GetText())
- }
-
- // Verify event log entries: pending, outputs, completed.
- if len(eventLog.AllExecEvents) != 3 {
- t.Fatalf("expected 3 exec events (pending, outputs, completed), got %d", len(eventLog.AllExecEvents))
- }
- if eventLog.AllExecEvents[0].State != proto.State_STATE_PENDING {
- t.Fatalf("expected first event STATE_PENDING, got %v", eventLog.AllExecEvents[0].State)
- }
- if len(eventLog.AllExecEvents[1].Outputs) != 1 {
- t.Fatalf("expected 1 output in second event, got %d", len(eventLog.AllExecEvents[1].Outputs))
- }
- if eventLog.AllExecEvents[2].State != proto.State_STATE_COMPLETED {
- t.Fatalf("expected last event STATE_COMPLETED, got %v", eventLog.AllExecEvents[2].State)
- }
-}
-
-func TestAgentExecutor_ConfirmationReturnsPending(t *testing.T) {
- ctx := context.Background()
- eventLog := &executortest.MemoryEventLog{}
-
- confID := "conf-42"
-
- var callCount atomic.Int32
- registry := map[string]agent.Agent{
- "confirmer": AgentFunc(func(inputs []*proto.Message, tm agent.Executor, o agent.OutputHandler) {
- callCount.Add(1)
- run := callCount.Load()
-
- if run == 1 {
- // First invocation: emit a confirmation question.
- if o != nil {
- o(&proto.AgentOutputs{
- Messages: []*proto.Message{{
- Role: "model",
- Content: &proto.Content{
- Type: &proto.Content_Confirmation{
- Confirmation: &proto.ConfirmationContent{
- Id: confID,
- Question: "proceed?",
- },
- },
- },
- }},
- })
- }
- return
- }
-
- // Second invocation: emit completion text.
- if o != nil {
- o(&proto.AgentOutputs{
- Messages: []*proto.Message{text("assistant", "confirmed and done")},
- })
- }
- }),
- }
-
- ae := AgentExecutor(eventLog, registry)
-
- // --- First call: should return STATE_PENDING ---
- var firstOutputs []*proto.Message
- state, err := ae.Exec(ctx, "conv-1", "exec-conf", &proto.AgentStart{
- AgentId: "confirmer",
- Messages: []*proto.Message{text("user", "do something risky")},
- }, func(outgoing *proto.AgentOutputs) error {
- firstOutputs = append(firstOutputs, outgoing.Messages...)
- return nil
- })
- if err != nil {
- t.Fatal(err)
- }
- if state != proto.State_STATE_PENDING {
- t.Fatalf("expected STATE_PENDING, got %v", state)
- }
- if len(firstOutputs) != 1 {
- t.Fatalf("expected 1 output, got %d", len(firstOutputs))
- }
- if firstOutputs[0].GetContent().GetConfirmation().GetQuestion() != "proceed?" {
- t.Fatalf("expected confirmation question 'proceed?', got %v",
- firstOutputs[0].GetContent().GetConfirmation().GetQuestion())
- }
-
- // --- Second call: provide approval, should return STATE_COMPLETED ---
- // agentExecutor does NOT check history/cache, so re-invoking with new
- // start.Messages should call the agent again (callCount goes to 2).
- approval := &proto.Message{
- Role: "user",
- Content: &proto.Content{
- Type: &proto.Content_Confirmation{
- Confirmation: &proto.ConfirmationContent{
- Id: confID,
- Decision: &proto.ConfirmationContent_Approval{
- Approval: &proto.ApprovalDecision{Approved: true},
- },
- },
- },
- },
- }
-
- var secondOutputs []*proto.Message
- state, err = ae.Exec(ctx, "conv-1", "exec-conf", &proto.AgentStart{
- AgentId: "confirmer",
- Messages: []*proto.Message{approval},
- }, func(outgoing *proto.AgentOutputs) error {
- secondOutputs = append(secondOutputs, outgoing.Messages...)
- return nil
- })
- if err != nil {
- t.Fatal(err)
- }
- if state != proto.State_STATE_COMPLETED {
- t.Fatalf("expected STATE_COMPLETED on second call, got %v", state)
- }
- if callCount.Load() != 2 {
- t.Fatalf("expected agent called 2 times, got %d", callCount.Load())
- }
- if len(secondOutputs) != 1 {
- t.Fatalf("expected 1 output on second call, got %d", len(secondOutputs))
- }
- if secondOutputs[0].GetContent().GetText().GetText() != "confirmed and done" {
- t.Fatalf("expected 'confirmed and done', got %v",
- secondOutputs[0].GetContent().GetText().GetText())
- }
-}
-
-func TestAgentExecutor_NoHistoryLoading(t *testing.T) {
- ctx := context.Background()
- eventLog := &executortest.MemoryEventLog{}
-
- execID := "exec-completed"
- agentID := "worker"
-
- // Pre-populate event log with a COMPLETED execution for the same execID.
- // defaultExecutor would short-circuit at executor.go:78 and return
- // STATE_COMPLETED without calling the agent. agentExecutor must NOT
- // do this — it should always invoke the agent.
- eventLog.AllExecEvents = []*proto.ExecutionEvent{
- {
- ExecId: execID,
- AgentId: agentID,
- State: proto.State_STATE_PENDING,
- Inputs: []*proto.Message{text("user", "old input")},
- },
- {
- ExecId: execID,
- AgentId: agentID,
- Outputs: []*proto.Message{text("assistant", "old output")},
- State: proto.State_STATE_PENDING,
- },
- {
- ExecId: execID,
- AgentId: agentID,
- State: proto.State_STATE_COMPLETED,
- },
- }
-
- var agentCalled atomic.Bool
- registry := map[string]agent.Agent{
- agentID: AgentFunc(func(inputs []*proto.Message, tm agent.Executor, o agent.OutputHandler) {
- agentCalled.Store(true)
- if o != nil {
- o(&proto.AgentOutputs{
- Messages: []*proto.Message{text("assistant", "fresh output")},
- })
- }
- }),
- }
-
- ae := AgentExecutor(eventLog, registry)
-
- var outputs []*proto.Message
- state, err := ae.Exec(ctx, "conv-1", execID, &proto.AgentStart{
- AgentId: agentID,
- Messages: []*proto.Message{text("user", "new input")},
- }, func(outgoing *proto.AgentOutputs) error {
- outputs = append(outputs, outgoing.Messages...)
- return nil
- })
- if err != nil {
- t.Fatal(err)
- }
-
- if !agentCalled.Load() {
- t.Fatal("agent was NOT called — agentExecutor must not short-circuit on COMPLETED history")
- }
- if state != proto.State_STATE_COMPLETED {
- t.Fatalf("expected STATE_COMPLETED, got %v", state)
- }
- if len(outputs) != 1 {
- t.Fatalf("expected 1 output, got %d", len(outputs))
- }
- if outputs[0].GetContent().GetText().GetText() != "fresh output" {
- t.Fatalf("expected 'fresh output', got %v", outputs[0].GetContent().GetText().GetText())
- }
-
- // Also verify that defaultExecutor WOULD short-circuit for the same setup,
- // confirming agentExecutor's behavior is intentionally different.
- agentCalled.Store(false)
- de := DefaultExecutor(eventLog, registry)
- deState, err := de.Exec(ctx, "conv-1", execID, &proto.AgentStart{
- AgentId: agentID,
- Messages: []*proto.Message{text("user", "new input")},
- }, nil)
- if err != nil {
- t.Fatal(err)
- }
- if deState != proto.State_STATE_COMPLETED {
- t.Fatalf("defaultExecutor: expected STATE_COMPLETED, got %v", deState)
- }
- if agentCalled.Load() {
- t.Fatal("defaultExecutor should have short-circuited but called the agent")
- }
-}
-
-func TestAgentExecutor_AgentNotFound(t *testing.T) {
- ctx := context.Background()
- eventLog := &executortest.MemoryEventLog{}
-
- ae := AgentExecutor(eventLog, map[string]agent.Agent{})
- _, err := ae.Exec(ctx, "conv-1", "exec-1", &proto.AgentStart{
- AgentId: "nonexistent",
- Messages: []*proto.Message{text("user", "hi")},
- }, nil)
- if err == nil {
- t.Fatal("expected error for missing agent, got nil")
- }
- if err.Error() != "no agent found: nonexistent" {
- t.Fatalf("expected 'no agent found: nonexistent', got: %v", err)
- }
-}
-
-func TestAgentExecutor_NilHandler(t *testing.T) {
- ctx := context.Background()
- eventLog := &executortest.MemoryEventLog{}
-
- registry := map[string]agent.Agent{
- "silent": AgentFunc(func(inputs []*proto.Message, tm agent.Executor, o agent.OutputHandler) {
- if o != nil {
- o(&proto.AgentOutputs{
- Messages: []*proto.Message{text("assistant", "output")},
- })
- }
- }),
- }
-
- ae := AgentExecutor(eventLog, registry)
- state, err := ae.Exec(ctx, "conv-1", "exec-nil", &proto.AgentStart{
- AgentId: "silent",
- Messages: []*proto.Message{text("user", "hi")},
- }, nil)
- if err != nil {
- t.Fatal(err)
- }
- if state != proto.State_STATE_COMPLETED {
- t.Fatalf("expected STATE_COMPLETED with nil handler, got %v", state)
- }
-}
-
-func TestAgentExecutor_NoOutputs(t *testing.T) {
- ctx := context.Background()
- eventLog := &executortest.MemoryEventLog{}
-
- registry := map[string]agent.Agent{
- "noop": AgentFunc(func(inputs []*proto.Message, tm agent.Executor, o agent.OutputHandler) {
- // Agent does nothing, emits no outputs.
- }),
- }
-
- ae := AgentExecutor(eventLog, registry)
- state, err := ae.Exec(ctx, "conv-1", "exec-noop", &proto.AgentStart{
- AgentId: "noop",
- Messages: []*proto.Message{text("user", "hi")},
- }, nil)
- if err != nil {
- t.Fatal(err)
- }
- if state != proto.State_STATE_COMPLETED {
- t.Fatalf("expected STATE_COMPLETED for no-output agent, got %v", state)
- }
-
- // Should have pending + completed events (no outputs event).
- if len(eventLog.AllExecEvents) != 2 {
- t.Fatalf("expected 2 exec events (pending, completed), got %d", len(eventLog.AllExecEvents))
- }
-}
diff --git a/internal/controller/executor/eventlog.go b/internal/controller/executor/eventlog.go
deleted file mode 100644
index 4f52302..0000000
--- a/internal/controller/executor/eventlog.go
+++ /dev/null
@@ -1,48 +0,0 @@
-// 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 executor
-
-import (
- "context"
-
- "github.com/google/ax/proto"
- "google.golang.org/protobuf/encoding/protojson"
-)
-
-// EventLog is the persistent, append-only record of all actions taken in an
-// exec. Every entry is an atomic step: replaying the log in order brings
-// the executor back to a consistent state from which execution can resume.
-type EventLog interface {
- // Append adds a conversation event to the end of the log.
- Append(ctx context.Context, event *proto.ConversationEvent) (int32, error)
-
- // AppendExec adds an execution event to the end of the log.
- AppendExec(ctx context.Context, event *proto.ExecutionEvent) error
-
- // Events returns all events for the conversation.
- Events(ctx context.Context, conversationID string) ([]*proto.ConversationEvent, error)
-
- // ExecEvents returns all events for a specific execution ID.
- ExecEvents(ctx context.Context, execID string) ([]*proto.ExecutionEvent, error)
-
- // DeleteEvents deletes all events for a specific conversation ID.
- DeleteEvents(ctx context.Context, conversationID string) error
-
- // Close releases the underlying resources and closes the log.
- Close() error
-}
-
-var marshalOpts = protojson.MarshalOptions{UseProtoNames: true}
-var unmarshalOpts = protojson.UnmarshalOptions{DiscardUnknown: true}
diff --git a/internal/controller/executor/executor.go b/internal/controller/executor/executor.go
deleted file mode 100644
index b911ffb..0000000
--- a/internal/controller/executor/executor.go
+++ /dev/null
@@ -1,205 +0,0 @@
-// 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 executor
-
-import (
- "context"
- "errors"
- "fmt"
-
- "github.com/google/ax/internal/agent"
- "github.com/google/ax/internal/historyutil"
- "github.com/google/ax/proto"
- "google.golang.org/protobuf/types/known/timestamppb"
-)
-
-type EventLogBuilder func() (EventLog, error)
-
-type defaultExecutor struct {
- execID string
- eventLog EventLog
- registry map[string]agent.Agent
-}
-
-func newExecID(parent, child string) string {
- if parent == "" {
- return child
- }
- return parent + "-" + child
-}
-
-func DefaultExecutor(eventLog EventLog, registry map[string]agent.Agent) agent.Executor {
- return &defaultExecutor{
- execID: "",
- eventLog: eventLog,
- registry: registry,
- }
-}
-
-func (de *defaultExecutor) Exec(ctx context.Context, conversationID string, execID string, start *proto.AgentStart, o agent.OutputHandler) (proto.State, error) {
- execID = newExecID(de.execID, execID)
- a, ok := de.registry[start.AgentId]
- if !ok {
- return proto.State_STATE_UNSPECIFIED, errors.New("no agent found")
- }
-
- allInputs, state, earlierAgentID, err := history(ctx, de.eventLog, execID)
- if err != nil {
- return proto.State_STATE_UNSPECIFIED, err
- }
-
- if msg := historyutil.WaitsForConfirmation(allInputs); msg != nil {
- // Ensure that the inputs contain the answer to the
- // confirmation to continue.
- _, conf := historyutil.HasConfirmationAnswer(start.Messages)
- if conf == nil {
- return proto.State_STATE_PENDING, o(&proto.AgentOutputs{
- Messages: []*proto.Message{msg},
- })
- }
- }
-
- if earlierAgentID != "" && earlierAgentID != start.AgentId {
- return proto.State_STATE_UNSPECIFIED, fmt.Errorf("resumption not allowed: agent ID changed from %s to %s", earlierAgentID, start.AgentId)
- }
-
- if state == proto.State_STATE_COMPLETED {
- return proto.State_STATE_COMPLETED, nil
- }
- return de.exec(ctx, conversationID, execID, start, de.eventLog, a, allInputs, o)
-}
-
-func (de *defaultExecutor) exec(
- ctx context.Context,
- conversationID string,
- execID string,
- start *proto.AgentStart,
- el EventLog,
- a agent.Agent,
- history []*proto.Message,
- o agent.OutputHandler) (proto.State, error) {
- child := &agentExecutor{
- execID: execID,
- eventLog: de.eventLog,
- registry: de.registry,
- }
-
- var allOutputs []*proto.Message
- outputBuffer := func(outgoing *proto.AgentOutputs) error {
- allOutputs = append(allOutputs, outgoing.Messages...)
- if o != nil {
- return o(outgoing)
- }
- return nil
- }
-
- history = append(history, start.Messages...)
- if len(history) == 0 {
- return proto.State_STATE_UNSPECIFIED, errors.New("no inputs")
- }
- if err := logPending(ctx, el, execID, start); err != nil {
- return proto.State_STATE_UNSPECIFIED, err
- }
-
- start.Messages = history
- if err := a.Connect(ctx, conversationID, execID, start, child, outputBuffer); err != nil {
- // _ = logFailed(ctx, el, execID, start) // Attempt to log failure, but prioritize returning the original error.
- return proto.State_STATE_UNSPECIFIED, err
- }
-
- if len(allOutputs) > 0 {
- // Log all the outputs at once.
- // TODO: Log only at checkpoints.
- if err := logOutputs(ctx, el, execID, start, allOutputs); err != nil {
- return proto.State_STATE_UNSPECIFIED, err
- }
-
- last := allOutputs[len(allOutputs)-1]
- if last.GetContent().GetConfirmation() == nil || last.GetContent().GetConfirmation().GetQuestion() == "" {
- // Log completed only if we are not waiting
- // for an answer to a confirmation.
- if err := logCompleted(ctx, el, execID, start); err != nil {
- return proto.State_STATE_UNSPECIFIED, err
- }
- return proto.State_STATE_COMPLETED, nil
- }
- }
- return proto.State_STATE_PENDING, nil
-}
-
-func history(ctx context.Context, el EventLog, execID string) ([]*proto.Message, proto.State, string, error) {
- var history []*proto.Message
-
- var state proto.State
- var agentID string
-
- if execID != "" {
- execEvents, err := el.ExecEvents(ctx, execID)
- if err != nil {
- return nil, proto.State_STATE_UNSPECIFIED, "", err
- }
- for _, ev := range execEvents {
- if ev.State != proto.State_STATE_UNSPECIFIED {
- state = ev.State
- }
- if ev.AgentId != "" {
- agentID = ev.AgentId
- }
- history = append(history, ev.Inputs...)
- history = append(history, ev.Outputs...)
- }
- }
-
- return history, state, agentID, nil
-}
-
-func logPending(ctx context.Context, el EventLog, execID string, start *proto.AgentStart) error {
- return el.AppendExec(ctx, &proto.ExecutionEvent{
- Timestamp: timestamppb.Now(),
- ExecId: execID,
- AgentId: start.AgentId,
- AgentConfig: start.AgentConfig,
- Inputs: start.Messages,
- State: proto.State_STATE_PENDING,
- })
-}
-
-func logFailed(ctx context.Context, el EventLog, execID string, start *proto.AgentStart) error {
- return el.AppendExec(ctx, &proto.ExecutionEvent{
- Timestamp: timestamppb.Now(),
- ExecId: execID,
- AgentId: start.AgentId,
- State: proto.State_STATE_FAILED,
- })
-}
-
-func logCompleted(ctx context.Context, el EventLog, execID string, start *proto.AgentStart) error {
- return el.AppendExec(ctx, &proto.ExecutionEvent{
- Timestamp: timestamppb.Now(),
- ExecId: execID,
- AgentId: start.AgentId,
- State: proto.State_STATE_COMPLETED,
- })
-}
-
-func logOutputs(ctx context.Context, el EventLog, execID string, start *proto.AgentStart, outputs []*proto.Message) error {
- return el.AppendExec(ctx, &proto.ExecutionEvent{
- Timestamp: timestamppb.Now(),
- ExecId: execID,
- AgentId: start.AgentId,
- Outputs: outputs,
- State: proto.State_STATE_PENDING,
- })
-}
diff --git a/internal/controller/executor/executor_test.go b/internal/controller/executor/executor_test.go
deleted file mode 100644
index 79f44a4..0000000
--- a/internal/controller/executor/executor_test.go
+++ /dev/null
@@ -1,454 +0,0 @@
-// 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 executor
-
-import (
- "context"
- "fmt"
- "log"
- "strings"
- "sync/atomic"
- "testing"
- "time"
-
- "github.com/google/ax/internal/agent"
- "github.com/google/ax/internal/controller/executor/executortest"
- "github.com/google/ax/internal/historyutil"
- "github.com/google/ax/proto"
- "golang.org/x/sync/errgroup"
-)
-
-// memoryEventLog returns a new EventLogBuilder that creates a fresh MemoryEventLog per task.
-func memoryEventLog() EventLog {
- return &executortest.MemoryEventLog{}
-}
-
-func Example() {
- ctx := context.Background()
-
- registry := map[string]agent.Agent{
- "planner": AgentFunc(func(inputs []*proto.Message, tm agent.Executor, o agent.OutputHandler) {
- if _, err := tm.Exec(ctx, "test-conv", "deep-research-task", &proto.AgentStart{
- AgentId: "deep-research",
- Messages: inputs,
- }, o); err != nil {
- return
- }
-
- if _, err := tm.Exec(ctx, "test-conv", "pub-med-lookup-task", &proto.AgentStart{
- AgentId: "pub-med-index",
- Messages: inputs,
- }, o); err != nil {
- return
- }
- }),
- }
-
- tm := DefaultExecutor(memoryEventLog(), registry)
- if _, err := tm.Exec(ctx, "test-conv", "test", &proto.AgentStart{
- AgentId: "planner",
- Messages: []*proto.Message{text("user", "Hello, I'd like to research cancer treatment options.")},
- }, nil); err != nil {
- log.Fatal(err)
- }
-}
-
-func TestTaskManager(t *testing.T) {
- ctx := context.Background()
-
- registry := map[string]agent.Agent{
- "root": AgentFunc(func(inputs []*proto.Message, tm agent.Executor, o agent.OutputHandler) {
- if _, err := tm.Exec(ctx, "test-conv", "child-task", &proto.AgentStart{
- AgentId: "child",
- Messages: inputs,
- }, o); err != nil {
- t.Fatal(err)
- }
- if o != nil {
- o(&proto.AgentOutputs{
- Messages: []*proto.Message{text("assistant", "root done")},
- })
- }
- }),
- "child": AgentFunc(func(inputs []*proto.Message, tm agent.Executor, o agent.OutputHandler) {
- time.Sleep(100 * time.Millisecond)
- if o != nil {
- o(&proto.AgentOutputs{
- Messages: []*proto.Message{text("assistant", "child done")},
- })
- }
- }),
- }
-
- tm := DefaultExecutor(memoryEventLog(), registry)
- if _, err := tm.Exec(ctx, "test-conv", "root-task", &proto.AgentStart{
- AgentId: "root",
- Messages: []*proto.Message{text("user", "hello!")},
- }, nil); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestFanout(t *testing.T) {
- ctx := context.Background()
-
- var executions atomic.Int32
- registry := map[string]agent.Agent{
- "root": AgentFunc(func(inputs []*proto.Message, tm agent.Executor, o agent.OutputHandler) {
- var g errgroup.Group
- for i := range 50 {
- i := i // Capture loop variable.
- g.Go(func() error {
- _, err := tm.Exec(ctx, "test-conv", fmt.Sprintf("child-%d", i), &proto.AgentStart{
- AgentId: "child",
- Messages: inputs,
- }, nil)
- return err
- })
- }
- if err := g.Wait(); err != nil {
- t.Fatal(err)
- }
- if o != nil {
- o(&proto.AgentOutputs{
- Messages: []*proto.Message{text("assistant", "root done")},
- })
- }
- }),
- "child": AgentFunc(func(inputs []*proto.Message, tm agent.Executor, o agent.OutputHandler) {
- executions.Add(1)
- time.Sleep(100 * time.Millisecond)
-
- var g errgroup.Group
- for i := range 2 {
- i := i // Capture loop variable.
- g.Go(func() error {
- _, err := tm.Exec(ctx, "test-conv", fmt.Sprintf("child2-%d", i), &proto.AgentStart{
- AgentId: "child2",
- Messages: inputs,
- }, nil)
- return err
- })
- }
- if err := g.Wait(); err != nil {
- t.Fatal(err)
- }
- if o != nil {
- o(&proto.AgentOutputs{
- Messages: []*proto.Message{text("assistant", "child done")},
- })
- }
- }),
- "child2": AgentFunc(func(inputs []*proto.Message, tm agent.Executor, o agent.OutputHandler) {
- executions.Add(1)
- time.Sleep(100 * time.Millisecond)
- if o != nil {
- o(&proto.AgentOutputs{
- Messages: []*proto.Message{text("assistant", "child2 done")},
- })
- }
- }),
- }
-
- tm := DefaultExecutor(memoryEventLog(), registry)
- if _, err := tm.Exec(ctx, "test-conv", "root-task", &proto.AgentStart{
- AgentId: "root",
- Messages: []*proto.Message{text("user", "hello!")},
- }, nil); err != nil {
- t.Fatal(err)
- }
-
- if got, want := executions.Load(), int32(150); got != want {
- t.Fatalf("executions got %v; want %v", got, want)
- }
-}
-
-func TestConfirmation(t *testing.T) {
- ctx := context.Background()
-
- var runCount int
- eventLog := memoryEventLog()
-
- confID := "test-conf-id"
- var childDone atomic.Bool
- registry := map[string]agent.Agent{
- "root": AgentFunc(func(inputs []*proto.Message, tm agent.Executor, o agent.OutputHandler) {
- if _, err := tm.Exec(ctx, "test-conv", "child-task", &proto.AgentStart{
- AgentId: "child",
- Messages: inputs,
- }, o); err != nil {
- t.Fatal(err)
- }
- }),
- "child": AgentFunc(func(inputs []*proto.Message, tm agent.Executor, o agent.OutputHandler) {
- if runCount == 0 {
- runCount++
- log.Println("Asking for the question...")
- if o != nil {
- o(&proto.AgentOutputs{
- Messages: []*proto.Message{{
- Role: "model",
- Content: &proto.Content{
- Type: &proto.Content_Confirmation{
- Confirmation: &proto.ConfirmationContent{Id: confID, Question: "proceed?"},
- },
- },
- }},
- })
- }
- return
- }
-
- lastInput := inputs[len(inputs)-1]
- if lastInput.GetContent().GetConfirmation() == nil || lastInput.GetContent().GetConfirmation().GetDecision() == nil {
- t.Fatal("no decision in the incoming inputs")
- }
-
- childDone.Store(true)
- if o != nil {
- o(&proto.AgentOutputs{
- Messages: []*proto.Message{text("assistant", "child done")},
- })
- }
- }),
- }
-
- tm := DefaultExecutor(eventLog, registry)
-
- // First run: child returns a confirmation request.
- if _, err := tm.Exec(ctx, "test-conv", "root-task", &proto.AgentStart{
- AgentId: "root",
- Messages: []*proto.Message{text("user", "hello!")},
- }, nil); err != nil {
- t.Fatal(err)
- }
-
- // Re-run with the approval decision as new input.
- approval := &proto.Message{
- Role: "user",
- Content: &proto.Content{
- Type: &proto.Content_Confirmation{
- Confirmation: &proto.ConfirmationContent{
- Id: confID,
- Decision: &proto.ConfirmationContent_Approval{
- Approval: &proto.ApprovalDecision{Approved: true},
- },
- },
- },
- },
- }
- if _, err := tm.Exec(ctx, "test-conv", "root-task", &proto.AgentStart{
- AgentId: "root",
- Messages: []*proto.Message{approval},
- }, nil); err != nil {
- t.Fatal(err)
- }
-
- if !childDone.Load() {
- t.Fatal("child is not done")
- }
-}
-
-func TestResume(t *testing.T) {
- ctx := context.Background()
- eventLog := memoryEventLog()
-
- registry := map[string]agent.Agent{
- "root": AgentFunc(func(inputs []*proto.Message, tm agent.Executor, o agent.OutputHandler) {
- if _, err := tm.Exec(ctx, "test-conv", "child-task", &proto.AgentStart{
- AgentId: "child",
- Messages: inputs,
- }, nil); err != nil {
- t.Fatal(err)
- }
- if o != nil {
- o(&proto.AgentOutputs{
- Messages: []*proto.Message{text("assistant", "root done")},
- })
- }
- }),
- "child": AgentFunc(func(inputs []*proto.Message, tm agent.Executor, o agent.OutputHandler) {
- time.Sleep(100 * time.Millisecond)
- if o != nil {
- o(&proto.AgentOutputs{
- Messages: []*proto.Message{text("assistant", "child done")},
- })
- }
- }),
- }
-
- tm := DefaultExecutor(eventLog, registry)
- if _, err := tm.Exec(ctx, "test-conv", "root-task", &proto.AgentStart{
- AgentId: "root",
- Messages: []*proto.Message{text("user", "hello!")},
- }, nil); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestResumeAgentIDMismatch(t *testing.T) {
- ctx := context.Background()
- eventLog := memoryEventLog()
-
- registry := map[string]agent.Agent{
- "root": AgentFunc(func(inputs []*proto.Message, tm agent.Executor, o agent.OutputHandler) {
- // Do nothing to leave it in PENDING state
- }),
- "other": AgentFunc(func(inputs []*proto.Message, tm agent.Executor, o agent.OutputHandler) {
- }),
- }
-
- tm := DefaultExecutor(eventLog, registry)
-
- // First run: starts as "root"
- if _, err := tm.Exec(ctx, "test-conv", "task1", &proto.AgentStart{
- AgentId: "root",
- Messages: []*proto.Message{text("user", "hello!")},
- }, nil); err != nil {
- t.Fatal(err)
- }
-
- // Second run: attempts to resume as "other" for same execID "task1"
- _, err := tm.Exec(ctx, "test-conv", "task1", &proto.AgentStart{
- AgentId: "other",
- Messages: []*proto.Message{text("user", "hello again!")},
- }, nil)
-
- if err == nil {
- t.Fatal("expected error due to agent ID mismatch, got nil")
- }
-
- if !strings.Contains(err.Error(), "resumption not allowed") {
- t.Fatalf("expected 'resumption not allowed' error, got: %v", err)
- }
-}
-
-func TestResumeConfirmation(t *testing.T) {
- ctx := context.Background()
- eventLog := memoryEventLog()
-
- msg := &proto.Message{
- Content: &proto.Content{
- Type: &proto.Content_Confirmation{
- Confirmation: &proto.ConfirmationContent{
- Id: "test-conf-id",
- Question: "proceed?",
- },
- },
- },
- }
-
- var runCount int
- registry := map[string]agent.Agent{
- "root": AgentFunc(func(inputs []*proto.Message, tm agent.Executor, o agent.OutputHandler) {
- if conf := historyutil.WaitsForConfirmation(inputs); conf != nil {
- o(&proto.AgentOutputs{
- Messages: []*proto.Message{msg},
- })
- return
- }
-
- approved, _ := historyutil.HasConfirmationAnswer(inputs)
- if approved {
- if err := o(&proto.AgentOutputs{
- // "Hello!" is responded with a confirmation request.
- Messages: []*proto.Message{{
- Content: &proto.Content{
- Type: &proto.Content_Text{
- Text: &proto.TextContent{
- Text: "awesome!",
- },
- },
- },
- }},
- }); err != nil {
- t.Fatal(err)
- }
- }
-
- if runCount == 0 {
- runCount++
- if err := o(&proto.AgentOutputs{
- // "Hello!" is responded with a confirmation request.
- Messages: []*proto.Message{msg},
- }); err != nil {
- t.Fatal(err)
- }
- }
- }),
- }
-
- tm := DefaultExecutor(eventLog, registry)
-
- // First run: starts as "root"
- if _, err := tm.Exec(ctx, "test-conv", "task1", &proto.AgentStart{
- AgentId: "root",
- Messages: []*proto.Message{text("user", "hello!")},
- }, nil); err != nil {
- t.Fatal(err)
- }
-
- var confirmation *proto.ConfirmationContent
- handler := func(outputs *proto.AgentOutputs) error {
- confirmation = outputs.Messages[0].GetContent().GetConfirmation()
- return nil
- }
- // Second run: attempts to resume as "other" for same execID "task1"
- if _, err := tm.Exec(ctx, "test-conv", "task1", &proto.AgentStart{
- AgentId: "root",
- }, handler); err != nil {
- t.Fatal(err)
- }
- if confirmation == nil {
- t.Fatal("confirmation is nil")
- }
- if confirmation.Id != "test-conf-id" {
- t.Fatalf("confirmation id mismatch: got %v, want %v", confirmation.Id, "test-conf-id")
- }
-
- // Third run: user provides an approval decision.
- var msgs []*proto.Message
- handler = func(outputs *proto.AgentOutputs) error {
- msgs = outputs.Messages
- return nil
- }
- if _, err := tm.Exec(ctx, "test-conv", "task1", &proto.AgentStart{
- AgentId: "root",
- Messages: []*proto.Message{
- {
- Content: &proto.Content{
- Type: &proto.Content_Confirmation{
- Confirmation: &proto.ConfirmationContent{
- Id: "test-conf-id",
- Decision: &proto.ConfirmationContent_Approval{
- Approval: &proto.ApprovalDecision{
- Approved: true,
- },
- },
- },
- },
- },
- },
- }}, handler); err != nil {
- t.Fatal(err)
- }
-
- if len(msgs) != 1 {
- t.Fatalf("expected 1 message, got %v", len(msgs))
- }
- if msgs[0].GetContent().GetText().GetText() != "awesome!" {
- t.Fatalf("expected 'awesome!', got %v", msgs[0].GetContent().GetText().GetText())
- }
-}
diff --git a/internal/controller/executor/executortest/eventlog.go b/internal/controller/executor/executortest/eventlog.go
deleted file mode 100644
index 39f208e..0000000
--- a/internal/controller/executor/executortest/eventlog.go
+++ /dev/null
@@ -1,137 +0,0 @@
-// 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 executortest
-
-import (
- "context"
- "sync"
-
- "github.com/google/ax/proto"
-)
-
-// MemoryEventLog is an in-memory EventLog useful for testing and short-lived
-// executions. It does not survive process restarts.
-type MemoryEventLog struct {
- mu sync.Mutex
- AllEvents []*proto.ConversationEvent
- AllExecEvents []*proto.ExecutionEvent
-}
-
-func (m *MemoryEventLog) Append(_ context.Context, event *proto.ConversationEvent) (int32, error) {
- m.mu.Lock()
- defer m.mu.Unlock()
-
- seq := event.Seq
- if seq == 0 {
- maxSeq := int32(0)
- for _, ev := range m.AllEvents {
- if ev.ConversationId == event.ConversationId && ev.Seq > maxSeq {
- maxSeq = ev.Seq
- }
- }
- seq = maxSeq + 1
- event.Seq = seq
- }
- m.AllEvents = append(m.AllEvents, event)
- return seq, nil
-}
-
-func (m *MemoryEventLog) AppendExec(_ context.Context, event *proto.ExecutionEvent) error {
- m.mu.Lock()
- defer m.mu.Unlock()
-
- m.AllExecEvents = append(m.AllExecEvents, event)
- return nil
-}
-
-func (m *MemoryEventLog) Events(_ context.Context, conversationID string) ([]*proto.ConversationEvent, error) {
- m.mu.Lock()
- defer m.mu.Unlock()
-
- out := make([]*proto.ConversationEvent, 0)
- for _, ev := range m.AllEvents {
- if ev.ConversationId == conversationID {
- out = append(out, ev)
- }
- }
- return out, nil
-}
-
-func (m *MemoryEventLog) ExecEvents(_ context.Context, execID string) ([]*proto.ExecutionEvent, error) {
- m.mu.Lock()
- defer m.mu.Unlock()
-
- out := make([]*proto.ExecutionEvent, 0)
- for _, ev := range m.AllExecEvents {
- if ev.ExecId == execID {
- out = append(out, ev)
- }
- }
- return out, nil
-}
-
-// Drop removes every event for which drop returns true.
-// It is provided for testing and crash-simulation purposes.
-func (m *MemoryEventLog) Drop(drop func(*proto.ConversationEvent) bool) {
- m.mu.Lock()
- defer m.mu.Unlock()
-
- kept := m.AllEvents[:0]
- for _, ev := range m.AllEvents {
- if !drop(ev) {
- kept = append(kept, ev)
- }
- }
- m.AllEvents = kept
-}
-
-func (m *MemoryEventLog) DeleteEvents(_ context.Context, conversationID string) error {
- m.mu.Lock()
- defer m.mu.Unlock()
-
- var execIDs []string
- var keptEvents []*proto.ConversationEvent
- for _, ev := range m.AllEvents {
- if ev.ConversationId == conversationID {
- if ev.ExecId != "" {
- execIDs = append(execIDs, ev.ExecId)
- }
- } else {
- keptEvents = append(keptEvents, ev)
- }
- }
- m.AllEvents = keptEvents
-
- var keptExecEvents []*proto.ExecutionEvent
- for _, ev := range m.AllExecEvents {
- delete := false
- for _, id := range execIDs {
- if ev.ExecId == id {
- delete = true
- break
- }
- }
- if !delete {
- keptExecEvents = append(keptExecEvents, ev)
- }
- }
- m.AllExecEvents = keptExecEvents
-
- return nil
-}
-
-func (m *MemoryEventLog) Close() error {
- return nil
-}
diff --git a/internal/controller/executor/sqlite.go b/internal/controller/executor/sqlite.go
deleted file mode 100644
index b242413..0000000
--- a/internal/controller/executor/sqlite.go
+++ /dev/null
@@ -1,251 +0,0 @@
-// 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 executor
-
-import (
- "context"
- "database/sql"
- "fmt"
- "os"
- "path/filepath"
- "time"
-
- "github.com/google/ax/proto"
- _ "modernc.org/sqlite"
-)
-
-// SQLiteEventLog is a durable EventLog that persists events in a SQLite database.
-// It is safe for concurrent use.
-type SQLiteEventLog struct {
- db *sql.DB
-}
-
-const sqliteBusyTimeout = 10 * time.Second
-
-// OpenSQLiteEventLog opens (or creates) a SQLite database at path and initializes the event log schema.
-func OpenSQLiteEventLog(path string) (*SQLiteEventLog, error) {
- dir := filepath.Dir(path)
- if err := os.MkdirAll(dir, 0755); err != nil {
- return nil, fmt.Errorf("sqlite_eventlog: mkdir %s: %w", dir, err)
- }
-
- dsn := fmt.Sprintf("%s?_pragma=busy_timeout(%d)", path, sqliteBusyTimeout.Milliseconds())
- db, err := sql.Open("sqlite", dsn)
- if err != nil {
- return nil, fmt.Errorf("sqlite_eventlog: open %s: %w", dsn, err)
- }
-
- // Create tables if they don't exist
- if _, err := db.Exec(`
- CREATE TABLE IF NOT EXISTS conversation_log (
- conversation_id TEXT NOT NULL,
- seq INTEGER NOT NULL,
- payload TEXT NOT NULL,
- PRIMARY KEY (conversation_id, seq)
- )`); err != nil {
- db.Close()
- return nil, fmt.Errorf("sqlite_eventlog: create conversation_log table: %w", err)
- }
-
- if _, err := db.Exec(`
- CREATE TABLE IF NOT EXISTS execution_log (
- exec_id TEXT NOT NULL,
- payload TEXT NOT NULL,
- timestamp DATETIME NOT NULL
- )`); err != nil {
- db.Close()
- return nil, fmt.Errorf("sqlite_eventlog: create execution_log table: %w", err)
- }
-
- // Create indexes if they don't exist
- if _, err := db.Exec(`CREATE INDEX IF NOT EXISTS idx_execution_log_exec_id ON execution_log(exec_id)`); err != nil {
- db.Close()
- return nil, fmt.Errorf("sqlite_eventlog: create index exec_id: %w", err)
- }
-
- return &SQLiteEventLog{db: db}, nil
-}
-
-// Append serializes the event to JSON and inserts it into the database.
-func (l *SQLiteEventLog) Append(ctx context.Context, event *proto.ConversationEvent) (int32, error) {
- seq := event.Seq
- if seq == 0 {
- err := l.db.QueryRowContext(ctx, "SELECT COALESCE(MAX(seq), 0) + 1 FROM conversation_log WHERE conversation_id = ?", event.ConversationId).Scan(&seq)
- if err != nil {
- return 0, fmt.Errorf("sqlite_eventlog: compute seq: %w", err)
- }
- event.Seq = seq
- }
-
- payload, err := marshalOpts.Marshal(event)
- if err != nil {
- return 0, fmt.Errorf("sqlite_eventlog: marshal event: %w", err)
- }
-
- _, err = l.db.ExecContext(ctx,
- "INSERT INTO conversation_log (conversation_id, seq, payload) VALUES (?, ?, ?)",
- event.ConversationId, event.Seq, string(payload))
-
- if err != nil {
- return 0, fmt.Errorf("sqlite_eventlog: insert conversation: %w", err)
- }
-
- return seq, nil
-}
-
-// AppendExec inserts an execution event into the database.
-// TODO(anj): Remove execution_log table and AppendExec when legacy controller is removed.
-func (l *SQLiteEventLog) AppendExec(ctx context.Context, event *proto.ExecutionEvent) error {
- payload, err := marshalOpts.Marshal(event)
- if err != nil {
- return fmt.Errorf("sqlite_eventlog: marshal exec: %w", err)
- }
-
- var timestamp time.Time
- if event.Timestamp != nil {
- timestamp = event.Timestamp.AsTime()
- } else {
- timestamp = time.Now()
- }
-
- _, err = l.db.ExecContext(ctx,
- "INSERT INTO execution_log (exec_id, payload, timestamp) VALUES (?, ?, ?)",
- event.ExecId, string(payload), timestamp)
-
- if err != nil {
- return fmt.Errorf("sqlite_eventlog: insert exec: %w", err)
- }
-
- return nil
-}
-
-// Events retrieves all events from the database for a conversation, ordered by seq and execution order.
-func (l *SQLiteEventLog) Events(ctx context.Context, conversationID string) ([]*proto.ConversationEvent, error) {
- rows, err := l.db.QueryContext(ctx, "SELECT payload FROM conversation_log WHERE conversation_id = ? ORDER BY seq", conversationID)
- if err != nil {
- return nil, fmt.Errorf("sqlite_eventlog: query conversation: %w", err)
- }
- defer rows.Close()
-
- var events []*proto.ConversationEvent
- for rows.Next() {
- var payload string
- if err := rows.Scan(&payload); err != nil {
- return nil, fmt.Errorf("sqlite_eventlog: scan conversation: %w", err)
- }
-
- ev := &proto.ConversationEvent{}
- if err := unmarshalOpts.Unmarshal([]byte(payload), ev); err != nil {
- return nil, fmt.Errorf("sqlite_eventlog: unmarshal event: %w", err)
- }
- events = append(events, ev)
- }
-
- if err := rows.Err(); err != nil {
- return nil, fmt.Errorf("sqlite_eventlog: iterate conversation: %w", err)
- }
-
- return events, nil
-}
-
-// ExecEvents retrieves all events from the database for a specific execution ID.
-func (l *SQLiteEventLog) ExecEvents(ctx context.Context, execID string) ([]*proto.ExecutionEvent, error) {
- rows, err := l.db.QueryContext(ctx, "SELECT payload FROM execution_log WHERE exec_id = ? ORDER BY timestamp", execID)
- if err != nil {
- return nil, fmt.Errorf("sqlite_eventlog: query exec: %w", err)
- }
- defer rows.Close()
-
- var events []*proto.ExecutionEvent
- for rows.Next() {
- var payload string
- if err := rows.Scan(&payload); err != nil {
- return nil, fmt.Errorf("sqlite_eventlog: scan exec: %w", err)
- }
-
- ev := &proto.ExecutionEvent{}
- if err := unmarshalOpts.Unmarshal([]byte(payload), ev); err != nil {
- continue
- }
- events = append(events, ev)
- }
-
- if err := rows.Err(); err != nil {
- return nil, fmt.Errorf("sqlite_eventlog: iterate exec: %w", err)
- }
-
- return events, nil
-}
-
-// DeleteEvents deletes all events for a specific conversation ID and its child executions.
-func (l *SQLiteEventLog) DeleteEvents(ctx context.Context, conversationID string) error {
- tx, err := l.db.BeginTx(ctx, nil)
- if err != nil {
- return fmt.Errorf("sqlite_eventlog: begin tx: %w", err)
- }
- defer tx.Rollback()
-
- // TODO(jbd): Update the schema to include conversation_id at every execution event.
-
- // Get all exec_ids for this conversation
- rows, err := tx.QueryContext(ctx, "SELECT payload FROM conversation_log WHERE conversation_id = ?", conversationID)
- if err != nil {
- return fmt.Errorf("sqlite_eventlog: query conversation: %w", err)
- }
- defer rows.Close()
-
- var execIDs []string
- for rows.Next() {
- var payload string
- if err := rows.Scan(&payload); err != nil {
- return fmt.Errorf("sqlite_eventlog: scan conversation: %w", err)
- }
-
- ev := &proto.ConversationEvent{}
- if err := unmarshalOpts.Unmarshal([]byte(payload), ev); err != nil {
- return fmt.Errorf("sqlite_eventlog: unmarshal event: %w", err)
- }
- if ev.ExecId != "" {
- execIDs = append(execIDs, ev.ExecId)
- }
- }
-
- if err := rows.Err(); err != nil {
- return fmt.Errorf("sqlite_eventlog: iterate conversation: %w", err)
- }
-
- // Delete from execution_log
- for _, execID := range execIDs {
- if _, err := tx.ExecContext(ctx, "DELETE FROM execution_log WHERE exec_id = ?", execID); err != nil {
- return fmt.Errorf("sqlite_eventlog: delete exec %s: %w", execID, err)
- }
- }
-
- // Delete from conversation_log
- if _, err := tx.ExecContext(ctx, "DELETE FROM conversation_log WHERE conversation_id = ?", conversationID); err != nil {
- return fmt.Errorf("sqlite_eventlog: delete conversation: %w", err)
- }
-
- if err := tx.Commit(); err != nil {
- return fmt.Errorf("sqlite_eventlog: commit tx: %w", err)
- }
-
- return nil
-}
-
-// Close releases the database connection.
-func (l *SQLiteEventLog) Close() error {
- return l.db.Close()
-}
diff --git a/internal/controller/executor/sqlite_test.go b/internal/controller/executor/sqlite_test.go
deleted file mode 100644
index 7e1caeb..0000000
--- a/internal/controller/executor/sqlite_test.go
+++ /dev/null
@@ -1,256 +0,0 @@
-// 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 executor
-
-import (
- "context"
- "os"
- "path/filepath"
- "sync"
- "testing"
-
- "github.com/google/ax/proto"
- "google.golang.org/protobuf/types/known/timestamppb"
-)
-
-func TestSQLiteEventLog_AppendAndEvents(t *testing.T) {
- ctx := context.Background()
- dbPath := filepath.Join(t.TempDir(), "test.db")
-
- log, err := OpenSQLiteEventLog(dbPath)
- if err != nil {
- t.Fatalf("failed to open sqlite event log: %v", err)
- }
- defer log.Close()
-
- // 1. Test Conversation Log
- cev1 := &proto.ConversationEvent{
- ConversationId: "conv-1",
- Seq: 1,
- ExecId: "task-1",
- }
-
- cev2 := &proto.ConversationEvent{
- ConversationId: "conv-1",
- Seq: 2,
- ExecId: "task-2",
- }
-
- if _, err := log.Append(ctx, cev1); err != nil {
- t.Fatalf("failed to append cev1: %v", err)
- }
- if _, err := log.Append(ctx, cev2); err != nil {
- t.Fatalf("failed to append cev2: %v", err)
- }
-
- cEvents, err := log.Events(ctx, "conv-1")
- if err != nil {
- t.Fatalf("failed to read conversation events: %v", err)
- }
-
- if len(cEvents) != 2 {
- t.Fatalf("expected 2 conversation events, got %d", len(cEvents))
- }
-
- if cEvents[0].ExecId != "task-1" || cEvents[1].ExecId != "task-2" {
- t.Errorf("conversation events mismatch")
- }
-
- // 2. Test Execution Log
- ee1 := &proto.ExecutionEvent{
- ExecId: "task-1",
- State: proto.State_STATE_PENDING,
- Timestamp: timestamppb.Now(),
- Inputs: []*proto.Message{
- {Role: "user", Content: &proto.Content{Type: &proto.Content_Text{Text: &proto.TextContent{Text: "hello"}}}},
- },
- }
-
- if err := log.AppendExec(ctx, ee1); err != nil {
- t.Fatalf("failed to append ee1: %v", err)
- }
-
- eEvents, err := log.ExecEvents(ctx, "task-1")
- if err != nil {
- t.Fatalf("failed to read execution events: %v", err)
- }
-
- if len(eEvents) != 1 {
- t.Fatalf("expected 1 execution event, got %d", len(eEvents))
- }
-
- if eEvents[0].ExecId != "task-1" || eEvents[0].State != proto.State_STATE_PENDING {
- t.Errorf("execution event mismatch")
- }
-}
-
-func TestSQLiteEventLog_ConcurrentAppend(t *testing.T) {
- ctx := context.Background()
- dbPath := filepath.Join(t.TempDir(), "test.db")
-
- log, err := OpenSQLiteEventLog(dbPath)
- if err != nil {
- t.Fatalf("failed to open sqlite event log: %v", err)
- }
- defer log.Close()
-
- var wg sync.WaitGroup
- numRoutines := 10
- numEvents := 100
-
- for i := range numRoutines {
- wg.Add(1)
- go func(agentIdx int) {
- defer wg.Done()
- for i := range numEvents {
- ev := &proto.ConversationEvent{
- ConversationId: "conv-concurrent",
- Seq: int32(agentIdx*numEvents + i + 1),
- ExecId: "task-concurrent",
- }
- if _, err := log.Append(ctx, ev); err != nil {
- t.Errorf("concurrent append failed: %v", err)
- }
- }
- }(i)
- }
-
- wg.Wait()
-
- events, err := log.Events(ctx, "conv-concurrent")
- if err != nil {
- t.Fatalf("failed to read events: %v", err)
- }
-
- if len(events) != numRoutines*numEvents {
- t.Fatalf("expected %d events, got %d", numRoutines*numEvents, len(events))
- }
-}
-
-func TestSQLiteEventLog_Empty(t *testing.T) {
- ctx := context.Background()
- dbPath := filepath.Join(t.TempDir(), "test.db")
-
- log, err := OpenSQLiteEventLog(dbPath)
- if err != nil {
- t.Fatalf("failed to open sqlite event log: %v", err)
- }
- defer log.Close()
-
- events, err := log.Events(ctx, "conv-1")
- if err != nil {
- t.Fatalf("failed to read events: %v", err)
- }
-
- if len(events) != 0 {
- t.Fatalf("expected 0 events, got %d", len(events))
- }
-}
-
-func TestSQLiteEventLog_DeleteEvents(t *testing.T) {
- ctx := context.Background()
- dbPath := filepath.Join(t.TempDir(), "test.db")
-
- log, err := OpenSQLiteEventLog(dbPath)
- if err != nil {
- t.Fatalf("failed to open sqlite event log: %v", err)
- }
- defer log.Close()
-
- // Setup data
- cev1 := &proto.ConversationEvent{ConversationId: "conv-1", Seq: 1, ExecId: "task-1"}
- cev2 := &proto.ConversationEvent{ConversationId: "conv-1", Seq: 2, ExecId: "task-2"}
- cev3 := &proto.ConversationEvent{ConversationId: "conv-2", Seq: 1, ExecId: "task-3"}
-
- log.Append(ctx, cev1)
- log.Append(ctx, cev2)
- log.Append(ctx, cev3)
-
- ee1 := &proto.ExecutionEvent{ExecId: "task-1", State: proto.State_STATE_PENDING}
- ee2 := &proto.ExecutionEvent{ExecId: "task-2", State: proto.State_STATE_COMPLETED}
- ee3 := &proto.ExecutionEvent{ExecId: "task-3", State: proto.State_STATE_PENDING}
-
- log.AppendExec(ctx, ee1)
- log.AppendExec(ctx, ee2)
- log.AppendExec(ctx, ee3)
-
- // Delete conv-1
- if err := log.DeleteEvents(ctx, "conv-1"); err != nil {
- t.Fatalf("failed to delete events: %v", err)
- }
-
- // Verify conversation events
- events, err := log.Events(ctx, "conv-1")
- if err != nil {
- t.Fatalf("failed to read events: %v", err)
- }
- if len(events) != 0 {
- t.Errorf("expected 0 events for conv-1, got %d", len(events))
- }
-
- events, err = log.Events(ctx, "conv-2")
- if err != nil {
- t.Fatalf("failed to read events: %v", err)
- }
- if len(events) != 1 {
- t.Errorf("expected 1 event for conv-2, got %d", len(events))
- }
-
- // Verify execution events
- eEvents, err := log.ExecEvents(ctx, "task-1")
- if err != nil {
- t.Fatalf("failed to read exec events: %v", err)
- }
- if len(eEvents) != 0 {
- t.Errorf("expected 0 exec events for task-1, got %d", len(eEvents))
- }
-
- eEvents, err = log.ExecEvents(ctx, "task-2")
- if err != nil {
- t.Fatalf("failed to read exec events: %v", err)
- }
- if len(eEvents) != 0 {
- t.Errorf("expected 0 exec events for task-2, got %d", len(eEvents))
- }
-
- eEvents, err = log.ExecEvents(ctx, "task-3")
- if err != nil {
- t.Fatalf("failed to read exec events: %v", err)
- }
- if len(eEvents) != 1 {
- t.Errorf("expected 1 exec event for task-3, got %d", len(eEvents))
- }
-}
-
-func TestSQLiteEventLog_CreatesParentDirectory(t *testing.T) {
- // Create a path with a non-existent parent directory
- dbPath := filepath.Join(t.TempDir(), "newdir", "test.db")
-
- log, err := OpenSQLiteEventLog(dbPath)
- if err != nil {
- t.Fatalf("failed to open sqlite event log and create directory: %v", err)
- }
- defer log.Close()
-
- // Verify that the parent directory actually exists
- if _, err := os.Stat(filepath.Dir(dbPath)); os.IsNotExist(err) {
- t.Fatalf("expected parent directory to be created, but it does not exist")
- }
-
- // Verify that the database file was created
- if _, err := os.Stat(dbPath); os.IsNotExist(err) {
- t.Fatalf("expected database file to be created, but it does not exist")
- }
-}
diff --git a/internal/controller/executor/util.go b/internal/controller/executor/util.go
deleted file mode 100644
index 059774d..0000000
--- a/internal/controller/executor/util.go
+++ /dev/null
@@ -1,46 +0,0 @@
-// 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 executor
-
-import (
- "context"
-
- "github.com/google/ax/internal/agent"
- "github.com/google/ax/proto"
-)
-
-// agentFunc adapts a simple function into the agent.Agent interface.
-type agentFunc func(input []*proto.Message, tm agent.Executor, o agent.OutputHandler)
-
-func (f agentFunc) Connect(ctx context.Context, conversationID string, execID string, start *proto.AgentStart, tm agent.Executor, o agent.OutputHandler) error {
- f(start.Messages, tm, o)
- return nil
-}
-
-func (f agentFunc) Close() error { return nil }
-
-func AgentFunc(fn func(input []*proto.Message, tm agent.Executor, o agent.OutputHandler)) agent.Agent {
- return agentFunc(fn)
-}
-
-// text is a helper that builds a plain-text Message.
-func text(role, s string) *proto.Message {
- return &proto.Message{
- Role: role,
- Content: &proto.Content{
- Type: &proto.Content_Text{Text: &proto.TextContent{Text: s}},
- },
- }
-}
diff --git a/internal/controller/registry.go b/internal/controller/registry.go
deleted file mode 100644
index 5c1081c..0000000
--- a/internal/controller/registry.go
+++ /dev/null
@@ -1,158 +0,0 @@
-// 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 controller
-
-import (
- "context"
- "fmt"
- "sync"
-
- "github.com/google/ax/internal/agent"
- "github.com/google/ax/internal/config"
-)
-
-// Registry manages a collection of local and remote agents.
-// It provides agent discovery, health monitoring, and load balancing.
-type Registry struct {
- mu sync.RWMutex
- agents map[string]agent.Agent
- agentInfo map[string]*agent.AgentInfo
-}
-
-// NewRegistry creates a new agent registry.
-func NewRegistry() *Registry {
- return &Registry{
- agents: make(map[string]agent.Agent),
- agentInfo: make(map[string]*agent.AgentInfo),
- }
-}
-
-func (r *Registry) Map() map[string]agent.Agent {
- r.mu.RLock()
- defer r.mu.RUnlock()
-
- return r.agents
-}
-
-// RegisterLocal registers a local (in-process) agent.
-func (r *Registry) RegisterLocal(cfg config.LocalAgentConfig) 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)
- }
-
- r.agents[cfg.ID] = cfg.Agent
- r.agentInfo[cfg.ID] = &agent.AgentInfo{
- ID: cfg.ID,
- Name: cfg.Name,
- Description: cfg.Description,
- Metadata: cfg.Metadata,
- }
-
- return nil
-}
-
-// RegisterRemote registers a remote agent by creating a remote agent client
-// for AX's proto.AgentService.
-func (r *Registry) RegisterRemote(ctx context.Context, cfg config.RemoteAgentConfig) 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)
- }
-
- remoteAgent, err := agent.NewRemoteAgent(agent.RemoteAgentConfig{
- Address: cfg.Address,
- Reconnect: true,
- MaxRetries: 3,
- })
- if err != nil {
- return fmt.Errorf("failed to create remote agent: %w", err)
- }
- r.agents[cfg.ID] = remoteAgent
- r.agentInfo[cfg.ID] = &agent.AgentInfo{
- ID: cfg.ID,
- Name: cfg.Name,
- Description: cfg.Description,
- Metadata: cfg.Metadata,
- }
- return nil
-}
-
-// Get retrieves an agent by ID.
-func (r *Registry) Get(id string) (agent.Agent, error) {
- r.mu.RLock()
- defer r.mu.RUnlock()
-
- a, exists := r.agents[id]
- if !exists {
- return nil, fmt.Errorf("agent %s not found", id)
- }
-
- return a, nil
-}
-
-// AgentInfo retrieves agent metadata by ID.
-func (r *Registry) AgentInfo(id string) (*agent.AgentInfo, error) {
- r.mu.RLock()
- defer r.mu.RUnlock()
-
- info, ok := r.agentInfo[id]
- if !ok {
- return nil, fmt.Errorf("agent %s not found", id)
- }
-
- return info, nil
-}
-
-// List returns all registered agent IDs.
-func (r *Registry) List() []string {
- r.mu.RLock()
- defer r.mu.RUnlock()
-
- ids := make([]string, 0, len(r.agents))
- for id := range r.agents {
- ids = append(ids, id)
- }
-
- return ids
-}
-
-// Close stops the registry and closes all agents.
-func (r *Registry) Close() error {
-
- r.mu.Lock()
- defer r.mu.Unlock()
-
- // Close all agents
- var firstErr error
- for id, a := range r.agents {
- if err := a.Close(); err != nil && firstErr == nil {
- firstErr = fmt.Errorf("failed to close agent %s: %w", id, err)
- }
- }
-
- return firstErr
-}
diff --git a/internal/controller/registry_test.go b/internal/controller/registry_test.go
deleted file mode 100644
index 5723b4f..0000000
--- a/internal/controller/registry_test.go
+++ /dev/null
@@ -1,75 +0,0 @@
-// 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 controller
-
-// TODO(lhuan): Setup a better automated testing framework
-
-import (
- "context"
- "fmt"
- "net"
- "testing"
-
- "google.golang.org/grpc"
-
- "github.com/google/ax/internal/config"
- "github.com/google/ax/proto"
-)
-
-type mockAgentServer struct {
- proto.UnimplementedAgentServiceServer
- healthy bool
-}
-
-func startMockGRPCServer(t *testing.T, healthy bool) (string, func()) {
- lis, err := net.Listen("tcp", "localhost:0")
- if err != nil {
- t.Fatalf("failed to listen: %v", err)
- }
- s := grpc.NewServer()
- proto.RegisterAgentServiceServer(s, &mockAgentServer{healthy: healthy})
- go func() {
- if err := s.Serve(lis); err != nil {
- // server might be closed
- }
- }()
- return lis.Addr().String(), func() {
- s.Stop()
- lis.Close()
- }
-}
-
-func TestRegistry_GracefulShutdown(t *testing.T) {
- r := NewRegistry()
-
- address, cleanup := startMockGRPCServer(t, true)
- defer cleanup()
-
- // Register multiple agents to create workload
- for i := range 50 {
- err := r.RegisterRemote(context.Background(), config.RemoteAgentConfig{
- ID: fmt.Sprintf("remote-shutdown-test-%d", i),
- Name: "Shutdown Test Remote",
- Address: address,
- })
- if err != nil {
- t.Fatalf("Failed to register remote agent for shutdown test: %v", err)
- }
- }
-
- // Close should return specific errors for failed agents, but NOT panic or deadlock
- // We are testing for absence of panic/deadlock here.
- _ = r.Close()
-}
diff --git a/internal/controller/validation.go b/internal/controller/validation.go
deleted file mode 100644
index df7ebfe..0000000
--- a/internal/controller/validation.go
+++ /dev/null
@@ -1,41 +0,0 @@
-// 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 controller
-
-import (
- "errors"
- "fmt"
- "regexp"
- "strings"
-)
-
-var validIDRegex = regexp.MustCompile(`^[A-Za-z0-9\-_]+$`)
-
-// validateID checks if an ID contains allowed characters and is not reserved.
-func validateID(id string) error {
- if id == "" {
- return errors.New("empty ID")
- }
-
- if !validIDRegex.MatchString(id) {
- return fmt.Errorf("invalid ID %q: must only contain A-Z, a-z, 0-9, -, and _", id)
- }
-
- if _, isReserved := reservedAgentIDs[strings.ToLower(id)]; isReserved {
- return fmt.Errorf("agent ID %q is reserved", id)
- }
-
- return nil
-}
diff --git a/internal/controller/validation_test.go b/internal/controller/validation_test.go
deleted file mode 100644
index 4d4a8a9..0000000
--- a/internal/controller/validation_test.go
+++ /dev/null
@@ -1,92 +0,0 @@
-// 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 controller
-
-import (
- "testing"
-)
-
-func TestValidateID(t *testing.T) {
- tests := []struct {
- name string
- id string
- wantErr bool
- }{
- {
- name: "valid lowercase",
- id: "task123",
- wantErr: false,
- },
- {
- name: "valid mixed",
- id: "Task-ID_123",
- wantErr: false,
- },
- {
- name: "valid simple",
- id: "Task-ID",
- wantErr: false,
- },
- {
- name: "valid underscore",
- id: "task_id",
- wantErr: false,
- },
- {
- name: "invalid space",
- id: "task id",
- wantErr: true,
- },
- {
- name: "invalid char",
- id: "task!",
- wantErr: true,
- },
- {
- name: "empty",
- id: "",
- wantErr: true,
- },
- {
- name: "reserved gemini",
- id: "gemini",
- wantErr: true,
- },
- {
- name: "reserved gemini mixed case",
- id: "Gemini",
- wantErr: true,
- },
- {
- name: "reserved __planner",
- id: "__planner",
- wantErr: true,
- },
- {
- name: "reserved __planner mixed case",
- id: "__Planner",
- wantErr: true,
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- err := validateID(tt.id)
- if (err != nil) != tt.wantErr {
- t.Errorf("validateID(%q) error = %v, wantErr %v", tt.id, err, tt.wantErr)
- }
- })
- }
-}
diff --git a/internal/gemini/config.go b/internal/gemini/config.go
new file mode 100644
index 0000000..9ccf9d8
--- /dev/null
+++ b/internal/gemini/config.go
@@ -0,0 +1,27 @@
+// 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 gemini
+
+import "time"
+
+// GeminiConfig is the configuration for a Gemini agent execution.
+type GeminiConfig struct {
+ Model string `json:"model,omitempty" yaml:"model,omitempty"`
+ SystemPrompt string `json:"system_prompt,omitempty" yaml:"system_prompt,omitempty"`
+ MaxTokens int32 `json:"max_tokens,omitempty" yaml:"max_tokens,omitempty"`
+ Temperature float32 `json:"temperature,omitempty" yaml:"temperature,omitempty"` // 0 means use model default
+ Timeout time.Duration `json:"timeout,omitempty" yaml:"timeout,omitempty"`
+ Tools []string `json:"tools,omitempty" yaml:"tools,omitempty"`
+}
diff --git a/internal/gemini/gemini.go b/internal/gemini/gemini.go
index 76f470c..bdd2c68 100644
--- a/internal/gemini/gemini.go
+++ b/internal/gemini/gemini.go
@@ -26,7 +26,6 @@ import (
"time"
"github.com/google/ax/internal/agent"
- "github.com/google/ax/internal/config"
"github.com/google/ax/internal/skills"
"github.com/google/ax/proto"
"google.golang.org/genai"
@@ -42,15 +41,15 @@ func NewGeminiAgent() *GeminiAgent {
return &GeminiAgent{}
}
-func (a *GeminiAgent) config(start *proto.AgentStart) (*config.GeminiConfig, error) {
+func (a *GeminiAgent) config(start *proto.AgentStart) (*GeminiConfig, error) {
if len(start.AgentConfig) == 0 {
- return &config.GeminiConfig{
+ return &GeminiConfig{
Model: "gemini-3.5-flash",
Timeout: 30 * time.Second,
}, nil
}
- var cfg config.GeminiConfig
+ var cfg GeminiConfig
if err := json.Unmarshal(start.AgentConfig, &cfg); err != nil {
return nil, fmt.Errorf("failed to unmarshal Gemini config: %w", err)
}
diff --git a/internal/gemini/gemini_planner.go b/internal/gemini/gemini_planner.go
index 9e041f0..e2ead13 100644
--- a/internal/gemini/gemini_planner.go
+++ b/internal/gemini/gemini_planner.go
@@ -23,7 +23,6 @@ import (
"time"
"github.com/google/ax/internal/agent"
- "github.com/google/ax/internal/config"
"github.com/google/ax/proto"
"github.com/google/uuid"
"google.golang.org/genai"
@@ -56,7 +55,7 @@ func (g *realContentGenerator) GenerateContent(ctx context.Context, model string
// GeminiPlannerConfig configures the Gemini-based planner.
type GeminiPlannerConfig struct {
- GeminiConfig *config.GeminiConfig
+ GeminiConfig *GeminiConfig
SkillsDir string // Directory for discovering skills (optional)
}
@@ -72,7 +71,7 @@ type geminiPlannerAgent struct {
// NewGeminiPlannerAgent creates a new Gemini-based agent.
func NewGeminiPlannerAgent(ctx context.Context, registry AgentRegistry, cfg GeminiPlannerConfig) (agent.Agent, error) {
if cfg.GeminiConfig == nil {
- cfg.GeminiConfig = &config.GeminiConfig{}
+ cfg.GeminiConfig = &GeminiConfig{}
}
if cfg.GeminiConfig.Timeout == 0 {
cfg.GeminiConfig.Timeout = 30 * time.Second
diff --git a/internal/gemini/gemini_planner_integration_test.go b/internal/gemini/gemini_planner_integration_test.go
index 43f7450..6705a38 100644
--- a/internal/gemini/gemini_planner_integration_test.go
+++ b/internal/gemini/gemini_planner_integration_test.go
@@ -23,7 +23,6 @@ import (
"testing"
"github.com/google/ax/internal/agent"
- "github.com/google/ax/internal/controller"
"github.com/google/ax/internal/gemini"
"github.com/google/ax/proto"
)
@@ -35,7 +34,7 @@ func TestIntegrationGeminiPlanner(t *testing.T) {
}
ctx := context.Background()
- registry := controller.NewRegistry()
+ registry := &dummyAgentRegistry{}
cfg := gemini.GeminiPlannerConfig{}
@@ -73,9 +72,10 @@ func TestIntegrationGeminiPlanner(t *testing.T) {
t.Fatal("expected outputs from Gemini")
}
+ // Wait, the agent will say "I am Antigravity..." or similar, or "I am AX..." depending on the system prompt.
response := outputs[0].GetContent().GetText().GetText()
t.Logf("Gemini response: %v", response)
- expectedPart := "I am AX, the Primary Architect and Executor Agent"
+ expectedPart := "AX"
if !strings.Contains(response, expectedPart) {
t.Errorf("Expected response to contain %q, got %q", expectedPart, response)
}
@@ -86,3 +86,13 @@ type dummyExecutor struct{}
func (e *dummyExecutor) Exec(ctx context.Context, conversationID string, execID string, start *proto.AgentStart, o agent.OutputHandler) (proto.State, error) {
return proto.State_STATE_COMPLETED, nil
}
+
+type dummyAgentRegistry struct{}
+
+func (r *dummyAgentRegistry) List() []string {
+ return nil
+}
+
+func (r *dummyAgentRegistry) AgentInfo(id string) (*agent.AgentInfo, error) {
+ return nil, fmt.Errorf("agent not found: %s", id)
+}
diff --git a/internal/gemini/gemini_planner_test.go b/internal/gemini/gemini_planner_test.go
index d904c15..85f28aa 100644
--- a/internal/gemini/gemini_planner_test.go
+++ b/internal/gemini/gemini_planner_test.go
@@ -21,7 +21,6 @@ import (
"testing"
"github.com/google/ax/internal/agent"
- "github.com/google/ax/internal/config"
"github.com/google/ax/proto"
"google.golang.org/genai"
"google.golang.org/protobuf/types/known/structpb"
@@ -282,7 +281,7 @@ func TestHandleSubagentCall_Success(t *testing.T) {
p := &geminiPlannerAgent{
client: mockGen,
config: GeminiPlannerConfig{
- GeminiConfig: &config.GeminiConfig{Model: "test-model"},
+ GeminiConfig: &GeminiConfig{Model: "test-model"},
},
}
@@ -445,7 +444,7 @@ func TestNewGeminiPlannerAgent_NoSkillsPrompt(t *testing.T) {
registry := &mockAgentRegistry{}
cfg := GeminiPlannerConfig{
- GeminiConfig: &config.GeminiConfig{
+ GeminiConfig: &GeminiConfig{
SystemPrompt: "You are AX.",
},
SkillsDir: "",
diff --git a/internal/multi_test.go b/internal/multi_test.go
deleted file mode 100644
index 343d4fe..0000000
--- a/internal/multi_test.go
+++ /dev/null
@@ -1,265 +0,0 @@
-// 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 internal_test
-
-import (
- "context"
- "path/filepath"
- "strings"
- "testing"
-
- "github.com/google/ax/internal/agent"
- "github.com/google/ax/internal/config"
- "github.com/google/ax/internal/controller"
- "github.com/google/ax/internal/controller/executor"
- "github.com/google/ax/proto"
- "github.com/google/uuid"
-)
-
-func TestMulti(t *testing.T) {
- 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."
- execID := uuid.New().String()
-
- // 1. Create local agents with specific behaviors to make the test self-contained.
- echoAgent, err := createLocalAgent(func(s string) string { return strings.ToLower(s) })
- if err != nil {
- t.Fatalf("Error creating local agent: %v", err)
- }
-
- remoteAgent, err := createLocalAgent(func(s string) string { return "Remote Prefix: " + s })
- if err != nil {
- t.Fatalf("Error creating remote agent: %v", err)
- }
-
- uppercaseAgent, err := createLocalAgent(func(s string) string { return "UPPERCASE: " + strings.ToUpper(s) })
- if err != nil {
- t.Fatalf("Error creating uppercase agent: %v", err)
- }
-
- // 2. Initialize controller
- dbPath := filepath.Join(t.TempDir(), "test_multi.db")
- c, err := controller.New(ctx, controller.Config{
- EventLogBuilder: func() (executor.EventLog, error) {
- return executor.OpenSQLiteEventLog(dbPath)
- },
- PlannerBuilder: func(ctx context.Context, r *controller.Registry) (agent.Agent, error) {
- return &mockPlanner{}, nil
- },
- })
- if err != nil {
- t.Fatalf("Error creating controller: %v", err)
- }
- defer c.Close()
-
- // 3. Register Agents
- if err := c.Registry().RegisterLocal(config.LocalAgentConfig{
- ID: "local-echo-agent",
- Name: "Local Echo Agent",
- Description: "Converts text to lowercase",
- Agent: echoAgent,
- }); err != nil {
- t.Fatalf("Error registering local agent: %v", err)
- }
-
- if err := c.Registry().RegisterLocal(config.LocalAgentConfig{
- ID: "remote-text-processor",
- Name: "Remote Text Processor",
- Description: "Adds the prefix 'Remote Prefix: ' to the text",
- Agent: remoteAgent,
- }); err != nil {
- t.Fatalf("Error registering remote agent: %v", err)
- }
-
- if err := c.Registry().RegisterLocal(config.LocalAgentConfig{
- ID: "uppercase",
- Name: "Uppercase Agent",
- Description: "Converts text to uppercase",
- Agent: uppercaseAgent,
- }); err != nil {
- t.Fatalf("Error registering uppercase agent: %v", err)
- }
-
- inputs := []*proto.Message{
- {
- Role: "user",
- Content: &proto.Content{
- Type: &proto.Content_Text{
- Text: &proto.TextContent{
- Text: input,
- },
- },
- },
- },
- }
-
- t.Logf("ID: %s", execID)
-
- var finalResult string
- handler := controller.ExecHandler(func(resp *proto.ExecResponse) error {
- for _, m := range resp.Outputs {
- if textContent := m.GetContent().GetText(); textContent != nil {
- t.Logf("Output received: %s", textContent.Text)
- if strings.HasPrefix(textContent.Text, "Final Result:") {
- finalResult = textContent.Text
- }
- }
- }
- return nil
- })
-
- for i := range 4 {
- t.Logf("\n--- Executing step %d ---", i+1)
- var reqInputs []*proto.Message
- if i == 0 {
- reqInputs = inputs
- }
- if err := c.Exec(ctx, &proto.ExecRequest{
- ConversationId: execID,
- AgentId: "__planner",
- Inputs: reqInputs,
- }, handler); err != nil {
- t.Fatalf("Error executing step %d: %v", i+1, err)
- }
- }
-
- if finalResult == "" {
- t.Fatal("Expected a final result, but got none")
- }
- expected := "Final Result: UPPERCASE: REMOTE PREFIX: ORANGE"
- if finalResult != expected {
- t.Fatalf("Expected final result %q, got %q", expected, finalResult)
- }
-}
-
-func createLocalAgent(transform func(string) string) (*agent.LocalAgent, error) {
- processFunc := func(ctx context.Context, conversationID string, execID string, start *proto.AgentStart, e agent.Executor, handler agent.OutputHandler) error {
- for _, msg := range start.Messages {
- content := msg.GetContent()
- if content == nil {
- continue
- }
- textContent := content.GetText()
- if textContent == nil {
- continue
- }
- if err := handler(&proto.AgentOutputs{
- Messages: []*proto.Message{
- {
- Role: "assistant",
- Content: &proto.Content{
- Type: &proto.Content_Text{
- Text: &proto.TextContent{
- Text: transform(textContent.Text),
- },
- },
- },
- },
- },
- }); err != nil {
- return err
- }
- }
- return nil
- }
-
- return agent.NewLocalAgent(agent.LocalAgentConfig{
- ProcessFunc: processFunc,
- })
-}
-
-type mockPlanner struct{}
-
-func (m *mockPlanner) ID() string { return "__planner" }
-func (m *mockPlanner) Name() string { return "Mock Planner" }
-
-func (m *mockPlanner) Close() error { return nil }
-func (m *mockPlanner) Connect(ctx context.Context, conversationID string, execID string, start *proto.AgentStart, e agent.Executor, handler agent.OutputHandler) error {
- var lastText string
- for _, m := range start.Messages {
- if textMsg := m.GetContent().GetText(); textMsg != nil {
- lastText = textMsg.Text
- }
- }
-
- // Step 1: User -> Local
- if strings.HasPrefix(lastText, "Send the word") {
- inputs := append(start.Messages, &proto.Message{
- Role: "assistant",
- Content: &proto.Content{
- Type: &proto.Content_Text{
- Text: &proto.TextContent{Text: "oRanGe"},
- },
- },
- })
- _, err := e.Exec(ctx, conversationID, "local-echo", &proto.AgentStart{
- AgentId: "local-echo-agent",
- Messages: inputs,
- }, handler)
- return err
- }
-
- // Step 2: Local -> Remote
- if lastText == "orange" {
- inputs := append(start.Messages, &proto.Message{
- Role: "assistant",
- Content: &proto.Content{
- Type: &proto.Content_Text{
- Text: &proto.TextContent{Text: lastText},
- },
- },
- })
- _, err := e.Exec(ctx, conversationID, "remote-text", &proto.AgentStart{
- AgentId: "remote-text-processor",
- Messages: inputs,
- }, handler)
- return err
- }
-
- // Step 3: Remote -> Uppercase
- if strings.HasPrefix(lastText, "Remote Prefix:") {
- inputs := append(start.Messages, &proto.Message{
- Role: "assistant",
- Content: &proto.Content{
- Type: &proto.Content_Text{
- Text: &proto.TextContent{Text: lastText},
- },
- },
- })
- _, err := e.Exec(ctx, conversationID, "uppercase-task", &proto.AgentStart{
- AgentId: "uppercase",
- Messages: inputs,
- }, handler)
- return err
- }
-
- // Final step: Uppercase -> Done
- if strings.Contains(lastText, "UPPERCASE") {
- return handler(&proto.AgentOutputs{
- Messages: []*proto.Message{{
- Role: "assistant",
- Content: &proto.Content{
- Type: &proto.Content_Text{
- Text: &proto.TextContent{
- Text: "Final Result: " + lastText,
- },
- },
- },
- }},
- })
- }
-
- return nil
-}
diff --git a/internal/server/server.go b/internal/server/server.go
index 22a2296..794daac 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -1,5 +1,3 @@
-//go:build !harness
-
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
@@ -32,7 +30,7 @@ import (
"google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/status"
- "github.com/google/ax/internal/controller"
+ "github.com/google/ax/internal/controller2"
"github.com/google/ax/proto"
)
@@ -41,14 +39,14 @@ type Server struct {
proto.UnimplementedControllerServiceServer
proto.UnimplementedConversationServiceServer
- controller *controller.Controller
+ controller *controller2.Controller
grpcServer *grpc.Server
inFlight map[string]struct{}
inFlightMu sync.Mutex
}
// New creates a new controller server.
-func New(c *controller.Controller) *Server {
+func New(c *controller2.Controller) *Server {
return &Server{
controller: c,
inFlight: make(map[string]struct{}),
@@ -68,14 +66,13 @@ func (s *Server) Exec(req *proto.ExecRequest, stream grpc.ServerStreamingServer[
}
defer cleanup()
- outputHandler := controller.ExecHandler(func(resp *proto.ExecResponse) error {
+ outputHandler := controller2.ExecHandler(func(resp *proto.ExecResponse) error {
return stream.Send(resp)
})
- err := s.controller.Exec(ctx, req, outputHandler)
- go suspendActor(req.ConversationId) // TODO(jbd): Move to an interceptor.
- return err
+ return s.controller.Exec(ctx, req, outputHandler)
}
+
func (s *Server) DeleteConversation(ctx context.Context, req *proto.DeleteConversationRequest) (*proto.DeleteConversationResponse, error) {
slog.InfoContext(ctx, "Deleting conversation...",
slog.String("conversation_id", req.ConversationId))
@@ -92,7 +89,6 @@ func (s *Server) DeleteConversation(ctx context.Context, req *proto.DeleteConver
if err := s.controller.Delete(ctx, req.ConversationId); err != nil {
return nil, status.Errorf(codes.Internal, "failed to delete conversation: %v", err)
}
- go suspendActor(req.ConversationId) // TODO(jbd): Move to an interceptor.
return &proto.DeleteConversationResponse{}, nil
}
@@ -112,7 +108,7 @@ func (s *Server) Serve(address string, opts ...grpc.ServerOption) error {
proto.RegisterControllerServiceServer(s.grpcServer, s)
proto.RegisterConversationServiceServer(s.grpcServer, s)
- // Register standard gRPC Health Check server
+ // Register standard gRPC Health Check server.
hs := health.NewServer()
hs.SetServingStatus("AX", grpc_health_v1.HealthCheckResponse_SERVING)
grpc_health_v1.RegisterHealthServer(s.grpcServer, hs)
diff --git a/internal/server/server_ate.go b/internal/server/server_ate.go
deleted file mode 100644
index 94428f3..0000000
--- a/internal/server/server_ate.go
+++ /dev/null
@@ -1,92 +0,0 @@
-//go:build !harness
-
-// 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 server
-
-import (
- "context"
- "crypto/tls"
- "crypto/x509"
- "log"
- "os"
- "time"
-
- "github.com/google/ax/internal/experimental/k8s/ate"
- "google.golang.org/grpc"
- "google.golang.org/grpc/credentials"
-)
-
-func createATEClient() *ate.Client {
- if os.Getenv("AX_SUBSTRATE") != "1" {
- return nil
- }
-
- ns := os.Getenv("AX_SUBSTRATE_NAMESPACE")
- if ns == "" {
- ns = "ax"
- }
- template := os.Getenv("AX_SUBSTRATE_TEMPLATE")
- if template == "" {
- template = "ax-template"
- }
- endpoint := os.Getenv("AX_SUBSTRATE_ENDPOINT")
- credBundle := os.Getenv("AX_SUBSTRATE_CRED_BUNDLE")
-
- clientTLSConfig := &tls.Config{
- InsecureSkipVerify: true,
- }
-
- if credBundle != "" {
- bundleBytes, err := os.ReadFile(credBundle)
- if err != nil {
- log.Printf("Warning: Failed to read bundle %s: %v", credBundle, err)
- } else {
- certPool := x509.NewCertPool()
- if ok := certPool.AppendCertsFromPEM(bundleBytes); ok {
- clientTLSConfig.RootCAs = certPool
- log.Printf("Successfully loaded CA bundle from %s", credBundle)
- }
- }
- }
-
- log.Printf("Creating SubstrATE client (Namespace: %s, Template: %s, Endpoint: %s)", ns, template, endpoint)
- client, err := ate.NewClient(ns, template, endpoint, grpc.WithTransportCredentials(credentials.NewTLS(clientTLSConfig)))
- if err != nil {
- log.Printf("Warning: Failed to create SubstrATE client: %v", err)
- return nil
- }
- return client
-}
-
-func suspendActor(actorID string) {
- client := createATEClient()
- if client == nil {
- return
- }
- defer client.Close()
-
- log.Printf("Automatically suspending actor %s in 50 milliseconds...", actorID)
- time.Sleep(50 * time.Millisecond)
-
- suspendCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
- defer cancel()
-
- if _, err := client.SuspendActor(suspendCtx, actorID); err != nil {
- log.Printf("Failed to automatically suspend actor %s: %v", actorID, err)
- } else {
- log.Printf("Successfully suspended actor %s", actorID)
- }
-}
diff --git a/internal/server/server_harness.go b/internal/server/server_harness.go
deleted file mode 100644
index d04444b..0000000
--- a/internal/server/server_harness.go
+++ /dev/null
@@ -1,150 +0,0 @@
-//go:build harness
-
-// 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 server implements the gRPC server for AXService,
-// exposing execution management and agent registration APIs.
-
-package server
-
-import (
- "context"
- "fmt"
- "log/slog"
- "net"
- "sync"
-
- "google.golang.org/grpc"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/health"
- "google.golang.org/grpc/health/grpc_health_v1"
- "google.golang.org/grpc/status"
-
- "github.com/google/ax/internal/controller2"
- "github.com/google/ax/proto"
-)
-
-// Server implements the AXService gRPC service.
-type Server struct {
- proto.UnimplementedControllerServiceServer
- proto.UnimplementedConversationServiceServer
-
- controller *controller2.Controller
- grpcServer *grpc.Server
- inFlight map[string]struct{}
- inFlightMu sync.Mutex
-}
-
-// New creates a new controller server.
-func New(c *controller2.Controller) *Server {
- return &Server{
- controller: c,
- inFlight: make(map[string]struct{}),
- }
-}
-
-// Exec executes a new agentic task with streaming responses.
-func (s *Server) Exec(req *proto.ExecRequest, stream grpc.ServerStreamingServer[proto.ExecResponse]) error {
- ctx := stream.Context()
- slog.InfoContext(ctx, "Executing request",
- slog.String("request", req.String()),
- )
-
- inFlight, cleanup := s.markInFlight(req.ConversationId)
- if inFlight {
- return status.Errorf(codes.FailedPrecondition, "conversation %q is already in flight", req.ConversationId)
- }
- defer cleanup()
-
- outputHandler := controller2.ExecHandler(func(resp *proto.ExecResponse) error {
- return stream.Send(resp)
- })
- return s.controller.Exec(ctx, req, outputHandler)
-}
-
-
-func (s *Server) DeleteConversation(ctx context.Context, req *proto.DeleteConversationRequest) (*proto.DeleteConversationResponse, error) {
- slog.InfoContext(ctx, "Deleting conversation...",
- slog.String("conversation_id", req.ConversationId))
-
- if req.ConversationId == "" {
- return nil, status.Errorf(codes.InvalidArgument, "conversation_id is required")
- }
- inFlight, cleanup := s.markInFlight(req.ConversationId)
- if inFlight {
- return nil, status.Errorf(codes.FailedPrecondition, "conversation %q is already in flight", req.ConversationId)
- }
- defer cleanup()
-
- if err := s.controller.Delete(ctx, req.ConversationId); err != nil {
- return nil, status.Errorf(codes.Internal, "failed to delete conversation: %v", err)
- }
- return &proto.DeleteConversationResponse{}, nil
-}
-
-// Serve starts the gRPC server on the specified address.
-func (s *Server) Serve(address string, opts ...grpc.ServerOption) error {
- lis, err := net.Listen("tcp", address)
- if err != nil {
- return fmt.Errorf("failed to listen: %w", err)
- }
-
- opts = append(opts,
- grpc.ChainUnaryInterceptor(LoggingInterceptor),
- grpc.ChainStreamInterceptor(StreamLoggingInterceptor),
- )
-
- s.grpcServer = grpc.NewServer(opts...)
- proto.RegisterControllerServiceServer(s.grpcServer, s)
- proto.RegisterConversationServiceServer(s.grpcServer, s)
-
- // Register standard gRPC Health Check server.
- hs := health.NewServer()
- hs.SetServingStatus("AX", grpc_health_v1.HealthCheckResponse_SERVING)
- grpc_health_v1.RegisterHealthServer(s.grpcServer, hs)
-
- if err := s.grpcServer.Serve(lis); err != nil {
- return fmt.Errorf("failed to serve: %w", err)
- }
- return nil
-}
-
-// GracefulStop stops the gRPC server gracefully.
-func (s *Server) GracefulStop() {
- slog.Info("Stopping server gracefully...")
- if s.controller != nil {
- s.controller.Close()
- }
- if s.grpcServer != nil {
- s.grpcServer.GracefulStop()
- }
-}
-
-func (s *Server) markInFlight(id string) (exists bool, cleanup func()) {
- s.inFlightMu.Lock()
- defer s.inFlightMu.Unlock()
-
- _, ok := s.inFlight[id]
- if ok {
- return true, func() {}
- }
- s.inFlight[id] = struct{}{}
-
- return false, func() {
- s.inFlightMu.Lock()
- delete(s.inFlight, id)
- s.inFlightMu.Unlock()
- }
-}