The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
feat(handoff): launch resumed sessions in detached terminals
akhilpotturi62a72232dedf
diff --git a/cli/beacon/cmd/handoff_launch.go b/cli/beacon/cmd/handoff_launch.gonew file mode 100644index 00000000..1f266473--- /dev/null+++ b/cli/beacon/cmd/handoff_launch.go@@ -0,0 +1,36 @@+package cmd++import (+ "github.com/spf13/cobra"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/handoff"+)++var handoffLaunchSpec string++var handoffLaunchCmd = &cobra.Command{+ Use: "_launch",+ Short: "Run a private handoff launch specification",+ Hidden: true,+ Args: cobra.NoArgs,+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ code, err := handoff.RunLaunchSpec(handoffLaunchSpec, cmd.InOrStdin(), cmd.OutOrStdout(), cmd.ErrOrStderr())+ if err != nil {+ return err+ }+ if code != 0 {+ if code < 0 {+ code = 1+ }+ handoffExit(code)+ }+ return nil+ },+}++func init() {+ handoffCmd.AddCommand(handoffLaunchCmd)+ handoffLaunchCmd.Flags().StringVar(&handoffLaunchSpec, "spec", "", "Private launch specification")+ _ = handoffLaunchCmd.MarkFlagRequired("spec")+}diff --git a/cli/beacon/cmd/handoff_resume.go b/cli/beacon/cmd/handoff_resume.goindex 68d945cd..05727d16 100644--- a/cli/beacon/cmd/handoff_resume.go+++ b/cli/beacon/cmd/handoff_resume.go@@ -21,6 +21,7 @@ type handoffResumeOptions struct {agent stringnewOnly boolcwd string+ launch stringprint boolyes booljsonPlan bool@@ -43,10 +44,12 @@ never inlined into the command line. Beacon cannot start DeepSeek Harness, and Honly reopen their own sessions, so a session of theirs continues in another runtime named with--agent.-The runtime runs in the session's directory, in this terminal. Beacon asks before launching unless---yes is given; --print shows what would run without writing or launching anything. Beacon never-passes a flag that turns a runtime's approvals off, and names the mode that asks where a CLI takes-one: Cline, for example, is always started with --auto-approve false.`,+The runtime starts in the session's directory. By default it owns this terminal while it runs.+--launch auto opens a new terminal on a desktop and uses tmux in a headless or SSH environment;+new-terminal and tmux select those modes explicitly. Beacon asks before launching unless --yes is+given; --print shows what would run without writing or launching anything. Beacon never passes a+flag that turns a runtime's approvals off, and names the mode that asks where a CLI takes one:+Cline, for example, is always started with --auto-approve false.`,Args: cobra.ExactArgs(1),SilenceUsage: true,RunE: runHandoffResume,@@ -54,15 +57,20 @@ one: Cline, for example, is always started with --auto-approve false.`,// Swapped by tests.var (- handoffLookPath = exec.LookPath- handoffLaunch = handoff.Launch- handoffIsTerminal = func() bool { return isTerminal(os.Stdin) && isTerminal(os.Stdout) }- handoffStdin io.Reader = os.Stdin- handoffExit = os.Exit+ handoffLookPath = exec.LookPath+ handoffLaunch = handoff.Launch+ handoffLaunchDetached = handoff.LaunchDetached+ handoffIsTerminal = func() bool { return isTerminal(os.Stdin) && isTerminal(os.Stdout) }+ handoffStdin io.Reader = os.Stdin+ handoffExit = os.Exit+ handoffExecutable = os.Executable)func runHandoffResume(cmd *cobra.Command, args []string) error {opts := handoffResumeOpts+ if err := handoff.ValidateLaunchMode(opts.launch); err != nil {+ return fmt.Errorf("--launch: %w", err)+ }if opts.jsonPlan && !opts.print {return errors.New("--json describes the plan and needs --print")}@@ -130,6 +138,26 @@ func runHandoffResume(cmd *cobra.Command, args []string) error {return err}}+ if opts.launch != "" && opts.launch != handoff.LaunchModeCurrent {+ beaconExecutable, err := handoffExecutable()+ if err != nil {+ return fmt.Errorf("resolve beacon executable: %w", err)+ }+ result, err := handoffLaunchDetached(plan, handoff.DetachedOptions{+ Mode: opts.launch,+ BeaconExecutable: beaconExecutable,+ SpecDir: briefDir,+ })+ if err != nil {+ return fmt.Errorf("launch %s: %w", handoff.RuntimeLabel(plan.Target), err)+ }+ fmt.Fprintf(out, "Launched %s with %s.\n", handoff.RuntimeLabel(plan.Target), result.Launcher)+ if result.AttachCommand != "" {+ fmt.Fprintf(out, "Attach with: %s\n", result.AttachCommand)+ }+ return nil+ }+code, err := handoffLaunch(plan, handoffStdin, out, errOut)if err != nil {return fmt.Errorf("start %s: %w", plan.Executable, err)@@ -200,6 +228,7 @@ func init() {f.StringVar(&handoffResumeOpts.agent, "agent", "", "Runtime to continue in: "+strings.Join(handoff.StartableNames(), ", ")+" (default the session's own)")f.BoolVar(&handoffResumeOpts.newOnly, "new", false, "Start a new session from a brief even when the session could be reopened")f.StringVar(&handoffResumeOpts.cwd, "cwd", "", "Directory to start the runtime in (default the session's directory)")+ f.StringVar(&handoffResumeOpts.launch, "launch", handoff.LaunchModeCurrent, "Where to launch: current, auto, new-terminal or tmux")f.BoolVar(&handoffResumeOpts.print, "print", false, "Show what would run without writing a brief or launching anything")f.BoolVar(&handoffResumeOpts.yes, "yes", false, "Launch without asking")f.BoolVar(&handoffResumeOpts.jsonPlan, "json", false, "With --print, describe the plan as JSON")diff --git a/cli/beacon/cmd/handoff_resume_test.go b/cli/beacon/cmd/handoff_resume_test.goindex 40fcebf8..25691cad 100644--- a/cli/beacon/cmd/handoff_resume_test.go+++ b/cli/beacon/cmd/handoff_resume_test.go@@ -44,7 +44,7 @@ func newResumeFixture(t *testing.T) *resumeFixture {}},})- prevLook, prevLaunch, prevTerm, prevStdin, prevExit := handoffLookPath, handoffLaunch, handoffIsTerminal, handoffStdin, handoffExit+ prevLook, prevLaunch, prevDetached, prevTerm, prevStdin, prevExit, prevExecutable := handoffLookPath, handoffLaunch, handoffLaunchDetached, handoffIsTerminal, handoffStdin, handoffExit, handoffExecutablehandoffLookPath = func(name string) (string, error) {if name == "claude" || name == "codex" {return "/bin/" + name, nil@@ -55,11 +55,16 @@ func newResumeFixture(t *testing.T) *resumeFixture {f.launched = append(f.launched, plan)return f.exitCode, nil}+ handoffLaunchDetached = func(plan handoff.Plan, _ handoff.DetachedOptions) (handoff.DetachedResult, error) {+ f.launched = append(f.launched, plan)+ return handoff.DetachedResult{Status: "launched", Mode: handoff.LaunchModeNewTerminal, Launcher: "Test Terminal"}, nil+ }handoffIsTerminal = func() bool { return true }handoffStdin = strings.NewReader("\n")handoffExit = func(code int) { f.exitCalled = code }+ handoffExecutable = func() (string, error) { return "/bin/beacon", nil }t.Cleanup(func() {- handoffLookPath, handoffLaunch, handoffIsTerminal, handoffStdin, handoffExit = prevLook, prevLaunch, prevTerm, prevStdin, prevExit+ handoffLookPath, handoffLaunch, handoffLaunchDetached, handoffIsTerminal, handoffStdin, handoffExit, handoffExecutable = prevLook, prevLaunch, prevDetached, prevTerm, prevStdin, prevExit, prevExecutable})return f}@@ -70,6 +75,18 @@ func runResume(t *testing.T, f *resumeFixture, args ...string) (string, string,return runHandoff(t, append([]string{"resume", "--output-dir", f.briefDir}, args...)...)}+func TestHandoffResumeCommandRegistered(t *testing.T) {+ cmd, _, err := rootCmd.Find([]string{"handoff", "resume"})+ if err != nil || cmd == nil || cmd.Name() != "resume" {+ t.Fatalf("handoff resume not registered: %v", err)+ }+ for _, flag := range []string{"agent", "new", "cwd", "launch", "print", "yes", "json", "output-dir", "log-path", "harness", "claude-projects-dir", "codex-dir", "opencode-dir", "cline-dir"} {+ if cmd.Flags().Lookup(flag) == nil {+ t.Fatalf("handoff resume missing --%s", flag)+ }+ }+}+func TestHandoffResumeReopensNativelyAfterConfirmation(t *testing.T) {f := newResumeFixture(t)_, stderr, err := runResume(t, f, "claude-1")@@ -203,6 +220,55 @@ func TestHandoffResumeRefusesToLaunchWithoutATerminal(t *testing.T) {}}+func TestHandoffResumeLaunchesInANewTerminalFromANonTTY(t *testing.T) {+ f := newResumeFixture(t)+ handoffIsTerminal = func() bool { return false }+ var options handoff.DetachedOptions+ handoffLaunchDetached = func(plan handoff.Plan, opts handoff.DetachedOptions) (handoff.DetachedResult, error) {+ f.launched = append(f.launched, plan)+ options = opts+ return handoff.DetachedResult{Status: "launched", Mode: handoff.LaunchModeNewTerminal, Launcher: "Terminal.app"}, nil+ }+ out, _, err := runResume(t, f, "claude-1", "--launch", "auto", "--yes")+ if err != nil {+ t.Fatalf("resume: %v", err)+ }+ if len(f.launched) != 1 || options.Mode != handoff.LaunchModeAuto || options.BeaconExecutable != "/bin/beacon" || options.SpecDir != f.briefDir {+ t.Fatalf("launch = %+v, options = %+v", f.launched, options)+ }+ if !strings.Contains(out, "Launched Claude Code with Terminal.app.") {+ t.Fatalf("stdout = %q", out)+ }+}++func TestHandoffResumeTmuxPrintsAttachCommand(t *testing.T) {+ f := newResumeFixture(t)+ handoffLaunchDetached = func(plan handoff.Plan, opts handoff.DetachedOptions) (handoff.DetachedResult, error) {+ f.launched = append(f.launched, plan)+ return handoff.DetachedResult{+ Status: "launched",+ Mode: handoff.LaunchModeTmux,+ Launcher: "tmux",+ SessionName: "beacon-handoff-abcd1234",+ AttachCommand: "tmux attach -t beacon-handoff-abcd1234",+ }, nil+ }+ out, _, err := runResume(t, f, "claude-1", "--launch", "tmux", "--yes")+ if err != nil {+ t.Fatalf("resume: %v", err)+ }+ if !strings.Contains(out, "Attach with: tmux attach -t beacon-handoff-abcd1234") {+ t.Fatalf("stdout = %q", out)+ }+}++func TestHandoffResumeRejectsInvalidLaunchMode(t *testing.T) {+ f := newResumeFixture(t)+ if _, _, err := runResume(t, f, "claude-1", "--launch", "background"); err == nil || !strings.Contains(err.Error(), "--launch") {+ t.Fatalf("err = %v", err)+ }+}+func TestHandoffResumePassesTheRuntimeExitCodeThrough(t *testing.T) {f := newResumeFixture(t)f.exitCode = 3diff --git a/cli/beacon/internal/handoff/detached.go b/cli/beacon/internal/handoff/detached.gonew file mode 100644index 00000000..2a8fe93f--- /dev/null+++ b/cli/beacon/internal/handoff/detached.go@@ -0,0 +1,576 @@+package handoff++import (+ "crypto/rand"+ "encoding/base64"+ "encoding/hex"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+ "time"+ "unicode/utf16"+)++const (+ LaunchModeCurrent = "current"+ LaunchModeAuto = "auto"+ LaunchModeNewTerminal = "new-terminal"+ LaunchModeTmux = "tmux"++ launchSpecVersion = 1+)++// DetachedOptions controls how LaunchDetached opens the terminal surface. The exported hooks keep+// every platform path testable from any OS; callers normally set only Mode, BeaconExecutable and+// SpecDir.+type DetachedOptions struct {+ Mode string+ BeaconExecutable string+ SpecDir string+ GOOS string+ Getenv func(string) string+ LookPath func(string) (string, error)+ Start func(*exec.Cmd) error+ Now func() time.Time+ Sleep func(time.Duration)+ StartupTimeout time.Duration+}++// DetachedResult describes the terminal surface that accepted a handoff.+type DetachedResult struct {+ Status string `json:"status"`+ Mode string `json:"launch"`+ Launcher string `json:"launcher"`+ SessionName string `json:"session_name,omitempty"`+ AttachCommand string `json:"attach_command,omitempty"`+}++type launchSpec struct {+ Version int `json:"version"`+ Plan Plan `json:"plan"`+ StatusPath string `json:"status_path"`+ CleanupPaths []string `json:"cleanup_paths,omitempty"`+ ExpiresAt time.Time `json:"expires_at"`+}++type launchStatus struct {+ State string `json:"state"`+ Error string `json:"error,omitempty"`+}++type detachedFiles struct {+ id string+ specPath string+ statusPath string+ scriptPath string+}++type launcherCommand struct {+ mode string+ name string+ executable string+ args []string+ sessionName string+ attachCommand string+ needsScript bool+}++// ValidateLaunchMode validates the public --launch values.+func ValidateLaunchMode(mode string) error {+ switch mode {+ case "", LaunchModeCurrent, LaunchModeAuto, LaunchModeNewTerminal, LaunchModeTmux:+ return nil+ default:+ return fmt.Errorf("launch mode must be %q, %q, %q or %q", LaunchModeCurrent, LaunchModeAuto, LaunchModeNewTerminal, LaunchModeTmux)+ }+}++// LaunchDetached writes a private one-time launch specification, opens a new terminal surface and+// waits until the Beacon trampoline confirms that the target runtime process started.+func LaunchDetached(plan Plan, opts DetachedOptions) (DetachedResult, error) {+ opts = normalizeDetachedOptions(opts)+ if err := ValidateLaunchMode(opts.Mode); err != nil {+ return DetachedResult{}, err+ }+ if opts.Mode == "" || opts.Mode == LaunchModeCurrent {+ return DetachedResult{}, errors.New("detached launch needs auto, new-terminal or tmux")+ }+ if !filepath.IsAbs(opts.BeaconExecutable) {+ return DetachedResult{}, fmt.Errorf("beacon executable must be absolute: %s", opts.BeaconExecutable)+ }+ if !filepath.IsAbs(opts.SpecDir) {+ return DetachedResult{}, fmt.Errorf("handoff launch directory must be absolute: %s", opts.SpecDir)+ }++ files, err := newDetachedFiles(opts.SpecDir)+ if err != nil {+ return DetachedResult{}, err+ }+ command, err := resolveLauncher(plan, files, opts)+ if err != nil {+ return DetachedResult{}, err+ }+ spec := launchSpec{+ Version: launchSpecVersion,+ Plan: plan,+ StatusPath: files.statusPath,+ ExpiresAt: opts.Now().Add(5 * time.Minute).UTC(),+ }+ if command.needsScript {+ spec.CleanupPaths = append(spec.CleanupPaths, files.scriptPath)+ }+ if err := writeLaunchSpec(files.specPath, spec); err != nil {+ return DetachedResult{}, err+ }+ cleanup := func() {+ _ = os.Remove(files.specPath)+ _ = os.Remove(files.statusPath)+ _ = os.Remove(files.scriptPath)+ }+ if command.needsScript {+ if err := writePOSIXLauncher(files.scriptPath, opts.BeaconExecutable, files.specPath); err != nil {+ cleanup()+ return DetachedResult{}, err+ }+ }++ cmd := exec.Command(command.executable, command.args...)+ if err := opts.Start(cmd); err != nil {+ cleanup()+ return DetachedResult{}, fmt.Errorf("open %s: %w", command.name, err)+ }+ status, err := waitLaunchStatus(files.statusPath, opts)+ if err != nil {+ return DetachedResult{}, fmt.Errorf("%s opened but the target runtime did not confirm startup: %w (launch spec: %s)", command.name, err, files.specPath)+ }+ _ = os.Remove(files.statusPath)+ if status.State != "started" {+ return DetachedResult{}, fmt.Errorf("%s could not start the target runtime: %s", command.name, status.Error)+ }+ return DetachedResult{+ Status: "launched",+ Mode: command.mode,+ Launcher: command.name,+ SessionName: command.sessionName,+ AttachCommand: command.attachCommand,+ }, nil+}++func normalizeDetachedOptions(opts DetachedOptions) DetachedOptions {+ if opts.GOOS == "" {+ opts.GOOS = runtime.GOOS+ }+ if opts.Getenv == nil {+ opts.Getenv = os.Getenv+ }+ if opts.LookPath == nil {+ opts.LookPath = exec.LookPath+ }+ if opts.Start == nil {+ opts.Start = func(cmd *exec.Cmd) error { return cmd.Start() }+ }+ if opts.Now == nil {+ opts.Now = time.Now+ }+ if opts.Sleep == nil {+ opts.Sleep = time.Sleep+ }+ if opts.StartupTimeout <= 0 {+ opts.StartupTimeout = 15 * time.Second+ }+ return opts+}++func newDetachedFiles(dir string) (detachedFiles, error) {+ if err := os.MkdirAll(dir, 0o700); err != nil {+ return detachedFiles{}, fmt.Errorf("create handoff directory: %w", err)+ }+ if err := os.Chmod(dir, 0o700); err != nil {+ return detachedFiles{}, fmt.Errorf("restrict handoff directory: %w", err)+ }+ var random [12]byte+ if _, err := rand.Read(random[:]); err != nil {+ return detachedFiles{}, fmt.Errorf("generate handoff launch id: %w", err)+ }+ id := hex.EncodeToString(random[:])+ base := filepath.Join(dir, "launch-"+id)+ return detachedFiles{+ id: id,+ specPath: base + ".json",+ statusPath: base + ".status.json",+ scriptPath: base + ".command",+ }, nil+}++func writeLaunchSpec(path string, spec launchSpec) error {+ data, err := json.Marshal(spec)+ if err != nil {+ return fmt.Errorf("encode handoff launch spec: %w", err)+ }+ data = append(data, '\n')+ file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)+ if err != nil {+ return fmt.Errorf("create handoff launch spec: %w", err)+ }+ if _, err := file.Write(data); err != nil {+ file.Close()+ _ = os.Remove(path)+ return fmt.Errorf("write handoff launch spec: %w", err)+ }+ if err := file.Close(); err != nil {+ _ = os.Remove(path)+ return fmt.Errorf("write handoff launch spec: %w", err)+ }+ return nil+}++func writePOSIXLauncher(path, beaconExecutable, specPath string) error {+ content := "#!/bin/sh\nexec " + quotePOSIX(beaconExecutable) + " handoff _launch --spec " + quotePOSIX(specPath) + "\n"+ file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o700)+ if err != nil {+ return fmt.Errorf("create handoff terminal launcher: %w", err)+ }+ if _, err := io.WriteString(file, content); err != nil {+ file.Close()+ _ = os.Remove(path)+ return fmt.Errorf("write handoff terminal launcher: %w", err)+ }+ if err := file.Close(); err != nil {+ _ = os.Remove(path)+ return fmt.Errorf("write handoff terminal launcher: %w", err)+ }+ return nil+}++func quotePOSIX(value string) string {+ return "'" + strings.ReplaceAll(value, "'", "'\"'\"'") + "'"+}++func resolveLauncher(plan Plan, files detachedFiles, opts DetachedOptions) (launcherCommand, error) {+ mode := opts.Mode+ if mode == LaunchModeAuto {+ mode = automaticLaunchMode(opts)+ }+ switch mode {+ case LaunchModeTmux:+ return tmuxLauncher(plan, files, opts)+ case LaunchModeNewTerminal:+ return terminalLauncher(plan, files, opts)+ default:+ return launcherCommand{}, fmt.Errorf("cannot resolve launch mode %q", mode)+ }+}++func automaticLaunchMode(opts DetachedOptions) string {+ if opts.GOOS == "linux" {+ if isHeadlessLinux(opts) {+ return LaunchModeTmux+ }+ if _, _, ok := findLinuxTerminal(opts); ok {+ return LaunchModeNewTerminal+ }+ return LaunchModeTmux+ }+ return LaunchModeNewTerminal+}++func isHeadlessLinux(opts DetachedOptions) bool {+ display := opts.Getenv("DISPLAY")+ if opts.Getenv("SSH_CONNECTION") != "" || opts.Getenv("SSH_TTY") != "" {+ host, _, ok := strings.Cut(display, ":")+ return !ok || host == "" || host == "unix" || strings.HasPrefix(host, "/")+ }+ return display == "" && opts.Getenv("WAYLAND_DISPLAY") == ""+}++func terminalLauncher(plan Plan, files detachedFiles, opts DetachedOptions) (launcherCommand, error) {+ runnerArgs := []string{"handoff", "_launch", "--spec", files.specPath}+ switch opts.GOOS {+ case "darwin":+ if cmux, ok := cmuxLauncher(files, opts); ok {+ return cmux, nil+ }+ open, err := opts.LookPath("open")+ if err != nil {+ return launcherCommand{}, errors.New("open Terminal.app: open was not found")+ }+ return launcherCommand{+ mode: LaunchModeNewTerminal,+ name: "Terminal.app",+ executable: open,+ args: []string{"-n", "-a", "Terminal.app", files.scriptPath},+ needsScript: true,+ }, nil+ case "windows":+ if wt, err := opts.LookPath("wt.exe"); err == nil {+ args := []string{"-w", "new", "new-tab", "--startingDirectory", plan.Dir, opts.BeaconExecutable}+ args = append(args, runnerArgs...)+ return launcherCommand{mode: LaunchModeNewTerminal, name: "Windows Terminal", executable: wt, args: args}, nil+ }+ for _, name := range []string{"powershell.exe", "pwsh.exe", "pwsh"} {+ if powershell, err := opts.LookPath(name); err == nil {+ script := powershellStartProcess(opts.BeaconExecutable, runnerArgs, plan.Dir)+ return launcherCommand{+ mode: LaunchModeNewTerminal,+ name: "PowerShell",+ executable: powershell,+ args: []string{"-NoProfile", "-NonInteractive", "-EncodedCommand", encodePowerShell(script)},+ }, nil+ }+ }+ return launcherCommand{}, errors.New("open a new Windows terminal: neither wt.exe nor PowerShell was found")+ case "linux":+ if isHeadlessLinux(opts) {+ return launcherCommand{}, errors.New("open a new Linux terminal: no local graphical display is available; use --launch tmux")+ }+ path, kind, ok := findLinuxTerminal(opts)+ if !ok {+ return launcherCommand{}, errors.New("open a new Linux terminal: no supported terminal emulator was found; set TERMINAL or use --launch tmux")+ }+ args, err := linuxTerminalArgs(kind, plan.Dir, opts.BeaconExecutable, runnerArgs)+ if err != nil {+ return launcherCommand{}, err+ }+ return launcherCommand{mode: LaunchModeNewTerminal, name: kind, executable: path, args: args}, nil+ default:+ return launcherCommand{}, fmt.Errorf("open a new terminal: unsupported platform %s", opts.GOOS)+ }+}++func cmuxLauncher(files detachedFiles, opts DetachedOptions) (launcherCommand, bool) {+ socketPath := strings.TrimSpace(opts.Getenv("CMUX_SOCKET_PATH"))+ if socketPath == "" {+ return launcherCommand{}, false+ }+ var executable string+ if configured := strings.TrimSpace(opts.Getenv("CMUX_BUNDLED_CLI_PATH")); configured != "" {+ executable, _ = opts.LookPath(configured)+ }+ if executable == "" {+ executable, _ = opts.LookPath("cmux")+ }+ if executable == "" {+ return launcherCommand{}, false+ }+ args := []string{"--socket", socketPath, "new-surface", "--type", "terminal", "--command", quotePOSIX(files.scriptPath), "--focus", "true"}+ if workspace := strings.TrimSpace(opts.Getenv("CMUX_WORKSPACE_ID")); workspace != "" {+ args = append(args, "--workspace", workspace)+ }+ return launcherCommand{+ mode: LaunchModeNewTerminal,+ name: "cmux",+ executable: executable,+ args: args,+ needsScript: true,+ }, true+}++func tmuxLauncher(plan Plan, files detachedFiles, opts DetachedOptions) (launcherCommand, error) {+ if opts.GOOS == "windows" {+ return launcherCommand{}, errors.New("tmux launch is not supported on Windows; use --launch new-terminal")+ }+ tmux, err := opts.LookPath("tmux")+ if err != nil {+ return launcherCommand{}, errors.New("launch with tmux: tmux was not found on PATH")+ }+ name := "beacon-handoff-" + files.id[:8]+ return launcherCommand{+ mode: LaunchModeTmux,+ name: "tmux",+ executable: tmux,+ args: []string{"new-session", "-d", "-s", name, "-c", plan.Dir, quotePOSIX(files.scriptPath)},+ sessionName: name,+ attachCommand: "tmux attach -t " + name,+ needsScript: true,+ }, nil+}++func findLinuxTerminal(opts DetachedOptions) (string, string, bool) {+ if configured := strings.TrimSpace(opts.Getenv("TERMINAL")); configured != "" && !strings.ContainsAny(configured, " \t\r\n") {+ if path, err := opts.LookPath(configured); err == nil {+ return path, filepath.Base(configured), true+ }+ }+ for _, candidate := range []string{"xdg-terminal-exec", "gnome-terminal", "konsole", "kitty", "wezterm", "alacritty", "foot", "x-terminal-emulator", "xterm"} {+ if path, err := opts.LookPath(candidate); err == nil {+ return path, candidate, true+ }+ }+ return "", "", false+}++func linuxTerminalArgs(kind, dir, beaconExecutable string, runnerArgs []string) ([]string, error) {+ command := append([]string{beaconExecutable}, runnerArgs...)+ switch filepath.Base(kind) {+ case "xdg-terminal-exec":+ return append([]string{"--dir=" + dir, "--"}, command...), nil+ case "gnome-terminal":+ return append([]string{"--working-directory=" + dir, "--"}, command...), nil+ case "konsole":+ return append([]string{"--workdir", dir, "-e"}, command...), nil+ case "kitty":+ return append([]string{"--directory", dir}, command...), nil+ case "wezterm":+ return append([]string{"start", "--cwd", dir, "--"}, command...), nil+ case "alacritty":+ return append([]string{"--working-directory", dir, "-e"}, command...), nil+ case "foot":+ return append([]string{"--cwd=" + dir}, command...), nil+ case "x-terminal-emulator", "xterm":+ return append([]string{"-e"}, command...), nil+ default:+ // $TERMINAL is commonly a terminal emulator with the conventional -e contract.+ return append([]string{"-e"}, command...), nil+ }+}++func powershellStartProcess(executable string, args []string, dir string) string {+ encodedExe := base64.StdEncoding.EncodeToString([]byte(executable))+ encodedDir := base64.StdEncoding.EncodeToString([]byte(dir))+ argLine := windowsCommandLine(args)+ encodedArgs := base64.StdEncoding.EncodeToString([]byte(argLine))+ return "$d={param($s)[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($s))};" ++ "Start-Process -FilePath (&$d '" + encodedExe + "') -ArgumentList (&$d '" + encodedArgs ++ "') -WorkingDirectory (&$d '" + encodedDir + "')"+}++func encodePowerShell(script string) string {+ encoded := utf16.Encode([]rune(script))+ data := make([]byte, 0, len(encoded)*2)+ for _, value := range encoded {+ data = append(data, byte(value), byte(value>>8))+ }+ return base64.StdEncoding.EncodeToString(data)+}++func windowsCommandLine(args []string) string {+ quoted := make([]string, 0, len(args))+ for _, arg := range args {+ quoted = append(quoted, quoteWindowsArg(arg))+ }+ return strings.Join(quoted, " ")+}++func quoteWindowsArg(arg string) string {+ if arg != "" && !strings.ContainsAny(arg, " \t\n\v\"") {+ return arg+ }+ var out strings.Builder+ out.WriteByte('"')+ slashes := 0+ for _, r := range arg {+ if r == '\\' {+ slashes+++ continue+ }+ if r == '"' {+ out.WriteString(strings.Repeat("\\", slashes*2+1))+ out.WriteRune(r)+ slashes = 0+ continue+ }+ out.WriteString(strings.Repeat("\\", slashes))+ slashes = 0+ out.WriteRune(r)+ }+ out.WriteString(strings.Repeat("\\", slashes*2))+ out.WriteByte('"')+ return out.String()+}++func waitLaunchStatus(path string, opts DetachedOptions) (launchStatus, error) {+ deadline := opts.Now().Add(opts.StartupTimeout)+ for opts.Now().Before(deadline) {+ data, err := os.ReadFile(path)+ if err == nil {+ var status launchStatus+ if err := json.Unmarshal(data, &status); err != nil {+ return launchStatus{}, fmt.Errorf("decode launch status: %w", err)+ }+ return status, nil+ }+ if !os.IsNotExist(err) {+ return launchStatus{}, fmt.Errorf("read launch status: %w", err)+ }+ opts.Sleep(50 * time.Millisecond)+ }+ return launchStatus{}, errors.New("timed out waiting for startup confirmation")+}++// RunLaunchSpec consumes a one-time launch specification and runs its target in the new terminal.+func RunLaunchSpec(path string, stdin io.Reader, stdout, stderr io.Writer) (int, error) {+ spec, err := readLaunchSpec(path)+ if err != nil {+ return -1, err+ }+ _ = os.Remove(path)+ for _, cleanup := range spec.CleanupPaths {+ _ = os.Remove(cleanup)+ }+ started := func() error {+ return writeLaunchStatus(spec.StatusPath, launchStatus{State: "started"})+ }+ code, err := LaunchWithStarted(spec.Plan, stdin, stdout, stderr, started)+ if err != nil {+ _ = writeLaunchStatus(spec.StatusPath, launchStatus{State: "error", Error: err.Error()})+ }+ return code, err+}++func readLaunchSpec(path string) (launchSpec, error) {+ if !filepath.IsAbs(path) {+ return launchSpec{}, errors.New("handoff launch spec path must be absolute")+ }+ info, err := os.Lstat(path)+ if err != nil {+ return launchSpec{}, fmt.Errorf("open handoff launch spec: %w", err)+ }+ if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() {+ return launchSpec{}, errors.New("handoff launch spec must be a regular file")+ }+ data, err := os.ReadFile(path)+ if err != nil {+ return launchSpec{}, fmt.Errorf("read handoff launch spec: %w", err)+ }+ var spec launchSpec+ if err := json.Unmarshal(data, &spec); err != nil {+ return launchSpec{}, fmt.Errorf("decode handoff launch spec: %w", err)+ }+ if spec.Version != launchSpecVersion {+ return launchSpec{}, fmt.Errorf("unsupported handoff launch spec version %d", spec.Version)+ }+ if time.Now().After(spec.ExpiresAt) {+ return launchSpec{}, errors.New("handoff launch spec has expired")+ }+ if !filepath.IsAbs(spec.Plan.Executable) || !filepath.IsAbs(spec.Plan.Dir) || !filepath.IsAbs(spec.StatusPath) {+ return launchSpec{}, errors.New("handoff launch spec paths must be absolute")+ }+ specDir := filepath.Clean(filepath.Dir(path))+ if filepath.Clean(filepath.Dir(spec.StatusPath)) != specDir {+ return launchSpec{}, errors.New("handoff launch status must stay in the spec directory")+ }+ for _, cleanup := range spec.CleanupPaths {+ if filepath.Clean(filepath.Dir(cleanup)) != specDir {+ return launchSpec{}, errors.New("handoff launch cleanup path must stay in the spec directory")+ }+ }+ return spec, nil+}++func writeLaunchStatus(path string, status launchStatus) error {+ data, err := json.Marshal(status)+ if err != nil {+ return err+ }+ data = append(data, '\n')+ if err := os.WriteFile(path, data, 0o600); err != nil {+ return fmt.Errorf("write handoff launch status: %w", err)+ }+ return os.Chmod(path, 0o600)+}diff --git a/cli/beacon/internal/handoff/detached_test.go b/cli/beacon/internal/handoff/detached_test.gonew file mode 100644index 00000000..79a09866--- /dev/null+++ b/cli/beacon/internal/handoff/detached_test.go@@ -0,0 +1,427 @@+package handoff++import (+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "reflect"+ "strings"+ "testing"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"+)++func detachedTestOptions(goos string, available ...string) DetachedOptions {+ return DetachedOptions{+ Mode: LaunchModeNewTerminal,+ GOOS: goos,+ Getenv: func(string) string { return "" },+ LookPath: func(name string) (string, error) {+ for _, candidate := range available {+ if name == candidate {+ return "/bin/" + name, nil+ }+ }+ return "", exec.ErrNotFound+ },+ }+}++func TestResolveTerminalLauncherAcrossPlatforms(t *testing.T) {+ files := detachedFiles{+ id: "0123456789abcdef01234567",+ specPath: "/private/handoffs/launch.json",+ statusPath: "/private/handoffs/status.json",+ scriptPath: "/private/handoffs/launch.command",+ }+ plan := Plan{Dir: "/work/project"}+ for _, tc := range []struct {+ name string+ opts DetachedOptions+ launcher string+ executable string+ contains []string+ script bool+ }{+ {+ name: "macOS Terminal",+ opts: detachedTestOptions("darwin", "open"),+ launcher: "Terminal.app",+ executable: "/bin/open",+ contains: []string{"-a", "Terminal.app", files.scriptPath},+ script: true,+ },+ {+ name: "Windows Terminal",+ opts: detachedTestOptions("windows", "wt.exe"),+ launcher: "Windows Terminal",+ executable: "/bin/wt.exe",+ contains: []string{"--startingDirectory", plan.Dir, "handoff", "_launch", files.specPath},+ },+ {+ name: "GNOME Terminal",+ opts: detachedTestOptions("linux", "gnome-terminal"),+ launcher: "gnome-terminal",+ executable: "/bin/gnome-terminal",+ contains: []string{"--working-directory=" + plan.Dir, "--", "handoff", "_launch", files.specPath},+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ opts := normalizeDetachedOptions(tc.opts)+ if tc.opts.GOOS == "linux" {+ opts.Getenv = func(name string) string {+ if name == "DISPLAY" {+ return ":0"+ }+ return ""+ }+ }+ command, err := terminalLauncher(plan, files, opts)+ if err != nil {+ t.Fatal(err)+ }+ if command.name != tc.launcher || command.executable != tc.executable || command.needsScript != tc.script {+ t.Fatalf("launcher = %+v", command)+ }+ joined := strings.Join(command.args, "\x00")+ for _, want := range tc.contains {+ if !strings.Contains(joined, want) {+ t.Fatalf("args %q missing %q", command.args, want)+ }+ }+ })+ }+}++func TestAutomaticLaunchModeUsesTmuxHeadlessAndTerminalOnDesktop(t *testing.T) {+ opts := normalizeDetachedOptions(detachedTestOptions("linux", "gnome-terminal", "tmux"))+ opts.Mode = LaunchModeAuto+ opts.Getenv = func(string) string { return "" }+ if got := automaticLaunchMode(opts); got != LaunchModeTmux {+ t.Fatalf("headless auto mode = %q", got)+ }+ opts.Getenv = func(name string) string {+ if name == "DISPLAY" {+ return ":0"+ }+ return ""+ }+ if got := automaticLaunchMode(opts); got != LaunchModeNewTerminal {+ t.Fatalf("desktop auto mode = %q", got)+ }+ opts.Getenv = func(name string) string {+ switch name {+ case "DISPLAY":+ return "localhost:10.0"+ case "SSH_CONNECTION":+ return "client server"+ default:+ return ""+ }+ }+ if got := automaticLaunchMode(opts); got != LaunchModeNewTerminal {+ t.Fatalf("forwarded X11 auto mode = %q", got)+ }+}++func TestCmuxLauncherUsesTheCallingWorkspace(t *testing.T) {+ const cmuxPath = "/Applications/cmux.app/Contents/Resources/bin/cmux"+ opts := normalizeDetachedOptions(DetachedOptions{+ Mode: LaunchModeNewTerminal,+ GOOS: "darwin",+ Getenv: func(name string) string {+ switch name {+ case "CMUX_SOCKET_PATH":+ return "/Users/me/.local/state/cmux/cmux.sock"+ case "CMUX_WORKSPACE_ID":+ return "workspace-id"+ case "CMUX_BUNDLED_CLI_PATH":+ return cmuxPath+ default:+ return ""+ }+ },+ LookPath: func(name string) (string, error) {+ if name == cmuxPath {+ return cmuxPath, nil+ }+ return "", exec.ErrNotFound+ },+ })+ files := detachedFiles{scriptPath: "/Users/me/Library/Application Support/Beacon/launch.command"}+ command, err := terminalLauncher(Plan{Dir: "/work"}, files, opts)+ if err != nil {+ t.Fatal(err)+ }+ if command.name != "cmux" || command.executable != cmuxPath || !command.needsScript {+ t.Fatalf("command = %+v", command)+ }+ want := []string{+ "--socket", "/Users/me/.local/state/cmux/cmux.sock",+ "new-surface", "--type", "terminal",+ "--command", "'/Users/me/Library/Application Support/Beacon/launch.command'",+ "--focus", "true",+ "--workspace", "workspace-id",+ }+ if !reflect.DeepEqual(command.args, want) {+ t.Fatalf("args = %q, want %q", command.args, want)+ }+}++func TestMacOSLauncherFallsBackToTerminalOutsideCmux(t *testing.T) {+ opts := normalizeDetachedOptions(detachedTestOptions("darwin", "open"))+ opts.Getenv = func(name string) string {+ if name == "CMUX_SOCKET_PATH" {+ return "/Users/me/.local/state/cmux/cmux.sock"+ }+ return ""+ }+ command, err := terminalLauncher(Plan{}, detachedFiles{scriptPath: "/tmp/launch.command"}, opts)+ if err != nil {+ t.Fatal(err)+ }+ if command.name != "Terminal.app" {+ t.Fatalf("launcher = %q", command.name)+ }+}++func TestLaunchDetachedWaitsForTheTargetStartupStatus(t *testing.T) {+ dir := t.TempDir()+ now := time.Date(2026, 9, 26, 12, 0, 0, 0, time.UTC)+ var started *exec.Cmd+ result, err := LaunchDetached(Plan{+ Executable: "/bin/codex",+ Args: []string{"resume", "session-1"},+ Dir: dir,+ }, DetachedOptions{+ Mode: LaunchModeNewTerminal,+ BeaconExecutable: "/opt/beacon/bin/beacon",+ SpecDir: dir,+ GOOS: "linux",+ Getenv: func(name string) string {+ if name == "DISPLAY" {+ return ":0"+ }+ return ""+ },+ LookPath: func(name string) (string, error) {+ if name == "gnome-terminal" {+ return "/usr/bin/gnome-terminal", nil+ }+ return "", exec.ErrNotFound+ },+ Start: func(cmd *exec.Cmd) error {+ started = cmd+ specPath := cmd.Args[len(cmd.Args)-1]+ data, err := os.ReadFile(specPath)+ if err != nil {+ return err+ }+ var spec launchSpec+ if err := json.Unmarshal(data, &spec); err != nil {+ return err+ }+ return writeLaunchStatus(spec.StatusPath, launchStatus{State: "started"})+ },+ Now: func() time.Time { return now },+ Sleep: func(time.Duration) {},+ StartupTimeout: time.Second,+ })+ if err != nil {+ t.Fatalf("LaunchDetached: %v", err)+ }+ if result.Status != "launched" || result.Mode != LaunchModeNewTerminal || result.Launcher != "gnome-terminal" {+ t.Fatalf("result = %+v", result)+ }+ if started == nil || started.Path != "/usr/bin/gnome-terminal" {+ t.Fatalf("started = %+v", started)+ }+}++func TestLaunchDetachedReportsAnUnconfirmedTerminal(t *testing.T) {+ dir := t.TempDir()+ now := time.Now()+ _, err := LaunchDetached(Plan{Executable: "/bin/codex", Dir: dir}, DetachedOptions{+ Mode: LaunchModeNewTerminal,+ BeaconExecutable: "/opt/beacon/bin/beacon",+ SpecDir: dir,+ GOOS: "darwin",+ LookPath: func(string) (string, error) { return "/usr/bin/open", nil },+ Start: func(*exec.Cmd) error { return nil },+ Now: func() time.Time {+ now = now.Add(time.Second)+ return now+ },+ Sleep: func(time.Duration) {},+ StartupTimeout: 2 * time.Second,+ })+ if err == nil || !strings.Contains(err.Error(), "did not confirm startup") || !strings.Contains(err.Error(), "launch spec:") {+ t.Fatalf("err = %v", err)+ }+}++func TestRunLaunchSpecStartsTheExactPlanAndConsumesPrivateFiles(t *testing.T) {+ testenv.RequirePOSIXExecutableFixtures(t)+ dir := t.TempDir()+ script := filepath.Join(dir, "agent")+ if err := os.WriteFile(script, []byte("#!/bin/sh\nprintf '%s|%s' \"$1\" \"$HANDOFF_MODE\"\n"), 0o700); err != nil {+ t.Fatal(err)+ }+ specPath := filepath.Join(dir, "launch.json")+ statusPath := filepath.Join(dir, "status.json")+ cleanupPath := filepath.Join(dir, "launch.command")+ if err := os.WriteFile(cleanupPath, []byte("temporary"), 0o700); err != nil {+ t.Fatal(err)+ }+ spec := launchSpec{+ Version: launchSpecVersion,+ Plan: Plan{+ Executable: script,+ Args: []string{"argument with spaces"},+ Dir: dir,+ Env: map[string]string{"HANDOFF_MODE": "safe"},+ },+ StatusPath: statusPath,+ CleanupPaths: []string{cleanupPath},+ ExpiresAt: time.Now().Add(time.Minute),+ }+ if err := writeLaunchSpec(specPath, spec); err != nil {+ t.Fatal(err)+ }+ var stdout strings.Builder+ code, err := RunLaunchSpec(specPath, nil, &stdout, &strings.Builder{})+ if err != nil || code != 0 {+ t.Fatalf("RunLaunchSpec = %d, %v", code, err)+ }+ if stdout.String() != "argument with spaces|safe" {+ t.Fatalf("stdout = %q", stdout.String())+ }+ for _, path := range []string{specPath, cleanupPath} {+ if _, err := os.Stat(path); !os.IsNotExist(err) {+ t.Fatalf("%s was not consumed: %v", path, err)+ }+ }+ var status launchStatus+ data, err := os.ReadFile(statusPath)+ if err != nil || json.Unmarshal(data, &status) != nil || status.State != "started" {+ t.Fatalf("status = %+v, %v, data=%s", status, err, data)+ }+}++func TestReadLaunchSpecRejectsEscapingStatusAndCleanupPaths(t *testing.T) {+ dir := t.TempDir()+ base := launchSpec{+ Version: launchSpecVersion,+ Plan: Plan{Executable: "/bin/codex", Dir: dir},+ StatusPath: filepath.Join(dir, "status.json"),+ ExpiresAt: time.Now().Add(time.Minute),+ }+ for i, edit := range []func(*launchSpec){+ func(spec *launchSpec) { spec.StatusPath = filepath.Join(t.TempDir(), "status.json") },+ func(spec *launchSpec) { spec.CleanupPaths = []string{filepath.Join(t.TempDir(), "script")} },+ } {+ spec := base+ edit(&spec)+ path := filepath.Join(dir, fmt.Sprintf("invalid-%d.json", i))+ if err := writeLaunchSpec(path, spec); err != nil {+ t.Fatal(err)+ }+ if _, err := readLaunchSpec(path); err == nil {+ t.Fatalf("readLaunchSpec accepted %+v", spec)+ }+ }+}++func TestLinuxTerminalArgumentsPreserveTheRunnerVector(t *testing.T) {+ command := []string{"/opt/beacon/bin/beacon", "handoff", "_launch", "--spec", "/home/me/a b/spec.json"}+ for _, kind := range []string{"xdg-terminal-exec", "gnome-terminal", "konsole", "kitty", "wezterm", "alacritty", "foot", "x-terminal-emulator", "xterm"} {+ args, err := linuxTerminalArgs(kind, "/work/a b", command[0], command[1:])+ if err != nil {+ t.Fatal(err)+ }+ if !containsSequence(args, command) {+ t.Fatalf("%s args = %q; command vector was not preserved", kind, args)+ }+ }+}++func containsSequence(values, sequence []string) bool {+ for i := 0; i+len(sequence) <= len(values); i++ {+ if reflect.DeepEqual(values[i:i+len(sequence)], sequence) {+ return true+ }+ }+ return false+}++func TestValidateLaunchMode(t *testing.T) {+ for _, mode := range []string{"", LaunchModeCurrent, LaunchModeAuto, LaunchModeNewTerminal, LaunchModeTmux} {+ if err := ValidateLaunchMode(mode); err != nil {+ t.Fatalf("%q: %v", mode, err)+ }+ }+ if err := ValidateLaunchMode("background"); err == nil {+ t.Fatal("invalid mode was accepted")+ }+}++func TestWindowsCommandLineQuotesArguments(t *testing.T) {+ got := windowsCommandLine([]string{"handoff", "_launch", "--spec", `C:\Users\A B\launch.json`, `ends\`})+ want := `handoff _launch --spec "C:\Users\A B\launch.json" ends\`+ if got != want {+ t.Fatalf("command line = %q, want %q", got, want)+ }+ if powershellStartProcess(`C:\Program Files\Beacon\beacon.exe`, []string{"handoff", "_launch", "--spec", `C:\A B\launch.json`}, `C:\Work`) == "" {+ t.Fatal("PowerShell fallback was empty")+ }+}++func TestTmuxLauncherNamesAResumableSession(t *testing.T) {+ opts := normalizeDetachedOptions(detachedTestOptions("linux", "tmux"))+ files := detachedFiles{id: "0123456789abcdef01234567", scriptPath: "/tmp/launch command"}+ command, err := tmuxLauncher(Plan{Dir: "/work"}, files, opts)+ if err != nil {+ t.Fatal(err)+ }+ if command.sessionName != "beacon-handoff-01234567" || command.attachCommand != "tmux attach -t beacon-handoff-01234567" {+ t.Fatalf("command = %+v", command)+ }+ if !reflect.DeepEqual(command.args, []string{"new-session", "-d", "-s", command.sessionName, "-c", "/work", "'/tmp/launch command'"}) {+ t.Fatalf("args = %q", command.args)+ }+}++func TestTerminalLauncherErrorsWithoutSupportedSurface(t *testing.T) {+ opts := normalizeDetachedOptions(detachedTestOptions("windows"))+ if _, err := terminalLauncher(Plan{Dir: `C:\work`}, detachedFiles{}, opts); err == nil {+ t.Fatal("Windows launcher succeeded without wt or PowerShell")+ }+ opts = normalizeDetachedOptions(detachedTestOptions("linux"))+ opts.Getenv = func(string) string { return "" }+ if _, err := terminalLauncher(Plan{Dir: "/work"}, detachedFiles{}, opts); err == nil || !strings.Contains(err.Error(), "tmux") {+ t.Fatalf("Linux headless error = %v", err)+ }+ opts = normalizeDetachedOptions(detachedTestOptions("plan9"))+ if _, err := terminalLauncher(Plan{}, detachedFiles{}, opts); err == nil {+ t.Fatal("unsupported OS was accepted")+ }+}++func TestLaunchDetachedReportsLauncherStartFailure(t *testing.T) {+ dir := t.TempDir()+ _, err := LaunchDetached(Plan{Executable: "/bin/codex", Dir: dir}, DetachedOptions{+ Mode: LaunchModeNewTerminal,+ BeaconExecutable: "/opt/beacon/bin/beacon",+ SpecDir: dir,+ GOOS: "darwin",+ LookPath: func(string) (string, error) { return "/usr/bin/open", nil },+ Start: func(*exec.Cmd) error { return errors.New("denied") },+ })+ if err == nil || !strings.Contains(err.Error(), "denied") {+ t.Fatalf("err = %v", err)+ }+}diff --git a/cli/beacon/internal/handoff/launch.go b/cli/beacon/internal/handoff/launch.goindex f6c0fc45..ad7380c0 100644--- a/cli/beacon/internal/handoff/launch.go+++ b/cli/beacon/internal/handoff/launch.go@@ -14,6 +14,17 @@ import (// code. The runtime owns the terminal while it runs: an interrupt reaches it through the terminal's// process group, so Beacon ignores the interrupt itself instead of exiting underneath it.func Launch(plan Plan, stdin io.Reader, stdout, stderr io.Writer) (int, error) {+ return launch(plan, stdin, stdout, stderr, nil)+}++// LaunchWithStarted runs the plan like Launch and calls started after the runtime process has+// started successfully. It is used by the detached-launch trampoline to tell the parent Beacon+// process that the new terminal is ready.+func LaunchWithStarted(plan Plan, stdin io.Reader, stdout, stderr io.Writer, started func() error) (int, error) {+ return launch(plan, stdin, stdout, stderr, started)+}++func launch(plan Plan, stdin io.Reader, stdout, stderr io.Writer, started func() error) (int, error) {cmd := exec.Command(plan.Executable, plan.Args...)cmd.Dir = plan.Dircmd.Stdin, cmd.Stdout, cmd.Stderr = stdin, stdout, stderr@@ -23,7 +34,17 @@ func Launch(plan Plan, stdin io.Reader, stdout, stderr io.Writer) (int, error) {signal.Notify(interrupts, os.Interrupt)defer signal.Stop(interrupts)- err := cmd.Run()+ if err := cmd.Start(); err != nil {+ return -1, err+ }+ if started != nil {+ if err := started(); err != nil {+ _ = cmd.Process.Kill()+ _ = cmd.Wait()+ return -1, err+ }+ }+ err := cmd.Wait()var exitErr *exec.ExitErrorif errors.As(err, &exitErr) {return exitErr.ExitCode(), nildiff --git a/docs/cli/handoff.mdx b/docs/cli/handoff.mdxindex 8d82b7c7..56b58c51 100644--- a/docs/cli/handoff.mdx+++ b/docs/cli/handoff.mdx@@ -122,10 +122,11 @@ Briefs are written to `~/.beacon/endpoint/handoffs`. The directory is `0700` andPicks a session up again, in its own runtime or another one.```bash-beacon handoff resume 7f3c2a91 # reopen it where it ran-beacon handoff resume 7f3c2a91 --agent codex # continue a Claude Code session in Codex-beacon handoff resume 7f3c2a91 --new # a fresh session in the same runtime, from a brief-beacon handoff resume 7f3c2a91 --print # show what would run; writes and launches nothing+beacon handoff resume 7f3c2a91 # reopen it where it ran+beacon handoff resume 7f3c2a91 --agent codex # continue a Claude Code session in Codex+beacon handoff resume 7f3c2a91 --new # a fresh session in the same runtime, from a brief+beacon handoff resume 7f3c2a91 --agent codex --launch auto --yes # detached handoff from an agent harness+beacon handoff resume 7f3c2a91 --print # show what would run; writes and launches nothing```There are two ways to resume:@@ -197,13 +198,40 @@ Hermes Agent asks before dangerous commands by default. Beacon never passes `--yGrok Build's configured permission mode can be always-approve. Beacon always passes `--permission-mode default`, the mode that asks before running tools, so a session Beacon starts or reopens never inherits always-approve from that config. You can still change the mode inside the Grok TUI. Grok looks a session id up under the directory it runs in, which is why the resume runs in the session's recorded directory. With `--cwd` naming another directory, a Grok session continues from a brief instead.-The runtime runs in this terminal, in the session's recorded directory. If that directory no longer exists, Beacon stops rather than starting somewhere else; pass `--cwd` to choose a directory. Beacon prints the plan and asks `Continue? [Y/n]` before launching. Without a terminal, it launches only with `--yes`. `beacon handoff resume` exits with the runtime's own exit code.+By default, the runtime runs in this terminal. `--launch auto` instead opens a new terminal surface+on a desktop and creates a detached tmux session on SSH or headless Linux. When Beacon runs inside+cmux on macOS, it opens another terminal in the calling workspace; otherwise it uses Terminal.app.+This is useful from an agent harness, whose command subprocess generally does not own a TTY that+another interactive runtime can use.++The launch modes are:++| Mode | Behavior |+|------|----------|+| `current` | Run in the calling terminal and wait for the runtime. This is the default. |+| `auto` | Use another terminal in the calling cmux workspace or Terminal.app on macOS, Windows Terminal or PowerShell on Windows, a supported Linux terminal emulator on a desktop, or tmux on headless Linux/SSH. |+| `new-terminal` | Require a graphical terminal and fail explicitly when none can be opened. |+| `tmux` | Create a detached `beacon-handoff-<id>` session and print its `tmux attach` command. |++Linux desktop detection supports `xdg-terminal-exec`, GNOME Terminal, Konsole, Kitty, WezTerm,+Alacritty, foot, `x-terminal-emulator`, xterm, and a simple executable named by `$TERMINAL`.++Detached launches use a private, expiring `0600` specification under+`~/.beacon/endpoint/handoffs`. The new terminal runs a hidden Beacon trampoline that consumes the+specification, starts the exact approval-safe argument vector, and confirms startup to the calling+process. Prompt or brief content is never interpolated into a terminal-launch shell command.++The runtime starts in the session's recorded directory. If that directory no longer exists, Beacon+stops rather than starting somewhere else; pass `--cwd` to choose a directory. Beacon prints the+plan and asks `Continue? [Y/n]` before launching. From a non-TTY tool, pass `--yes` with a detached+launch mode. A `current` launch exits with the runtime's own exit code.| Flag | Description ||------|-------------|| `--agent` | Runtime to continue in, by the names in the tables above. Defaults to the session's own runtime. || `--new` | Start a new session from a brief even when the session could be reopened. || `--cwd` | Directory to start the runtime in. |+| `--launch` | `current`, `auto`, `new-terminal`, or `tmux`. Defaults to `current`. || `--print` | Show the plan and command without writing a brief or launching anything. || `--json` | With `--print`, describe the plan as JSON (`mode`, `reason`, `target`, `executable`, `args`, `env`, `dir`, `brief_path`). || `--yes` | Launch without asking. |diff --git a/docs/concepts/session-handoff.mdx b/docs/concepts/session-handoff.mdxindex f32505a7..1163bb8f 100644--- a/docs/concepts/session-handoff.mdx+++ b/docs/concepts/session-handoff.mdx@@ -38,6 +38,18 @@ beacon handoff resume 7f3c2a91 --agent codex # continue it in another runtime3. **Continue it.** `beacon handoff resume` prints its plan, asks you to confirm, andlaunches the runtime in this terminal, in the session's recorded directory.+From inside another agent harness, use Beacon's CLI with detached launch. It uses the same planner+and runtime registry, but starts the destination in a separate terminal surface so it does not+depend on the source harness's non-TTY command subprocess:++```text+source harness -> Beacon CLI -> private launch spec -> new terminal or tmux -> destination runtime+```++The private launch specification contains Beacon's validated executable and argument vector. The+destination terminal consumes it once and confirms process startup before the command reports+success.+## Two ways to resume**Reopen natively.** Beacon reopens the session with its full context when you continue@@ -113,6 +125,10 @@ The marker is text in a prompt, not a verified identity, and anyone can type it.- **Confirmation before launch.** `resume` asks before it starts a runtime, and itlaunches without a terminal only with `--yes`. It stops if the session's directory nolonger exists, rather than starting somewhere else.+- **Detached launch is one-time and structured.** A new-terminal or tmux launch reads a private,+ expiring specification containing the executable and argument vector. Beacon does not construct+ a shell command from prompt content, and the source process waits for the destination runtime to+ confirm that it started.- **Approvals stay on.** Beacon never passes a flag that turns a runtime's approvals off.Where a CLI takes an approval mode, Beacon names the one that asks. For example, Clineis always started with `--auto-approve false`, because it approves every tool call by