Agent Executor (AX) is Google's open agentic orchestration runtime
Go
feat(cli): forward stdin and Ctrl-C in ax ssh (#413)
Anzal Husain Abidi92d297e97c43
diff --git a/cmd/ax/main.go b/cmd/ax/main.goindex c8733f8..fad4b79 100644--- a/cmd/ax/main.go+++ b/cmd/ax/main.go@@ -22,6 +22,7 @@ import ("io""net""os"+ "os/signal""sort""strconv""strings"@@ -210,6 +211,7 @@ Available Commands:describe model <name> Show detailed information about a modelwatch task <name> Stream live status and condition updates for a taskssh <task-name> [-- cmd] Run a command or shell inside the running task container+ (Ctrl-C is forwarded; press it twice quickly, or Ctrl-\, to exit locally)suspend task <name> Suspend execution of a task and checkpoint stateresume task <name> Resume execution of a suspended taskdelete task <name> Delete a task@@ -1115,10 +1117,29 @@ func runSSH(serverURL, atespace, kubeContext string, args []string) error {}defer guestClient.Close()+ // A bare shell on a terminal runs with -i, so it prompts and Ctrl-C stops the+ // command it is running rather than the shell itself.+ if stdinIsTerminal() && len(cmdToRun) == 1 && cmdToRun[0] == "/bin/sh" {+ cmdToRun = []string{"/bin/sh", "-i"}+ }++ // Ctrl-C is passed on to the remote command instead of ending ax ssh. Pressing+ // it twice in quick succession gives up on the session and exits locally, so+ // a hung connection never traps the terminal.+ rawSigs := make(chan os.Signal, 4)+ signal.Notify(rawSigs, os.Interrupt)+ defer signal.Stop(rawSigs)+ sigs := escalateInterrupts(rawSigs, interruptExitWindow, func() {+ fmt.Fprintln(os.Stderr, "\nax ssh: interrupted twice, exiting")+ os.Exit(130)+ })+exitCode, err := guestClient.Exec(context.Background(), guest.ExecOptions{Command: cmdToRun,+ Stdin: os.Stdin,Stdout: os.Stdout,Stderr: os.Stderr,+ Signals: sigs,})if err != nil {return err@@ -1130,3 +1151,38 @@ func runSSH(serverURL, atespace, kubeContext string, args []string) error {return nil}++// interruptExitWindow is how soon a second Ctrl-C must follow the first to end+// ax ssh locally instead of being forwarded to the remote command.+const interruptExitWindow = time.Second++// escalateInterrupts relays each signal from in to the returned channel, except+// that a signal arriving within window of the previous one calls exit instead.+// This keeps a single Ctrl-C going to the remote command while a repeated one+// still works as an escape hatch.+func escalateInterrupts(in <-chan os.Signal, window time.Duration, exit func()) <-chan os.Signal {+ out := make(chan os.Signal, 1)+ go func() {+ var last time.Time+ for sig := range in {+ now := time.Now()+ if !last.IsZero() && now.Sub(last) < window {+ exit()+ return+ }+ last = now+ select {+ case out <- sig:+ default:+ }+ }+ }()+ return out+}++// stdinIsTerminal reports whether standard input is a terminal rather than a+// pipe or file.+func stdinIsTerminal() bool {+ fi, err := os.Stdin.Stat()+ return err == nil && fi.Mode()&os.ModeCharDevice != 0+}diff --git a/cmd/ax/ssh_interrupt_test.go b/cmd/ax/ssh_interrupt_test.gonew file mode 100644index 0000000..adcc1f3--- /dev/null+++ b/cmd/ax/ssh_interrupt_test.go@@ -0,0 +1,66 @@+// 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 (+ "os"+ "testing"+ "time"+)++func TestEscalateInterruptsForwardsFirstAndExitsOnSecond(t *testing.T) {+ in := make(chan os.Signal, 2)+ exited := make(chan struct{})+ out := escalateInterrupts(in, time.Minute, func() { close(exited) })++ in <- os.Interrupt+ select {+ case <-out:+ case <-time.After(2 * time.Second):+ t.Fatal("first interrupt was not forwarded")+ }+ select {+ case <-exited:+ t.Fatal("exited after a single interrupt")+ default:+ }++ in <- os.Interrupt+ select {+ case <-exited:+ case <-time.After(2 * time.Second):+ t.Fatal("second interrupt did not exit")+ }+ select {+ case <-out:+ t.Error("second interrupt was forwarded as well")+ default:+ }+}++func TestEscalateInterruptsSlowSecondIsForwarded(t *testing.T) {+ in := make(chan os.Signal, 2)+ out := escalateInterrupts(in, 10*time.Millisecond, func() { t.Error("exited on a slow second interrupt") })++ in <- os.Interrupt+ <-out+ time.Sleep(50 * time.Millisecond)+ in <- os.Interrupt+ select {+ case <-out:+ case <-time.After(2 * time.Second):+ t.Fatal("second interrupt outside the window was not forwarded")+ }+}diff --git a/internal/guest/client.go b/internal/guest/client.goindex 959e1fe..ffb7480 100644--- a/internal/guest/client.go+++ b/internal/guest/client.go@@ -19,7 +19,9 @@ import ("errors""fmt""io"+ "os""strings"+ "syscall""time"ateenvv1alpha "github.com/agent-substrate/env/proto/ateenv/v1alpha"@@ -85,12 +87,18 @@ type ExecOptions struct {Command []stringCwd stringEnv map[string]string- Stdout io.Writer- Stderr io.Writer+ // Stdin, if set, is copied to the process's standard input, which is closed+ // once Stdin reaches EOF. If nil, the process reads an empty stdin.+ Stdin io.Reader+ Stdout io.Writer+ Stderr io.Writer+ // Signals, if set, delivers each signal received on it to the process group.+ // Only SIGHUP, SIGINT, SIGQUIT and SIGTERM are forwarded.+ Signals <-chan os.Signal}-// Exec runs a command inside the task container and streams stdout/stderr until completion.-// It returns the process exit code.+// Exec runs a command inside the task container, feeding it opts.Stdin and+// streaming stdout/stderr until completion. It returns the process exit code.func (c *Client) Exec(ctx context.Context, opts ExecOptions) (int, error) {if len(opts.Command) == 0 {return 1, errors.New("exec: command cannot be empty")@@ -100,12 +108,24 @@ func (c *Client) Exec(ctx context.Context, opts ExecOptions) (int, error) {Command: opts.Command,Cwd: opts.Cwd,Env: opts.Env,+ Stdin: opts.Stdin != nil,})if err != nil {return 1, fmt.Errorf("starting process: %w", err)}pid := proc.GetProcessId()++ // Input and signal forwarding stop when the command finishes.+ ctx, cancel := context.WithCancel(ctx)+ defer cancel()+ if opts.Stdin != nil {+ go c.forwardStdin(ctx, pid, opts.Stdin)+ }+ if opts.Signals != nil {+ go c.forwardSignals(ctx, pid, opts.Signals)+ }+stream, err := c.process.StreamProcessOutput(ctx, &ateenvv1alpha.StreamProcessOutputRequest{ProcessId: pid,Follow: true,@@ -150,3 +170,51 @@ func (c *Client) Exec(ctx context.Context, opts ExecOptions) (int, error) {}}}++// forwardStdin copies r to the stdin of process pid and closes it when r ends.+// Errors are dropped: they mean the process has exited or the connection is+// gone, and Exec reports either from the output stream.+func (c *Client) forwardStdin(ctx context.Context, pid string, r io.Reader) {+ stream, err := c.process.WriteProcessInput(ctx)+ if err != nil {+ return+ }+ buf := make([]byte, 32*1024)+ for {+ n, readErr := r.Read(buf)+ if n > 0 {+ if err := stream.Send(&ateenvv1alpha.WriteProcessInputRequest{ProcessId: pid, Data: buf[:n]}); err != nil {+ return+ }+ }+ if readErr != nil {+ if err := stream.Send(&ateenvv1alpha.WriteProcessInputRequest{ProcessId: pid, Close: true}); err != nil {+ return+ }+ _, _ = stream.CloseAndRecv()+ return+ }+ }+}++// forwardedSignals maps the local signals Exec forwards to their guest equivalents.+var forwardedSignals = map[os.Signal]ateenvv1alpha.Signal{+ syscall.SIGHUP: ateenvv1alpha.Signal_SIGNAL_HUP,+ syscall.SIGINT: ateenvv1alpha.Signal_SIGNAL_INT,+ syscall.SIGQUIT: ateenvv1alpha.Signal_SIGNAL_QUIT,+ syscall.SIGTERM: ateenvv1alpha.Signal_SIGNAL_TERM,+}++// forwardSignals delivers each signal from sigs to process pid until ctx ends.+func (c *Client) forwardSignals(ctx context.Context, pid string, sigs <-chan os.Signal) {+ for {+ select {+ case <-ctx.Done():+ return+ case sig := <-sigs:+ if guestSig, ok := forwardedSignals[sig]; ok {+ _, _ = c.process.SignalProcess(ctx, &ateenvv1alpha.SignalProcessRequest{ProcessId: pid, Signal: guestSig})+ }+ }+ }+}diff --git a/internal/guest/client_test.go b/internal/guest/client_test.gonew file mode 100644index 0000000..7d8109d--- /dev/null+++ b/internal/guest/client_test.go@@ -0,0 +1,240 @@+// 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 guest_test++import (+ "bytes"+ "context"+ "io"+ "net"+ "os"+ "strings"+ "sync"+ "testing"+ "time"++ envguest "github.com/agent-substrate/env/guest"+ "github.com/google/ax/internal/guest"+)++// startGuest serves the real guest services on a local port and returns a+// client connected to them.+func startGuest(t *testing.T) *guest.Client {+ t.Helper()+ cfg := envguest.DefaultConfig()+ cfg.Workspace = t.TempDir()+ cfg.LogDir = t.TempDir()+ srv, cleanup, err := envguest.NewServer(cfg)+ if err != nil {+ t.Fatalf("creating guest server: %v", err)+ }+ lis, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("listening: %v", err)+ }+ go func() { _ = srv.Serve(lis) }()+ t.Cleanup(func() {+ srv.Stop()+ cleanup()+ })++ client, err := guest.Dial(lis.Addr().String())+ if err != nil {+ t.Fatalf("dialing guest: %v", err)+ }+ t.Cleanup(func() { _ = client.Close() })+ return client+}++func execContext(t *testing.T) context.Context {+ t.Helper()+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ t.Cleanup(cancel)+ return ctx+}++// newPipe returns an OS pipe standing in for a terminal's stdin.+func newPipe(t *testing.T) (*os.File, *os.File) {+ t.Helper()+ r, w, err := os.Pipe()+ if err != nil {+ t.Fatalf("creating pipe: %v", err)+ }+ t.Cleanup(func() {+ _ = r.Close()+ _ = w.Close()+ })+ return r, w+}++// syncBuffer is a bytes.Buffer that can be written and read from different goroutines.+type syncBuffer struct {+ mu sync.Mutex+ buf bytes.Buffer+}++func (b *syncBuffer) Write(p []byte) (int, error) {+ b.mu.Lock()+ defer b.mu.Unlock()+ return b.buf.Write(p)+}++func (b *syncBuffer) String() string {+ b.mu.Lock()+ defer b.mu.Unlock()+ return b.buf.String()+}++func TestExecForwardsStdin(t *testing.T) {+ client := startGuest(t)++ var stdout bytes.Buffer+ code, err := client.Exec(execContext(t), guest.ExecOptions{+ Command: []string{"cat"},+ Stdin: strings.NewReader("hello from stdin\n"),+ Stdout: &stdout,+ })+ if err != nil {+ t.Fatalf("Exec: %v", err)+ }+ if code != 0 {+ t.Errorf("exit code = %d, want 0", code)+ }+ if got := stdout.String(); got != "hello from stdin\n" {+ t.Errorf("stdout = %q, want %q", got, "hello from stdin\n")+ }+}++func TestExecStreamsInteractiveInput(t *testing.T) {+ client := startGuest(t)++ // Each line is only written after the reply to the previous one arrives,+ // so this passes only if input and output stream while the process runs.+ stdinR, stdinW := newPipe(t)+ stdout := &syncBuffer{}+ done := make(chan struct{})+ var (+ code int+ err error+ )+ go func() {+ defer close(done)+ code, err = client.Exec(execContext(t), guest.ExecOptions{+ Command: []string{"sh", "-c", "while read line; do echo \"got $line\"; done; echo bye"},+ Stdin: stdinR,+ Stdout: stdout,+ })+ }()++ waitFor := func(want string) {+ t.Helper()+ deadline := time.Now().Add(5 * time.Second)+ for !strings.Contains(stdout.String(), want) {+ if time.Now().After(deadline) {+ t.Fatalf("timed out waiting for %q, stdout so far %q", want, stdout.String())+ }+ time.Sleep(10 * time.Millisecond)+ }+ }+ _, _ = io.WriteString(stdinW, "one\n")+ waitFor("got one\n")+ _, _ = io.WriteString(stdinW, "two\n")+ waitFor("got two\n")++ // Closing stdin ends the read loop, so the shell prints bye and exits.+ _ = stdinW.Close()+ <-done+ if err != nil {+ t.Fatalf("Exec: %v", err)+ }+ if code != 0 {+ t.Errorf("exit code = %d, want 0", code)+ }+ if got, want := stdout.String(), "got one\ngot two\nbye\n"; got != want {+ t.Errorf("stdout = %q, want %q", got, want)+ }+}++func TestExecPropagatesExitCode(t *testing.T) {+ client := startGuest(t)++ code, err := client.Exec(execContext(t), guest.ExecOptions{+ Command: []string{"sh", "-c", "read code; exit $code"},+ Stdin: strings.NewReader("7\n"),+ })+ if err != nil {+ t.Fatalf("Exec: %v", err)+ }+ if code != 7 {+ t.Errorf("exit code = %d, want 7", code)+ }+}++func TestExecWithoutStdinReadsEmpty(t *testing.T) {+ client := startGuest(t)++ var stdout bytes.Buffer+ code, err := client.Exec(execContext(t), guest.ExecOptions{+ Command: []string{"sh", "-c", "cat; echo done"},+ Stdout: &stdout,+ })+ if err != nil {+ t.Fatalf("Exec: %v", err)+ }+ if code != 0 || stdout.String() != "done\n" {+ t.Errorf("got exit code %d, stdout %q; want 0, %q", code, stdout.String(), "done\n")+ }+}++func TestExecForwardsSignals(t *testing.T) {+ client := startGuest(t)++ // The process prints once it is running, then waits on stdin, which the+ // test keeps open. Only the forwarded SIGINT can end it.+ stdinR, _ := newPipe(t)+ stdout := &syncBuffer{}+ sigs := make(chan os.Signal, 1)+ done := make(chan struct{})+ var (+ code int+ err error+ )+ go func() {+ defer close(done)+ code, err = client.Exec(execContext(t), guest.ExecOptions{+ Command: []string{"sh", "-c", "echo ready; cat"},+ Stdin: stdinR,+ Stdout: stdout,+ Signals: sigs,+ })+ }()++ deadline := time.Now().Add(5 * time.Second)+ for !strings.Contains(stdout.String(), "ready") {+ if time.Now().After(deadline) {+ t.Fatalf("process never became ready")+ }+ time.Sleep(10 * time.Millisecond)+ }+ sigs <- os.Interrupt+ <-done++ if err != nil {+ t.Fatalf("Exec: %v", err)+ }+ if code != 130 {+ t.Errorf("exit code = %d, want 130 (killed by SIGINT)", code)+ }+}