Skip to content

armgit / ax

Public Imported from GitHub
0

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

Go

Add doctor command to diagnose sidecar, assets, and runtime

JBDb77731302075
diff --git a/cmd/ax/doctor.go b/cmd/ax/doctor.go
new file mode 100644
index 0000000..77f89c5
--- /dev/null
+++ b/cmd/ax/doctor.go
@@ -0,0 +1,251 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package main
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+
+ "charm.land/lipgloss/v2"
+ "github.com/google/ax/internal/config"
+ "github.com/spf13/cobra"
+)
+
+var doctorEndpoint string
+
+var doctorCmd = &cobra.Command{
+ Use: "doctor",
+ Short: "Diagnose and display health of the AX runtime, sidecar process, and system metrics",
+ Long: `Display the current diagnostic status of:
+- Python sidecar process (PID, CPU, Memory RSS, Uptime, Command)
+- gRPC harness endpoint connectivity
+- AX config/assets directory status
+- Go runtime memory and goroutines`,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ printStatus(os.Stdout, doctorEndpoint)
+ return nil
+ },
+}
+
+func init() {
+ doctorCmd.Flags().StringVar(&doctorEndpoint, "endpoint", "127.0.0.1:50053", "Harness gRPC endpoint to monitor")
+}
+
+// Stats holds the sampled metrics and state of the AX system.
+type Stats struct {
+ Timestamp time.Time
+ AssetsDir string
+ SidecarPID int
+ SidecarAlive bool
+ SidecarCPU string
+ SidecarRSS string
+ SidecarUptime string
+ SidecarCmd string
+ Endpoint string
+ EndpointActive bool
+ PythonVersion string
+ GoVersion string
+ NumGoroutine int
+ MemAllocMB float64
+ NumAssetsFiles int
+ AssetsSizeKB int64
+}
+
+// Sampler collects status of the AX runtime and Python sidecar.
+type Sampler struct {
+ endpoint string
+}
+
+// NewSampler creates a new Sampler for the given endpoint.
+func NewSampler(endpoint string) *Sampler {
+ if endpoint == "" {
+ endpoint = "127.0.0.1:50053"
+ }
+ return &Sampler{
+ endpoint: endpoint,
+ }
+}
+
+// Sample collects current metrics from the system.
+func (s *Sampler) Sample() Stats {
+ st := Stats{
+ Timestamp: time.Now(),
+ Endpoint: s.endpoint,
+ GoVersion: runtime.Version(),
+ NumGoroutine: runtime.NumGoroutine(),
+ }
+
+ var m runtime.MemStats
+ runtime.ReadMemStats(&m)
+ st.MemAllocMB = float64(m.Alloc) / (1024 * 1024)
+
+ // 1. Assets dir
+ assetsDir, err := config.AXAssetsDir()
+ if err == nil {
+ st.AssetsDir = assetsDir
+ if entries, err := os.ReadDir(assetsDir); err == nil {
+ st.NumAssetsFiles = len(entries)
+ for _, e := range entries {
+ if info, err := e.Info(); err == nil {
+ st.AssetsSizeKB += info.Size() / 1024
+ }
+ }
+ }
+
+ pidFile := filepath.Join(assetsDir, "sidecar.pid")
+ if data, err := os.ReadFile(pidFile); err == nil {
+ if pid, err := strconv.Atoi(strings.TrimSpace(string(data))); err == nil && pid > 0 {
+ st.SidecarPID = pid
+ st.SidecarAlive = isProcessAlive(pid)
+ }
+ }
+ }
+
+ // 2. Sidecar process details if alive
+ if st.SidecarAlive && st.SidecarPID > 0 {
+ out, err := exec.Command("ps", "-p", strconv.Itoa(st.SidecarPID), "-o", "%cpu,rss,etime,command").Output()
+ if err == nil {
+ lines := strings.Split(strings.TrimSpace(string(out)), "\n")
+ if len(lines) >= 2 {
+ fields := strings.Fields(lines[1])
+ if len(fields) >= 4 {
+ st.SidecarCPU = fields[0] + "%"
+ if rssKB, err := strconv.ParseFloat(fields[1], 64); err == nil {
+ st.SidecarRSS = fmt.Sprintf("%.1f MB", rssKB/1024)
+ } else {
+ st.SidecarRSS = fields[1] + " KB"
+ }
+ st.SidecarUptime = fields[2]
+ st.SidecarCmd = strings.Join(fields[3:], " ")
+ }
+ }
+ }
+ }
+
+ // 3. Check endpoint connectivity
+ conn, err := net.DialTimeout("tcp", s.endpoint, 120*time.Millisecond)
+ if err == nil {
+ st.EndpointActive = true
+ _ = conn.Close()
+ }
+
+ // 4. Python version
+ if out, err := exec.Command("python3", "--version").Output(); err == nil {
+ st.PythonVersion = strings.TrimSpace(string(out))
+ } else {
+ st.PythonVersion = "python3 not found"
+ }
+
+ return st
+}
+
+func isProcessAlive(pid int) bool {
+ if pid <= 0 {
+ return false
+ }
+ proc, err := os.FindProcess(pid)
+ if err != nil {
+ return false
+ }
+ err = proc.Signal(syscall.Signal(0))
+ return err == nil || errors.Is(err, syscall.EPERM)
+}
+
+// Display handles plain text rendering of AX runtime metrics using bold labels and headers.
+type Display struct {
+ w io.Writer
+ styleBold lipgloss.Style
+ styleTitle lipgloss.Style
+}
+
+// NewDisplay creates a new Display writer.
+func NewDisplay(w io.Writer) *Display {
+ if w == nil {
+ w = os.Stdout
+ }
+
+ return &Display{
+ w: w,
+ styleBold: lipgloss.NewStyle().Bold(true),
+ styleTitle: lipgloss.NewStyle().Bold(true),
+ }
+}
+
+// Render formats and prints the system status in plain bold text.
+func (d *Display) Render(stats Stats) {
+ var b strings.Builder
+
+ b.WriteString(d.styleTitle.Render("ax doctor") + " (" + stats.Timestamp.Format("2006-01-02 15:04:05 MST") + ")\n\n")
+
+ b.WriteString(d.styleBold.Render("Sidecar:") + "\n")
+ if stats.SidecarAlive {
+ b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Status:")), "RUNNING"))
+ b.WriteString(fmt.Sprintf(" %s %d\n", d.styleBold.Render(fmt.Sprintf("%-14s", "PID:")), stats.SidecarPID))
+ if stats.SidecarCPU != "" {
+ b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "CPU:")), stats.SidecarCPU))
+ }
+ if stats.SidecarRSS != "" {
+ b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Memory (RSS):")), stats.SidecarRSS))
+ }
+ if stats.SidecarUptime != "" {
+ b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Elapsed Time:")), stats.SidecarUptime))
+ }
+ if stats.SidecarCmd != "" {
+ b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Command:")), stats.SidecarCmd))
+ }
+ } else {
+ b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Status:")), "STOPPED"))
+ b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "PID:")), "none"))
+ }
+
+ endpointStatus := stats.Endpoint
+ if stats.EndpointActive {
+ endpointStatus += " (ACTIVE)"
+ } else {
+ endpointStatus += " (UNREACHABLE)"
+ }
+ b.WriteString(fmt.Sprintf(" %s %s\n\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Endpoint:")), endpointStatus))
+
+ b.WriteString(d.styleBold.Render("Assets:") + "\n")
+ b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Assets Dir:")), stats.AssetsDir))
+ b.WriteString(fmt.Sprintf(" %s %d files (%d KB)\n\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Asset Files:")), stats.NumAssetsFiles, stats.AssetsSizeKB))
+
+ b.WriteString(d.styleBold.Render("Environment:") + "\n")
+ b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Python:")), stats.PythonVersion))
+ b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Go Runtime:")), stats.GoVersion))
+ b.WriteString(fmt.Sprintf(" %s %d\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Goroutines:")), stats.NumGoroutine))
+ b.WriteString(fmt.Sprintf(" %s %.2f MB\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Go Memory:")), stats.MemAllocMB))
+
+ fmt.Fprint(d.w, b.String())
+}
+
+// printStatus samples the system and renders the output to w.
+func printStatus(w io.Writer, endpoint string) {
+ sampler := NewSampler(endpoint)
+ stats := sampler.Sample()
+ display := NewDisplay(w)
+ display.Render(stats)
+}
diff --git a/cmd/ax/doctor_test.go b/cmd/ax/doctor_test.go
new file mode 100644
index 0000000..8994ddd
--- /dev/null
+++ b/cmd/ax/doctor_test.go
@@ -0,0 +1,147 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package main
+
+import (
+ "bytes"
+ "net"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+func TestDoctorCommandRegistration(t *testing.T) {
+ cmd, _, err := rootCmd.Find([]string{"doctor"})
+ if err != nil {
+ t.Fatalf("failed to find 'doctor' subcommand: %v", err)
+ }
+ if cmd.Name() != "doctor" {
+ t.Fatalf("expected subcommand name 'doctor', got '%s'", cmd.Name())
+ }
+
+ if endpointFlag := cmd.Flags().Lookup("endpoint"); endpointFlag == nil {
+ t.Errorf("expected --endpoint flag on doctor command")
+ }
+}
+
+func TestSampler_NoSidecar(t *testing.T) {
+ tmpDir := t.TempDir()
+ t.Setenv("AX_DURABLE_DIR", tmpDir)
+
+ sampler := NewSampler("127.0.0.1:0")
+ stats := sampler.Sample()
+
+ if stats.SidecarAlive {
+ t.Errorf("expected SidecarAlive to be false, got true")
+ }
+ if stats.SidecarPID != 0 {
+ t.Errorf("expected SidecarPID to be 0, got %d", stats.SidecarPID)
+ }
+ if stats.AssetsDir != filepath.Join(tmpDir, ".ax") {
+ t.Errorf("expected AssetsDir %s, got %s", filepath.Join(tmpDir, ".ax"), stats.AssetsDir)
+ }
+}
+
+func TestSampler_WithActiveProcessAndEndpoint(t *testing.T) {
+ tmpDir := t.TempDir()
+ t.Setenv("AX_DURABLE_DIR", tmpDir)
+
+ cmd := exec.Command("sleep", "10")
+ if err := cmd.Start(); err != nil {
+ t.Fatalf("failed to start sleep process: %v", err)
+ }
+ defer func() {
+ _ = cmd.Process.Kill()
+ _ = cmd.Wait()
+ }()
+
+ axDir := filepath.Join(tmpDir, ".ax")
+ if err := os.MkdirAll(axDir, 0755); err != nil {
+ t.Fatalf("failed to create axDir: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(axDir, "sidecar.pid"), []byte(strconv.Itoa(cmd.Process.Pid)+"\n"), 0644); err != nil {
+ t.Fatalf("failed to write pid file: %v", err)
+ }
+
+ l, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatalf("failed to listen: %v", err)
+ }
+ defer l.Close()
+
+ sampler := NewSampler(l.Addr().String())
+ stats := sampler.Sample()
+
+ if !stats.SidecarAlive {
+ t.Errorf("expected SidecarAlive to be true")
+ }
+ if stats.SidecarPID != cmd.Process.Pid {
+ t.Errorf("expected SidecarPID %d, got %d", cmd.Process.Pid, stats.SidecarPID)
+ }
+ if !stats.EndpointActive {
+ t.Errorf("expected EndpointActive to be true")
+ }
+}
+
+func TestDisplay_Render(t *testing.T) {
+ var buf bytes.Buffer
+ display := NewDisplay(&buf)
+
+ stats := Stats{
+ AssetsDir: "/test/assets",
+ SidecarPID: 1234,
+ SidecarAlive: true,
+ SidecarCPU: "0.5%",
+ SidecarRSS: "45.2 MB",
+ SidecarUptime: "02:15",
+ SidecarCmd: "python3 -m test",
+ Endpoint: "127.0.0.1:50053",
+ PythonVersion: "Python 3.13.0",
+ GoVersion: "go1.26.3",
+ NumGoroutine: 5,
+ MemAllocMB: 12.4,
+ }
+
+ display.Render(stats)
+ output := buf.String()
+
+ if !strings.Contains(output, "ax doctor") {
+ t.Errorf("expected output to contain 'ax doctor'")
+ }
+ if !strings.Contains(output, "1234") {
+ t.Errorf("expected output to contain PID '1234'")
+ }
+ if !strings.Contains(output, "RUNNING") {
+ t.Errorf("expected output to contain 'RUNNING'")
+ }
+ if !strings.Contains(output, "Assets:") {
+ t.Errorf("expected output to contain 'Assets:'")
+ }
+ if !strings.Contains(output, "Environment:") {
+ t.Errorf("expected output to contain 'Environment:'")
+ }
+}
+
+func TestPrintStatus(t *testing.T) {
+ var buf bytes.Buffer
+ printStatus(&buf, "127.0.0.1:0")
+
+ if buf.Len() == 0 {
+ t.Errorf("expected non-empty printStatus output")
+ }
+}
diff --git a/cmd/ax/main.go b/cmd/ax/main.go
index bee13db..0112a76 100644
--- a/cmd/ax/main.go
+++ b/cmd/ax/main.go
@@ -40,8 +40,9 @@ var rootCmd = &cobra.Command{
Short: "Execute a conversation or resume an existing one",
Long: `Execute a new conversation or resume an existing one.
If no conversation ID is provided, a new UUID will be generated.`,
- SilenceUsage: true,
- RunE: runExec,
+ SilenceUsage: true,
+ SilenceErrors: true,
+ RunE: runExec,
}
func init() {
@@ -49,6 +50,7 @@ func init() {
rootCmd.AddCommand(execCmd)
rootCmd.AddCommand(serveCmd)
+ rootCmd.AddCommand(doctorCmd)
}
func connect(server string) (*grpc.ClientConn, error) {