Skip to content

armgit / ax

Public Imported from GitHub
0

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

Go

Add built-in filesystem tool to the default planner (#41)

Jaana Doganecaf5189a662
diff --git a/README.md b/README.md
index 2e520a5..c9689e9 100644
--- a/README.md
+++ b/README.md
@@ -25,6 +25,12 @@ Built-in consistency and resumability features:
└────────────────────────┘ └──────────────┘
```
+As agents move from simple interactions to "autonomous workers," most developers
+will need what GAR provides: a way to manage state, ensure reliability, and audit
+the process through a structured event log. It is a "runtime" in the same way
+Kubernetes is a runtime for containers. GAR provides the plumbing so developers
+can focus on the logic.
+
## Installation
Install the gar CLI directly from the repository:
@@ -45,18 +51,32 @@ You should see the gar CLI usage information.
## Quick Start
-### 1. Run Local Agent Example
+### 1. Run headless
+
+The CLI provides an easy way to trigger a session by using the
+agents and built-in tools already linked into the GAR binary.
```bash
-# Run the local agent example by linking the local agent with controller.
-go run examples/local_agent/main.go
+# Using default gar.yaml
+gar gar trigger --headless --input "Can you list me this directory?"
+
+# Using a custom configuration
+gar gar trigger --headless --input "Can you list me this directory?" --config my-config.yaml
+
+```
+
+You can continue a session any time:
+
+```bash
+gar trigger --headless --session session123 --input "Show me the contents of README.md"
```
### 2. Run Remote Agent with GAR Server
+Most developers want to register their custom remote agents.
+
This example demonstrates how the GAR server triggers remote agents through the `AgentService.Process` RPC. You can run this in two ways:
-#### [Option A] Client-Server Mode
This is the standard way to run GAR, separating the controller from the trigger client.
**Terminal 1** - Start the remote agent server:
@@ -83,29 +103,9 @@ gar register \
# Trigger a session - gar will coordinate the remote agent via Process RPC
gar trigger \
--session session123 \
- --input "Hello remote agent"
+ --input "Hello, can you uppercase what I just said?"
```
-#### [Option B] Headless Mode (Simplified)
-Run everything in a single command. The trigger starts its own internal controller.
-
-**Terminal 1** - Start the remote agent server:
-```bash
-go run examples/remote_agent/main.go
-```
-(Same as Option A, the agent must be running to receive requests)
-
-**Terminal 2** - Trigger directly:
-```bash
-# Using default gar.yaml
-gar trigger --headless --input "Hello from headless mode"
-
-# Using a custom configuration
-gar trigger --headless --input "Hello" --config my-config.yaml
-
-```
-The `trigger` command starts its own internal controller, reads the specified configuration file (default: `gar.yaml`) to discover agents, and executes the session locally.
-
## Usage
### GAR CLI
@@ -118,7 +118,9 @@ The `gar` command provides several subcommands:
gar trigger \
--input <text> \
[--session <id>] \
- [--server <address>]
+ [--server <address>] \
+ [--headless] \
+ [--config <file>]
```
Triggers a new agentic loop session or automatically resumes an existing one. If the session ID already exists, the session will be resumed from its last state with the new input.
diff --git a/cmd/gar/internal/display.go b/cmd/gar/internal/display.go
new file mode 100644
index 0000000..0e51511
--- /dev/null
+++ b/cmd/gar/internal/display.go
@@ -0,0 +1,154 @@
+// 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
+
+import (
+ "fmt"
+ "sync/atomic"
+
+ "github.com/charmbracelet/huh"
+ "github.com/charmbracelet/huh/spinner"
+ "github.com/charmbracelet/lipgloss"
+)
+
+const (
+ boxWidth = 100
+)
+
+var (
+ purple = lipgloss.AdaptiveColor{Light: "#5A56E0", Dark: "#7571F9"}
+ comment = lipgloss.AdaptiveColor{Dark: "#6d6d6d"}
+)
+
+type Display struct {
+ sessionID string
+
+ userStyle lipgloss.Style
+ checkpointStyle lipgloss.Style
+ sessionStyle lipgloss.Style
+
+ loadingVisible atomic.Bool
+ loadingStopCh chan bool
+}
+
+func NewDisplay(sessionID string) *Display {
+ return &Display{
+ sessionID: sessionID,
+ userStyle: lipgloss.NewStyle().
+ Foreground(purple),
+ checkpointStyle: lipgloss.NewStyle().
+ Foreground(comment),
+ sessionStyle: lipgloss.NewStyle().
+ Foreground(comment),
+ loadingStopCh: make(chan bool),
+ }
+}
+
+func (d *Display) hideLoading() {
+ if d.loadingVisible.Load() {
+ d.loadingStopCh <- true
+ d.loadingVisible.Store(false)
+ }
+}
+
+func (d *Display) showLoading() {
+ d.loadingVisible.Store(true)
+
+ done := func() {
+ <-d.loadingStopCh
+ }
+ go func() {
+ spinner.New().
+ Title("Loading...").
+ Action(done).
+ Run()
+ }()
+}
+
+// DisplayInput displays the user input.
+func (d *Display) DisplayInput(text string) {
+ fmt.Printf("%s %s\n",
+ d.userStyle.Render("⏺"),
+ text,
+ )
+ fmt.Println()
+
+ d.showLoading()
+}
+
+// DisplayOutput displays an output fragment.
+func (d *Display) DisplayOutput(text string) {
+ d.hideLoading()
+
+ fmt.Print(text)
+}
+
+// Finish completes the streaming output and shows checkpoint if provided
+func (d *Display) FinishOutput(checkpointID string) {
+ fmt.Print("\n")
+
+ // Show checkpoint box if checkpoint ID exists
+ if checkpointID != "" {
+ fmt.Println(d.checkpointStyle.Render("Checkpoint: " + checkpointID))
+ }
+ fmt.Println()
+}
+
+func (d *Display) DisplayHeader() {
+ fmt.Println(d.sessionStyle.Render("Session: " + d.sessionID))
+ fmt.Println()
+}
+
+// PromptForApproval shows an accept/reject dialog
+// Returns true if accepted, false if rejected, and an error if cancelled (Ctrl+C)
+func (d *Display) PromptForApproval(question string) (bool, error) {
+ d.hideLoading()
+
+ var accepted bool
+ form := huh.NewForm(
+ huh.NewGroup(
+ huh.NewConfirm().
+ Title(question).
+ Affirmative("Accept").
+ Negative("Reject").
+ Value(&accepted),
+ ),
+ ).WithWidth(boxWidth)
+
+ if err := form.Run(); err != nil {
+ return false, err
+ }
+ return accepted, nil
+}
+
+// PromptForInput shows the input box and returns the user input
+// Returns the input string and an error if the user cancelled (Ctrl+C)
+func (d *Display) PromptForInput() (string, error) {
+ d.hideLoading()
+
+ var userInput string
+ form := huh.NewForm(
+ huh.NewGroup(
+ huh.NewInput().
+ Placeholder("Enter prompt...").
+ Value(&userInput),
+ ),
+ ).WithWidth(boxWidth)
+
+ if err := form.Run(); err != nil {
+ return "", err
+ }
+ return userInput, nil
+}
diff --git a/cmd/gar/serve.go b/cmd/gar/serve.go
index e33fd06..b5bd941 100644
--- a/cmd/gar/serve.go
+++ b/cmd/gar/serve.go
@@ -31,7 +31,8 @@ import (
)
var (
- serveConfigFile string
+ serveConfigFile string
+ serveSkipApprovals bool
)
var serveCmd = &cobra.Command{
@@ -44,11 +45,16 @@ Loads configuration from a YAML file (default: gar.yaml).`,
func init() {
serveCmd.Flags().StringVar(&serveConfigFile, "config", "gar.yaml", "Path to YAML configuration file")
+ serveCmd.Flags().BoolVar(&serveSkipApprovals, "dangerously-skip-approvals", false, "Skips all approvals")
}
func runServe(cmd *cobra.Command, args []string) error {
ctx := context.Background()
+ if !serveSkipApprovals {
+ return fmt.Errorf("serve cannot ask for user approval yet; dangerously skip approvals")
+ }
+
// Load configuration from YAML file
cfg, err := config.LoadFromFile(serveConfigFile)
if err != nil {
@@ -60,7 +66,7 @@ func runServe(cmd *cobra.Command, args []string) error {
return fmt.Errorf("invalid configuration: %w", err)
}
- c, err := newControllerFromConfig(ctx, cfg)
+ c, err := newControllerFromConfig(ctx, func(string) bool { return true }, cfg)
if err != nil {
return fmt.Errorf("error creating controller: %w", err)
}
@@ -87,7 +93,7 @@ func runServe(cmd *cobra.Command, args []string) error {
return nil
}
-func newControllerFromConfig(ctx context.Context, cfg *config.Config) (*controller.Controller, error) {
+func newControllerFromConfig(ctx context.Context, approval controller.ApprovalHandler, cfg *config.Config) (*controller.Controller, error) {
// Create event log builder
eventLogBuilder := func(sessionID string) (eventlog.EventLog, error) {
return eventlog.NewFileEventLog(eventlog.FileConfig{
@@ -97,12 +103,12 @@ func newControllerFromConfig(ctx context.Context, cfg *config.Config) (*controll
}
// Create planner builder
- plannerBuilder := func(ctx context.Context, r *controller.Registry) (agent.Agent, error) {
+ plannerBuilder := func(ctx context.Context, r *controller.Registry, h controller.ApprovalHandler) (agent.Agent, error) {
// The builder defines which planner to use.
// Currently, it uses the Gemini planner.
// Gemini config can be customized via environment variables (GEMINI_API_KEY, GAR_GEMINI_MODEL)
// TODO(lhuan): allow other planners based on cfg.PlannerType
- return controller.NewGeminiPlanner(ctx, r, controller.GeminiPlannerConfig{
+ return controller.NewGeminiPlanner(ctx, r, h, controller.GeminiPlannerConfig{
Model: cfg.Planner.Gemini.Model,
MaxTokens: cfg.Planner.Gemini.MaxTokens,
Timeout: cfg.Planner.Gemini.Timeout,
@@ -112,6 +118,7 @@ func newControllerFromConfig(ctx context.Context, cfg *config.Config) (*controll
// Build controller config
controllerConfig := controller.Config{
+ ApprovalHandler: approval,
EventLogBuilder: eventLogBuilder,
PlannerBuilder: plannerBuilder,
MaxSteps: cfg.MaxSteps,
@@ -130,11 +137,5 @@ func newControllerFromConfig(ctx context.Context, cfg *config.Config) (*controll
return nil, fmt.Errorf("failed to register remote agent %s: %w", agentCfg.ID, err)
}
}
-
- agents := c.Registry().List()
- if len(agents) == 0 {
- log.Println("WARNING: No agents at startup.")
- }
-
return c, nil
}
diff --git a/cmd/gar/trigger.go b/cmd/gar/trigger.go
index 5523142..b1d3a0c 100644
--- a/cmd/gar/trigger.go
+++ b/cmd/gar/trigger.go
@@ -23,7 +23,9 @@ import (
"syscall"
"github.com/google/gar/agent"
+ "github.com/google/gar/cmd/gar/internal"
"github.com/google/gar/internal/config"
+ "github.com/google/gar/internal/controller"
"github.com/google/gar/proto"
"github.com/google/uuid"
"github.com/spf13/cobra"
@@ -56,25 +58,16 @@ func init() {
// TODO(jbd): Add multimodal input flags, e.g. --input-image.
+var (
+ triggerController *controller.Controller
+)
+
func runTrigger(cmd *cobra.Command, args []string) error {
ctx := context.Background()
// Generate UUID if no session ID provided
if triggerSessionID == "" {
triggerSessionID = uuid.New().String()
- fmt.Printf("Generated session ID: %s\n", triggerSessionID)
- }
-
- // Create input content
- inputs := []*proto.Content{
- {
- Role: "user",
- Content: &proto.Content_Text{
- Text: &proto.TextContent{
- Text: triggerInput,
- },
- },
- },
}
// Setup signal handling for graceful shutdown
@@ -90,10 +83,85 @@ func runTrigger(cmd *cobra.Command, args []string) error {
cancel()
}()
- if triggerHeadless {
- return runHeadless(ctx, triggerSessionID, inputs)
+ return triggerLoop(ctx, triggerSessionID, triggerInput)
+}
+
+func triggerLoop(ctx context.Context, sessionID string, input string) error {
+ d := internal.NewDisplay(sessionID)
+ d.DisplayHeader()
+
+ for {
+ d.DisplayInput(input)
+
+ inputs := []*proto.Content{
+ {
+ Role: "user",
+ Content: &proto.Content_Text{
+ Text: &proto.TextContent{
+ Text: input,
+ },
+ },
+ },
+ }
+ if triggerHeadless {
+ if err := runTriggerHeadless(ctx, d, triggerSessionID, inputs); err != nil {
+ return err
+ }
+ } else {
+ if err := runTriggerServer(ctx, d, triggerSessionID, inputs); err != nil {
+ return err
+ }
+ }
+
+ var err error
+ input, err = d.PromptForInput()
+ if err != nil {
+ return err
+ }
+ }
+}
+
+func runTriggerHeadless(ctx context.Context, d *internal.Display, sessionID string, inputs []*proto.Content) error {
+ if triggerController == nil {
+ cfg, err := config.LoadFromFile(triggerConfigFile)
+ if err != nil {
+ return fmt.Errorf("error loading config file '%s': %w", triggerConfigFile, err)
+ }
+
+ approval := func(question string) bool {
+ ok, err := d.PromptForApproval(question)
+ if err != nil {
+ return false
+ }
+ return ok
+ }
+
+ c, err := newControllerFromConfig(ctx, approval, cfg)
+ if err != nil {
+ return fmt.Errorf("error creating controller: %w", err)
+ }
+ triggerController = c
+ }
+
+ var checkpoint string
+ outputHandler := agent.OutputHandler(func(resp *proto.ProcessResponse) error {
+ displayContents(d, resp.Contents)
+ if resp.CheckpointId != "" {
+ checkpoint = resp.CheckpointId
+ }
+ return nil
+ })
+ if err := triggerController.TriggerSession(ctx, sessionID, &proto.ProcessRequest{
+ Contents: inputs,
+ }, outputHandler); err != nil {
+ return fmt.Errorf("error triggering session in headless mode: %w", err)
}
+ d.FinishOutput(checkpoint)
+ return nil
+}
+
+func runTriggerServer(ctx context.Context, d *internal.Display, sessionID string, inputs []*proto.Content) error {
conn, err := connect(triggerServerAddr)
if err != nil {
return err
@@ -101,16 +169,15 @@ func runTrigger(cmd *cobra.Command, args []string) error {
defer conn.Close()
client := proto.NewGARServiceClient(conn)
-
stream, err := client.TriggerSession(ctx, &proto.TriggerSessionRequest{
- SessionId: triggerSessionID,
- Inputs: inputs,
+ SessionId: sessionID,
+ Inputs: inputs,
})
if err != nil {
return fmt.Errorf("error triggering session: %w", err)
}
- // Receive and print all responses
+ var checkpoint string
for {
resp, err := stream.Recv()
if err == io.EOF {
@@ -119,62 +186,24 @@ func runTrigger(cmd *cobra.Command, args []string) error {
if err != nil {
return fmt.Errorf("error receiving response: %w", err)
}
-
- if resp.CheckpointId != "" {
- fmt.Printf("Checkpoint ID: %s\n", resp.CheckpointId)
- }
-
if resp.Outputs != nil {
- printResponse(resp.State, resp.Outputs)
+ displayContents(d, resp.Outputs)
+ }
+ if resp.CheckpointId != "" {
+ checkpoint = resp.CheckpointId
}
}
+ d.FinishOutput(checkpoint)
return nil
}
-func runHeadless(ctx context.Context, sessionID string, inputs []*proto.Content) error {
- // Load configuration from YAML file
- cfg, err := config.LoadFromFile(triggerConfigFile)
- if err != nil {
- return fmt.Errorf("error loading config file '%s': %w", triggerConfigFile, err)
- }
-
- // Validate configuration
- if err := cfg.Validate(); err != nil {
- return fmt.Errorf("invalid configuration: %w", err)
- }
-
- c, err := newControllerFromConfig(ctx, cfg)
- if err != nil {
- return fmt.Errorf("error creating controller: %w", err)
- }
- defer c.Close()
- // TODO(lhuan): Allow a default local agent to be registered in headless mode.
-
- // Create output handler to print streaming results to stdout
- outputHandler := agent.OutputHandler(func(resp *proto.ProcessResponse) error {
- printResponse(proto.State_STATE_RUNNING, resp.Contents)
- return nil
- })
-
- req := &proto.ProcessRequest{
- Contents: inputs,
- }
-
- if err := c.TriggerSession(ctx, sessionID, req, outputHandler); err != nil {
- return fmt.Errorf("error triggering session in headless mode: %w", err)
- }
-
- fmt.Println("[COMPLETED]")
- return nil
-}
-
-func printResponse(state proto.State, outputs []*proto.Content) {
- for _, content := range outputs {
- switch c := content.Content.(type) {
+func displayContents(d *internal.Display, contents []*proto.Content) {
+ for _, output := range contents {
+ switch o := output.Content.(type) {
case *proto.Content_Text:
- fmt.Printf("[%s] %s\n", state, c.Text.Text)
+ d.DisplayOutput(o.Text.Text)
default:
- fmt.Printf("[%s] Unknown content type: %T\n", state, c)
+ d.DisplayOutput(fmt.Sprintf("unknown output type: %v", o))
}
}
}
diff --git a/examples/local_agent/main.go b/examples/local_agent/main.go
index 859cc75..f1c7450 100644
--- a/examples/local_agent/main.go
+++ b/examples/local_agent/main.go
@@ -48,6 +48,9 @@ func main() {
c, err := controller.New(ctx, controller.Config{
MaxSteps: 10,
+ ApprovalHandler: func(prompt string) bool {
+ return true // nothing to approve
+ },
HealthCheck: config.HealthCheckConfig{
Enabled: true,
Interval: 30 * time.Second,
diff --git a/go.mod b/go.mod
index 5d9dcd0..7316b1d 100644
--- a/go.mod
+++ b/go.mod
@@ -3,9 +3,11 @@ module github.com/google/gar
go 1.24.0
require (
+ github.com/charmbracelet/huh v0.8.0
+ github.com/charmbracelet/huh/spinner v0.0.0-20260216111231-bffc99a26329
+ github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834
github.com/google/uuid v1.6.0
github.com/spf13/cobra v1.10.2
- golang.org/x/sync v0.19.0
google.golang.org/genai v1.43.0
google.golang.org/grpc v1.78.0
google.golang.org/protobuf v1.36.11
@@ -16,6 +18,18 @@ require (
cloud.google.com/go v0.116.0 // indirect
cloud.google.com/go/auth v0.9.3 // indirect
cloud.google.com/go/compute/metadata v0.9.0 // indirect
+ github.com/atotto/clipboard v0.1.4 // indirect
+ github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
+ github.com/catppuccin/go v0.3.0 // indirect
+ github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7 // indirect
+ github.com/charmbracelet/bubbletea v1.3.10 // indirect
+ github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
+ github.com/charmbracelet/x/ansi v0.10.1 // indirect
+ github.com/charmbracelet/x/cellbuf v0.0.13 // indirect
+ github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect
+ github.com/charmbracelet/x/term v0.2.1 // indirect
+ github.com/dustin/go-humanize v1.0.1 // indirect
+ github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/s2a-go v0.1.8 // indirect
@@ -23,8 +37,18 @@ require (
github.com/gorilla/websocket v1.5.3 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/kr/pretty v0.3.1 // indirect
+ github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
+ github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/mattn/go-localereader v0.0.1 // indirect
+ github.com/mattn/go-runewidth v0.0.16 // indirect
+ github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect
+ github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
+ github.com/muesli/cancelreader v0.2.2 // indirect
+ github.com/muesli/termenv v0.16.0 // indirect
+ github.com/rivo/uniseg v0.4.7 // indirect
github.com/rogpeppe/go-internal v1.14.1 // indirect
github.com/spf13/pflag v1.0.10 // indirect
+ github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
go.opencensus.io v0.24.0 // indirect
golang.org/x/crypto v0.46.0 // indirect
golang.org/x/net v0.48.0 // indirect
diff --git a/go.sum b/go.sum
index 3f69597..7951ffe 100644
--- a/go.sum
+++ b/go.sum
@@ -6,17 +6,63 @@ cloud.google.com/go/auth v0.9.3/go.mod h1:7z6VY+7h3KUdRov5F1i8NDP5ZzWKYmEPO842Bg
cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
+github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
+github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
+github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
+github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
+github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
+github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
+github.com/aymanbagabas/go-udiff v0.3.1 h1:LV+qyBQ2pqe0u42ZsUEtPiCaUoqgA9gYRDs3vj1nolY=
+github.com/aymanbagabas/go-udiff v0.3.1/go.mod h1:G0fsKmG+P6ylD0r6N/KgQD/nWzgfnl8ZBcNLgcbrw8E=
+github.com/catppuccin/go v0.3.0 h1:d+0/YicIq+hSTo5oPuRi5kOpqkVA5tAsU6dNhvRu+aY=
+github.com/catppuccin/go v0.3.0/go.mod h1:8IHJuMGaUUjQM82qBrGNBv7LFq6JI3NnQCF6MOlZjpc=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
+github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7 h1:JFgG/xnwFfbezlUnFMJy0nusZvytYysV4SCS2cYbvws=
+github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7/go.mod h1:ISC1gtLcVilLOf23wvTfoQuYbW2q0JevFxPfUzZ9Ybw=
+github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw=
+github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4=
+github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=
+github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=
+github.com/charmbracelet/huh v0.8.0 h1:Xz/Pm2h64cXQZn/Jvele4J3r7DDiqFCNIVteYukxDvY=
+github.com/charmbracelet/huh v0.8.0/go.mod h1:5YVc+SlZ1IhQALxRPpkGwwEKftN/+OlJlnJYlDRFqN4=
+github.com/charmbracelet/huh/spinner v0.0.0-20260216111231-bffc99a26329 h1:0qvbszNGxDNsLfktnN6eFngemvxTzKWyL2ER1AEmawM=
+github.com/charmbracelet/huh/spinner v0.0.0-20260216111231-bffc99a26329/go.mod h1:OMqKat/mm9a/qOnpuNOPyYO9bPzRNnmzLnRZT5KYltg=
+github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 h1:ZR7e0ro+SZZiIZD7msJyA+NjkCNNavuiPBLgerbOziE=
+github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834/go.mod h1:aKC/t2arECF6rNOnaKaVU6y4t4ZeHQzqfxedE/VkVhA=
+github.com/charmbracelet/x/ansi v0.10.1 h1:rL3Koar5XvX0pHGfovN03f5cxLbCF2YvLeyz7D2jVDQ=
+github.com/charmbracelet/x/ansi v0.10.1/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE=
+github.com/charmbracelet/x/cellbuf v0.0.13 h1:/KBBKHuVRbq1lYx5BzEHBAFBP8VcQzJejZ/IA3iR28k=
+github.com/charmbracelet/x/cellbuf v0.0.13/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=
+github.com/charmbracelet/x/conpty v0.1.0 h1:4zc8KaIcbiL4mghEON8D72agYtSeIgq8FSThSPQIb+U=
+github.com/charmbracelet/x/conpty v0.1.0/go.mod h1:rMFsDJoDwVmiYM10aD4bH2XiRgwI7NYJtQgl5yskjEQ=
+github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86 h1:JSt3B+U9iqk37QUU2Rvb6DSBYRLtWqFqfxf8l5hOZUA=
+github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86/go.mod h1:2P0UgXMEa6TsToMSuFqKFQR+fZTO9CNGUNokkPatT/0=
+github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ=
+github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=
+github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 h1:qko3AQ4gK1MTS/de7F5hPGx6/k1u0w4TeYmBFwzYVP4=
+github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0/go.mod h1:pBhA0ybfXv6hDjQUZ7hk1lVxBiUbupdw5R31yPUViVQ=
+github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
+github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
+github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=
+github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo=
+github.com/charmbracelet/x/xpty v0.1.2 h1:Pqmu4TEJ8KeA9uSkISKMU3f+C1F6OGBn8ABuGlqCbtI=
+github.com/charmbracelet/x/xpty v0.1.2/go.mod h1:XK2Z0id5rtLWcpeNiMYBccNNBrP2IJnzHI0Lq13Xzq4=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
+github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
+github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
+github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
+github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
+github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
@@ -63,9 +109,28 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
+github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
+github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
+github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
+github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
+github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
+github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4=
+github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE=
+github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
+github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
+github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
+github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
+github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
+github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
+github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
+github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
+github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
@@ -81,6 +146,8 @@ github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpE
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
+github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
+github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
@@ -101,6 +168,8 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
+golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
+golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
@@ -122,6 +191,8 @@ golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5h
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
diff --git a/internal/controller/controller.go b/internal/controller/controller.go
index d97cfee..0125b2c 100644
--- a/internal/controller/controller.go
+++ b/internal/controller/controller.go
@@ -18,6 +18,7 @@ package controller
import (
"context"
+ "errors"
"fmt"
"sync"
@@ -38,15 +39,21 @@ type Controller struct {
}
// PlannerBuilder is a function that creates a PlanFunc given a Registry.
-type PlannerBuilder func(ctx context.Context, r *Registry) (agent.Agent, error)
+type PlannerBuilder func(ctx context.Context, r *Registry, h ApprovalHandler) (agent.Agent, error)
+
+// ApprovalHandler is the handler function triggered if an explicit
+// user approval is required to continue the controller. For example, it's triggered
+// before executing commands.
+type ApprovalHandler func(question string) bool
// Config configures the controller.
type Config struct {
EventLogBuilder eventlog.EventLogBuilder
PlannerBuilder PlannerBuilder
// TODO(jbd): Add CompacterBuilder.
- HealthCheck config.HealthCheckConfig
- MaxSteps int
+ HealthCheck config.HealthCheckConfig
+ ApprovalHandler ApprovalHandler
+ MaxSteps int
}
// New creates a new controller instance.
@@ -55,6 +62,10 @@ func New(ctx context.Context, config Config) (*Controller, error) {
config.MaxSteps = 5
}
+ if config.ApprovalHandler == nil {
+ return nil, errors.New("approval handler is required")
+ }
+
if config.EventLogBuilder == nil {
config.EventLogBuilder = func(sessionID string) (eventlog.EventLog, error) {
return eventlog.NewFileEventLog(eventlog.FileConfig{
@@ -76,12 +87,12 @@ func New(ctx context.Context, config Config) (*Controller, error) {
// Determine plan function
// If no planner builder is provided, use the default Gemini planner.
if config.PlannerBuilder == nil {
- config.PlannerBuilder = func(ctx context.Context, r *Registry) (agent.Agent, error) {
- return NewGeminiPlanner(ctx, r, GeminiPlannerConfig{})
+ config.PlannerBuilder = func(ctx context.Context, r *Registry, h ApprovalHandler) (agent.Agent, error) {
+ return NewGeminiPlanner(ctx, r, h, GeminiPlannerConfig{})
}
}
- planner, err := config.PlannerBuilder(ctx, registry)
+ planner, err := config.PlannerBuilder(ctx, registry, config.ApprovalHandler)
if err != nil {
return nil, fmt.Errorf("failed to create planner from builder: %w", err)
}
@@ -132,7 +143,10 @@ func (d *Controller) TriggerSession(ctx context.Context, sessionID string, incom
// Check if session already exists
sess, err := d.sessionManager.LoadSession(ctx, sessionID)
- if err == nil && sess == nil {
+ if err != nil {
+ return fmt.Errorf("failed to load session: %w", err)
+ }
+ if sess == nil {
// Session doesn't exist - create new session
// Checkpoint ID is ignored for new sessions
sess, err = d.sessionManager.NewSession(sessionID)
diff --git a/internal/controller/gemini.go b/internal/controller/gemini.go
index 48a5c86..1c3943c 100644
--- a/internal/controller/gemini.go
+++ b/internal/controller/gemini.go
@@ -18,6 +18,9 @@ import (
"context"
"fmt"
"os"
+ "os/exec"
+ "runtime"
+ "strings"
"time"
"github.com/google/gar/agent"
@@ -25,6 +28,8 @@ import (
"google.golang.org/genai"
)
+const fsToolName = "filesystem"
+
// GeminiPlannerConfig configures the Gemini-based planner.
type GeminiPlannerConfig struct {
APIKey string // Google AI API key (for programmatic use only; if empty, uses GEMINI_API_KEY env var - recommended)
@@ -34,7 +39,7 @@ type GeminiPlannerConfig struct {
SystemPrompt string // Custom system prompt (optional)
}
-func NewGeminiPlanner(ctx context.Context, registry *Registry, config GeminiPlannerConfig) (agent.Agent, error) {
+func NewGeminiPlanner(ctx context.Context, registry *Registry, h ApprovalHandler, config GeminiPlannerConfig) (agent.Agent, error) {
if config.Timeout == 0 {
config.Timeout = 60 * time.Second
}
@@ -53,21 +58,22 @@ func NewGeminiPlanner(ctx context.Context, registry *Registry, config GeminiPlan
// Default system prompt
if config.SystemPrompt == "" {
- config.SystemPrompt = `You are an intelligent agent orchestrator. Your role is to analyze the conversation history and user requests, then select the most appropriate agent to handle the task.
+ config.SystemPrompt = `You are an intelligent orchestrator. Your role is to analyze the conversation history and user requests, then select the most appropriate agent to handle the task.
-Available agents have been provided to you as function tools. Each agent has:
+Available tools have been provided to you as function tools. Each agent has:
- A unique ID
- A description of its capabilities
Your job is to:
1. Analyze the current conversation context and understand what needs to be done
-2. Select the best agent for the task by calling the appropriate function
+2. Select the best tool for the task by calling the appropriate function
3. If enough work is done, stop to indicate completion
Guidelines:
-- Choose agents based on their capabilities and the user's needs
-- If no suitable agent exists, stop.
-- Keep the conversation context in mind when selecting agents`
+- Choose tools based on their capabilities and the user's needs
+- If no suitable tool exists, stop.
+- Keep the conversation context in mind when selecting tools
+- It's valid not to choose a tool`
}
client, err := genai.NewClient(ctx, &genai.ClientConfig{
@@ -79,6 +85,7 @@ Guidelines:
return &geminiPlannerAgent{
client: client,
+ fsTool: newFilesystemTool(h),
registry: registry,
config: config,
}, nil
@@ -86,16 +93,14 @@ Guidelines:
type geminiPlannerAgent struct {
client *genai.Client
+ fsTool *filesystemTool
registry *Registry
config GeminiPlannerConfig
}
// agentsToTools converts registry agents to Gemini function declarations.
-func agentsToTools(registry *Registry) ([]*genai.Tool, error) {
+func agentsToTools(fsTool *filesystemTool, registry *Registry) ([]*genai.Tool, error) {
healthyAgents := registry.ListHealthy()
- if len(healthyAgents) == 0 {
- return nil, fmt.Errorf("no healthy agents available")
- }
var tools []*genai.Tool
// TODO(lhuan): Check if agentsToTools returns an error or empty list and return a friendly "no agent available, try later" error.
@@ -115,12 +120,13 @@ func agentsToTools(registry *Registry) ([]*genai.Tool, error) {
FunctionDeclarations: []*genai.FunctionDeclaration{funcDecl},
})
}
+ tools = append(tools, fsTool.funcDecl())
return tools, nil
}
func (p *geminiPlannerAgent) Process(ctx context.Context, sessionID string, incoming *proto.ProcessRequest, handler agent.OutputHandler) error {
// Convert agents to Gemini function declarations
- tools, err := agentsToTools(p.registry)
+ tools, err := agentsToTools(p.fsTool, p.registry)
if err != nil {
return fmt.Errorf("failed to convert agents to tools: %w", err)
}
@@ -128,7 +134,12 @@ func (p *geminiPlannerAgent) Process(ctx context.Context, sessionID string, inco
// Convert session to conversation history
contents := protoToContents(incoming.Contents)
resp, err := p.client.Models.GenerateContent(ctx, p.config.Model, contents, &genai.GenerateContentConfig{
- Tools: tools,
+ Tools: tools,
+ ToolConfig: &genai.ToolConfig{
+ FunctionCallingConfig: &genai.FunctionCallingConfig{
+ Mode: genai.FunctionCallingConfigModeAuto,
+ },
+ },
SystemInstruction: genai.Text(p.config.SystemPrompt)[0],
MaxOutputTokens: p.config.MaxTokens,
CandidateCount: 1,
@@ -154,13 +165,39 @@ func (p *geminiPlannerAgent) Process(ctx context.Context, sessionID string, inco
continue
}
- if fc := part.FunctionCall; fc != nil {
+ if part.Text != "" {
+ // Text response
if err := handler(&proto.ProcessResponse{
- AgentHandoff: fc.Name,
+ Contents: []*proto.Content{{
+ Content: &proto.Content_Text{
+ Text: &proto.TextContent{Text: part.Text},
+ },
+ }},
}); err != nil {
return err
}
}
+
+ if fc := part.FunctionCall; fc != nil {
+ switch fc.Name {
+ case fsToolName:
+ output, err := p.fsTool.executeShellCommand(fc.Args)
+ if err != nil {
+ return err
+ }
+ return handler(&proto.ProcessResponse{
+ Contents: []*proto.Content{{
+ Content: &proto.Content_Text{
+ Text: &proto.TextContent{Text: output},
+ },
+ }},
+ })
+ default:
+ return handler(&proto.ProcessResponse{
+ AgentHandoff: fc.Name,
+ })
+ }
+ }
}
return nil
}
@@ -198,8 +235,79 @@ func protoToContents(inputs []*proto.Content) []*genai.Content {
},
})
// TODO(jbd): Handle other content types (e.g., images, files)
-
}
}
return contents
}
+
+func newFilesystemTool(h ApprovalHandler) *filesystemTool {
+ return &filesystemTool{
+ approval: h,
+ }
+}
+
+// filesystemTool is the built-in tool that allows
+// planner to operate file system operations.
+type filesystemTool struct {
+ approval ApprovalHandler
+}
+
+func (f *filesystemTool) funcDecl() *genai.Tool {
+ osInfo := fmt.Sprintf("User's Operating System: %s (%s)", runtime.GOOS, runtime.GOARCH)
+ description := fmt.Sprintf("Execute a shell command for file system operations. %s. Generate commands appropriate for this OS. Supports listing directories, reading files, writing files, and other file operations. Returns the command output or error. Never produce code, only use existing command line programs available in the system.", osInfo)
+
+ return &genai.Tool{
+ FunctionDeclarations: []*genai.FunctionDeclaration{
+ {
+ Name: fsToolName,
+ Description: description,
+ Parameters: &genai.Schema{
+ Type: genai.TypeObject,
+ Properties: map[string]*genai.Schema{
+ "command": {
+ Type: genai.TypeString,
+ Description: "The shell command to execute (e.g., 'ls -la' for Unix/macOS, 'dir' for Windows, 'cat file.txt', etc.)",
+ },
+ },
+ Required: []string{"command"},
+ },
+ },
+ },
+ }
+}
+
+func (f *filesystemTool) executeShellCommand(args map[string]any) (string, error) {
+ command, ok := args["command"].(string)
+ if !ok {
+ return "", fmt.Errorf("command parameter missing or invalid")
+ }
+
+ // Request approval if callback is set
+ if f.approval != nil {
+ approved := f.approval(fmt.Sprintf("Can I execute %q?", command))
+ if !approved {
+ return fmt.Sprintf("Command execution of %q is rejected by user.", command), nil
+ }
+ }
+
+ // Execute the command.
+ var cmd *exec.Cmd
+ if runtime.GOOS == "windows" {
+ cmd = exec.Command("cmd", "/C", command)
+ } else {
+ cmd = exec.Command("sh", "-c", command)
+ }
+
+ output, err := cmd.CombinedOutput()
+ if err != nil {
+ // Return both the error and any output that was produced
+ return fmt.Sprintf("Error: %v\nOutput: %s", err, output), nil
+ }
+
+ result := strings.TrimSpace(string(output))
+ if result == "" {
+ return "Command executed successfully (no output)", nil
+ }
+
+ return result, nil
+}
diff --git a/internal/controller/loop.go b/internal/controller/loop.go
index 64536aa..73868ab 100644
--- a/internal/controller/loop.go
+++ b/internal/controller/loop.go
@@ -20,14 +20,9 @@ import (
"github.com/google/gar/agent"
"github.com/google/gar/proto"
- "golang.org/x/sync/errgroup"
)
-// Task represents a task to be executed by an agent.
-type Task struct {
- AgentID string
- Inputs []*proto.Content
-}
+const plannerAgentID = "__planner"
// LoopExecutor orchestrates the agentic loop workflow.
// It implements the plan-execute-evaluate-checkpoint cycle.
@@ -55,7 +50,7 @@ func NewLoopExecutor(ctx context.Context, config LoopConfig) (*LoopExecutor, err
return nil, fmt.Errorf("session manager cannot be nil")
}
if config.MaxSteps == 0 {
- config.MaxSteps = 10 // Default max steps per trigger
+ return nil, fmt.Errorf("max_steps cannot be zero")
}
// Plan function is required
if config.Planner == nil {
@@ -92,6 +87,7 @@ func (e *LoopExecutor) runLoop(ctx context.Context, session *Session, incoming *
return fmt.Errorf("failed to write input content: %w", err)
}
+ var nextAgentID = plannerAgentID // Start from planner.
for steps < e.maxSteps {
// Check context cancellation
select {
@@ -101,26 +97,17 @@ func (e *LoopExecutor) runLoop(ctx context.Context, session *Session, incoming *
}
history := session.History()
- handoffs, err := e.plan(ctx, session.ID(), history)
+ handoff, err := e.runAgent(ctx, session, nextAgentID, history, handler)
if err != nil {
- return fmt.Errorf("planning failed: %w", err)
+ return err
}
- if len(handoffs) == 0 {
+ if handoff == "" {
// No more agent handoffs to execute; loop is complete.
return nil
}
- g, ctx := errgroup.WithContext(ctx)
- for _, agentID := range handoffs {
- g.Go(func() error {
- return e.runHandoff(ctx, session, history, agentID, handler)
- })
- }
- if err := g.Wait(); err != nil {
- return err
- }
-
+ nextAgentID = handoff
steps++
}
@@ -128,40 +115,48 @@ func (e *LoopExecutor) runLoop(ctx context.Context, session *Session, incoming *
return fmt.Errorf("max steps per trigger (%d) reached", e.maxSteps)
}
-func (e *LoopExecutor) plan(ctx context.Context, sessionID string, history []*proto.Content) ([]string, error) {
- var handoffs []string
- handler := func(outgoing *proto.ProcessResponse) error {
- handoffs = append(handoffs, outgoing.AgentHandoff)
- return nil
- }
- if err := e.planner.Process(ctx, sessionID, &proto.ProcessRequest{
- Contents: history,
- }, handler); err != nil {
- return nil, fmt.Errorf("planner failed to process: %w", err)
- }
- return handoffs, nil
-}
-
-func (e *LoopExecutor) runHandoff(ctx context.Context, session *Session, inputs []*proto.Content, agentID string, handler agent.OutputHandler) error {
- // TODO(jbd): Log task start and task end to allow resuming dangling tasks.
- taskOutputHandler := func(outgoing *proto.ProcessResponse) error {
- if err := session.WriteContent(ctx, agentID, outgoing.CheckpointId, outgoing.Contents); err != nil {
- return fmt.Errorf("failed to write output content: %w", err)
+func (e *LoopExecutor) runAgent(ctx context.Context, session *Session, agentID string, inputs []*proto.Content, handler agent.OutputHandler) (handoff string, err error) {
+ var buffer []*proto.Content
+ runHandler := func(outgoing *proto.ProcessResponse) error {
+ if outgoing.AgentHandoff != "" {
+ // Only support one handoff a time.
+ handoff = outgoing.AgentHandoff
+ if err := session.WriteAgentHandoff(ctx, agentID, handoff); err != nil {
+ return fmt.Errorf("failed to write handoff: %w", err)
+ }
+ return nil
+ }
+ buffer = append(buffer, outgoing.Contents...)
+ if outgoing.CheckpointId != "" {
+ // Buffer until checkpoint or to the end.
+ if err := session.WriteContent(ctx, agentID, outgoing.CheckpointId, buffer); err != nil {
+ return fmt.Errorf("failed to write output content: %w", err)
+ }
+ buffer = []*proto.Content{}
}
return handler(outgoing)
}
- ag, err := e.registry.Get(agentID)
- if err != nil {
- return fmt.Errorf("failed to get agent: %w", err)
+ var a agent.Agent
+ if agentID == plannerAgentID {
+ a = e.planner
+ } else {
+ a, err = e.registry.Get(agentID)
+ if err != nil {
+ return "", fmt.Errorf("failed to get agent: %w", err)
+ }
}
- // TODO(lhuan): Handle scenario where agent is marked healthy (optimistic) but fails to respond (e.g. still starting up).
- // Return "agent internal error, try again later" to the user.
- if err := ag.Process(ctx, session.ID(), &proto.ProcessRequest{
+ if err := a.Process(ctx, session.ID(), &proto.ProcessRequest{
Contents: inputs,
- }, taskOutputHandler); err != nil {
- return fmt.Errorf("agent process failed: %w", err)
+ }, runHandler); err != nil {
+ return "", fmt.Errorf("agent process failed: %w", err)
+ }
+
+ if len(buffer) > 0 {
+ if err := session.WriteContent(ctx, agentID, "", buffer); err != nil {
+ return "", fmt.Errorf("failed to write output buffer: %w", err)
+ }
}
- return nil
+ return handoff, nil
}
diff --git a/internal/controller/session.go b/internal/controller/session.go
index f6e6c29..2523828 100644
--- a/internal/controller/session.go
+++ b/internal/controller/session.go
@@ -315,6 +315,24 @@ func (sm *SessionManager) CloseAll() {
}
}
+func (s *Session) WriteAgentHandoff(ctx context.Context, source, target string) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ return s.eventLog.AppendEvent(ctx, &proto.Event{
+ SessionId: s.id,
+ SenderId: source,
+ Timestamp: timestamppb.Now(),
+ ControllerTimestamp: timestamppb.Now(),
+ Kind: &proto.Event_HandoffEvent{
+ HandoffEvent: &proto.HandoffEvent{
+ SourceAgentId: source,
+ TargetAgentId: target,
+ },
+ },
+ })
+}
+
// WriteContent appends an incoming content message to the session.
// Creates a checkpoint only if checkpoint_id is provided in the content.
func (s *Session) WriteContent(ctx context.Context, sender string, checkpointID string, contents []*proto.Content) error {
@@ -406,17 +424,3 @@ func (s *Session) History() []*proto.Content {
return s.messageHistory
}
-
-func (s *Session) CheckpointIDs() []string {
- s.mu.RLock()
- defer s.mu.RUnlock()
-
- // TODO(jbd): Not ordered, but is still useful
- // for introspection capabilities.
-
- var checkpointIDs []string
- for checkpointID := range s.checkpointIDs {
- checkpointIDs = append(checkpointIDs, checkpointID)
- }
- return checkpointIDs
-}
diff --git a/internal/eventlog/file.go b/internal/eventlog/file.go
index 771c9fd..5beae0e 100644
--- a/internal/eventlog/file.go
+++ b/internal/eventlog/file.go
@@ -122,6 +122,8 @@ func (e *FileEventLog) LoadEvents(ctx context.Context, checkpointID string) ([]*
var events []*proto.Event
scanner := bufio.NewScanner(f)
+ var buf = make([]byte, 1024*1024) // initial 1MB
+ scanner.Buffer(buf, 8*1024*1024) // max 8MB
checkpointFound := false
for scanner.Scan() {