pkg/cli/main.go

package cli

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"git.cafe/ezterry/ez-agent/internal/frontend"
	"git.cafe/ezterry/ez-agent/internal/hubfeature"
	"git.cafe/ezterry/ez-agent/pkg/buildinfo"
	"git.cafe/ezterry/ez-agent/pkg/ezagentapi"
	"git.cafe/ezterry/ez-agent/pkg/protocol"
	"git.cafe/ezterry/ez-agent/pkg/service"
	"golang.org/x/term"
)

func parseCSV(s string) []string {
	result := make([]string, 0)
	for _, part := range strings.Split(s, ",") {
		part = strings.TrimSpace(part)
		if part != "" {
			result = append(result, part)
		}
	}
	return result
}

// cliStderr is separate from RunWithWriter output so startup feedback never
// contaminates command output. Tests replace it with an in-memory writer.
var cliStderr io.Writer = os.Stderr

var hubEnabled = hubfeature.Enabled

const hubUsageText = `
  ez-agent --hub
  ez-agent --hub <target> [--cwd <dir>]

AgentHub remote mode:
  --hub               Choose a saved Hub without contacting the local daemon
  <target>             A saved Hub name, "last", or an explicit host:port
  --cwd <dir>          Supply exact remote CWD, overriding the endpoint default
                      Without --cwd, use the last CWD for the selected endpoint;
                      startup fails before EzAgent hello if neither is available
                      Use --cwd=<dir> for opaque values beginning with '-'

Local remote-bookmark controls, all exit without connecting:
  ez-agent --hub --bookmarks
  ez-agent --hub --select-bookmark <endpoint> --cwd <dir>
  ez-agent --hub --forget-bookmark <endpoint> --cwd <dir>
  <endpoint>          Exact 64-character lowercase endpoint fingerprint
  --bookmarks         List saved endpoint/CWD pairs with quoted CWD and leaf
  --select-bookmark   Set an existing pair as that endpoint's startup default
                      Then connect normally with --hub and choose the endpoint
  --forget-bookmark   Forget only this exact local pair, not pins, approvals,
                      or remote sessions. No automatic fallback CWD is selected.

The --hub marker must be the first argument. AgentHub mode does not accept
local CLI commands or autolaunch options.
`

const localUsageText = `
Local options:
  -p <text>           Send a prompt (creates a new session or continues via -s)
  -s, --leaf <id>     Leaf ID for prompt continuation or macros; -p cannot target EZ_AGENT_LEAF_ID or its ancestors
  --tools <csv>        Set and validate active tools. '' = no tools. Fresh sessions otherwise use CWD defaults.
  --plugins <csv>      Set and validate active plugins. '' = no plugins. Fresh sessions otherwise use CWD defaults.
  --list-sessions, --list-leaves  List all sessions (leaves) and exit
  --list-models        List all available models (provider/model) and exit
  --list-roots         List all roots and exit
  --delete-leaf <id>   Delete a leaf by ID and exit
  --vacuum             Prune orphaned roots (leafless roots with no sessions)
  --deep               With --vacuum: also prune old unreachable turn branches
  --older-than <dur>   With --vacuum: only prune roots orphaned longer than duration (e.g. 7d, 2h, 30m)
  --dry-run            With --vacuum: show what would be pruned without deleting
  --cwd <dir>          Set working directory for new sessions
  --no-parent          Do not group under or inherit the profile of EZ_AGENT_LEAF_ID
  --list-macros [type] List available macros and exit. Optional filter examples: on_preplugin, on_assistant, on_success, on_error, on_idle, on_user, completions, cache_cleanup
  --macro-info <name>  Show detailed info for a macro and exit
  --macro <name>       Call a macro by name and print result to stdout
  --param <text>       With --macro: param_string passed to the macro
  --show-config        Print effective merged config and exit
  --third-party-licenses  Print versions and complete third-party license notices, then exit
  --no-autolaunch      Do not start the daemon if it is not running; error instead
  --autolaunch         Start the daemon if it is not running (default)
  --model <ref>        Set and validate model; fresh children otherwise inherit it
  --thinking <level>   Set and validate thinking; fresh children inherit it when models match
  --mode <name>        Set and validate mode; fresh children otherwise inherit it
  --stop               Stop the daemon
  -h, --help           Show this help message

Interactive TUI connections:
  ez-agent            Open the default connection, or the picker when no default is selected
  --connections       Open the TUI connection manager
  --connection <id-or-name>  Open a saved connection
  --via <destination>  Open a temporary SSH connection with best-effort Auto socket discovery
  --socket <path>      Open a temporary custom socket; combine with --via to override its remote path
  --cwd <dir>          With no scripted action, open the TUI in this directory
  In the TUI, /connections manages connections; /cwd or clicking the sidebar CWD changes directory.
  Enable local, Start local automatically, and Open by default are independent TUI preferences.
  Only the built-in Local daemon can autostart. SSH passwords/passphrases are prompted and never saved.

Remote CLI for one-off prompts and scripts:
  --socket <path>      Connect to an absolute destination Unix socket; never start a local daemon
  --ssh <destination>  Forward --socket through SSH; requires --socket
  --via <destination>  Temporary SSH connection; discover the socket unless --socket overrides it
  --connection <id-or-name>  Use a saved TUI connection, without local fallback
  --cwd <dir>          Exact absolute remote CWD; defaults to the saved connection CWD
                      Required for fresh remote sessions, not for -s/--leaf continuation
  Auto socket discovery needs SSH exec and a remote login environment with XDG_RUNTIME_DIR.
  Discovery is best effort, with no guessed path or local fallback.
  --connection cannot be combined with --socket, --ssh, or --via. Remote --stop is not supported.
  Interactive users: open the TUI and use /connections to select or manage connections.

Examples:
  ez-agent -p "hello world"              Start a new session
  ez-agent --tools '' -p "hello"         Start a new session with no tools
  ez-agent --tools run-cmd,buffer -p "hi" Start a new session with only run-cmd and buffer
  ez-agent --plugins '' -p "hello"        Start a new session with no plugins
  ez-agent -s l_abc123 --tools '' -p "hi" Resume a session, strip all tools
  ez-agent --list-sessions               List all sessions
  ez-agent --list-models                 List all available models
  ez-agent --list-roots                  List all roots
  ez-agent --delete-leaf l_abc123        Delete a leaf
  ez-agent --vacuum                      Prune all orphaned roots
  ez-agent --vacuum --older-than 7d     Prune orphaned roots older than 7 days
  ez-agent --vacuum --deep --older-than 30d  Deep-prune unreachable branches older than 30 days
  ez-agent --vacuum --dry-run            Preview what would be pruned
  ez-agent -s l_abc123 -p "follow up"   Continue an existing session
  ez-agent --macro hello.hello --param World   Call a macro
  ez-agent --list-macros cache_cleanup   List cache-cleanup providers
  ez-agent --show-config                 Print effective merged config
  ez-agent --third-party-licenses        Print the embedded offline license report
  ez-agent -s l_abc123 --model ollama/qwen2.5 -p "hi"  Continue with a different model
  ez-agent --model chatgpt/gpt-5.6-terra --thinking low --mode plan -p "hello"
  ez-agent --stop                        Stop the daemon (no-op if not running)
  ez-agent --connection office -p "summarize the changes"
  ez-agent --via user@host --cwd /srv/project -p "summarize the changes"
  ez-agent --socket /run/user/1000/ez-agent.sock --cwd /srv/project -p "hello"
  ez-agent --ssh user@host --socket /run/user/1000/ez-agent.sock -s l_abc123 -p "continue"
`

const hubUsageExamples = `
  ez-agent --hub                         Choose a saved Hub for a remote TUI
  ez-agent --hub office --cwd /workspace/project
`

// WriteUsage includes AgentHub forms only in opted-in installations, without
// starting or connecting to a daemon.
func WriteUsage(out io.Writer) error {
	_, err := fmt.Fprint(out, usageText())
	return err
}

func usageText() string {
	enabled := hubEnabled()
	text := "Usage:\n  ez-agent [options]\n"
	if enabled {
		text = strings.TrimSuffix(text, "\n") + hubUsageText
	}
	text += localUsageText
	if enabled {
		text = strings.TrimSuffix(text, "\n") + hubUsageExamples
	}
	return text
}

func reasoningStylingEnabled(stdoutFD int, lookupEnv func(string) (string, bool), isTerminal func(int) bool) bool {
	if _, present := lookupEnv("NO_COLOR"); present {
		return false
	}
	if value, present := lookupEnv("TERM"); present && strings.EqualFold(strings.TrimSpace(value), "dumb") {
		return false
	}
	return isTerminal(stdoutFD)
}

func Run(args []string, autolaunch bool) error {
	return RunContext(context.Background(), args, autolaunch)
}

// RunContext is Run with cancellation for startup and connected operations.
func RunContext(ctx context.Context, args []string, autolaunch bool) error {
	return RunWithWriterContext(ctx, args, autolaunch, os.Stdout)
}

// RunWithWriter runs the CLI, directing output that does not involve the
// daemon (help and legal notices) to out.
func RunWithWriter(args []string, autolaunch bool, out io.Writer) error {
	return RunWithWriterContext(context.Background(), args, autolaunch, out)
}

// RunWithWriterContext is RunWithWriter with cancellation for the client lifetime.
// Startup progress is written to cliStderr, deliberately separate from out.
func RunWithWriterContext(ctx context.Context, args []string, autolaunch bool, out io.Writer) error {
	var promptText string
	var sessionID string
	var cwd string
	var cwdExplicit bool
	var socketPath, sshDestination, savedConnection, viaDestination string
	var stop bool
	var listSessions bool
	var listRoots bool
	var deleteLeaf string
	var vacuum bool
	var deep bool
	var olderThan string
	var dryRun bool
	var macroName string
	var macroParam string
	var listMacros bool
	var listMacrosFilter string
	var macroInfoName string
	var showConfig bool
	var listModels bool
	var modelRef string
	var modelExplicit bool
	var thinkingLevel string
	var thinkingExplicit bool
	var modeName string
	var modeExplicit bool
	var toolsCSV string
	var toolsExplicit bool
	var pluginsCSV string
	var pluginsExplicit bool
	var thirdPartyLicenses bool
	var noParent bool

	i := 0
	for i < len(args) {
		switch args[i] {
		case "-h", "--help":
			return WriteUsage(out)
		case "--third-party-licenses":
			thirdPartyLicenses = true
		case "-p":
			i++
			if i >= len(args) {
				return fmt.Errorf("-p requires an argument")
			}
			promptText = args[i]
		case "-s", "--leaf":
			i++
			if i >= len(args) {
				return fmt.Errorf("-s/--leaf requires an argument")
			}
			sessionID = args[i]
		case "--cwd":
			i++
			if i >= len(args) {
				return fmt.Errorf("--cwd requires an argument")
			}
			cwd = args[i]
			cwdExplicit = true
		case "--socket", "--ssh", "--connection", "--via":
			option := args[i]
			i++
			if i >= len(args) || args[i] == "" {
				return fmt.Errorf("%s requires an argument", option)
			}
			switch option {
			case "--socket":
				socketPath = args[i]
			case "--ssh":
				sshDestination = args[i]
			case "--connection":
				savedConnection = args[i]
			case "--via":
				viaDestination = args[i]
			}
		case "--no-parent":
			noParent = true
		case "--stop":
			stop = true
		case "--list-sessions", "--list-leaves":
			listSessions = true
		case "--list-roots":
			listRoots = true
		case "--delete-leaf":
			i++
			if i >= len(args) {
				return fmt.Errorf("--delete-leaf requires an argument")
			}
			deleteLeaf = args[i]
		case "--vacuum":
			vacuum = true
		case "--deep":
			deep = true
		case "--older-than":
			i++
			if i >= len(args) {
				return fmt.Errorf("--older-than requires an argument")
			}
			olderThan = args[i]
		case "--dry-run":
			dryRun = true
		case "--macro":
			i++
			if i >= len(args) {
				return fmt.Errorf("--macro requires an argument")
			}
			macroName = args[i]
		case "--list-macros":
			listMacros = true
			if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
				i++
				listMacrosFilter = args[i]
			}
		case "--macro-info":
			i++
			if i >= len(args) {
				return fmt.Errorf("--macro-info requires an argument")
			}
			macroInfoName = args[i]
		case "--param":
			i++
			if i >= len(args) {
				return fmt.Errorf("--param requires an argument")
			}
			macroParam = args[i]
		case "--no-autolaunch":
			autolaunch = false
		case "--autolaunch":
			autolaunch = true
		case "--show-config":
			showConfig = true
		case "--list-models":
			listModels = true
		case "--model":
			i++
			if i >= len(args) {
				return fmt.Errorf("--model requires an argument")
			}
			modelRef = args[i]
			modelExplicit = true
		case "--thinking":
			i++
			if i >= len(args) {
				return fmt.Errorf("--thinking requires an argument")
			}
			thinkingLevel = args[i]
			thinkingExplicit = true
		case "--mode":
			i++
			if i >= len(args) {
				return fmt.Errorf("--mode requires an argument")
			}
			modeName = args[i]
			modeExplicit = true
		case "--tools":
			i++
			if i >= len(args) {
				return fmt.Errorf("--tools requires an argument")
			}
			toolsCSV = args[i]
			toolsExplicit = true
		case "--plugins":
			i++
			if i >= len(args) {
				return fmt.Errorf("--plugins requires an argument")
			}
			pluginsCSV = args[i]
			pluginsExplicit = true
		default:
			return fmt.Errorf("unknown argument: %s\n\n%s", args[i], usageText())
		}
		i++
	}

	if deep && !vacuum {
		return fmt.Errorf("--deep requires --vacuum")
	}
	if noParent && sessionID != "" {
		return fmt.Errorf("--no-parent cannot be used with -s/--leaf")
	}

	if thirdPartyLicenses {
		_, err := fmt.Fprint(out, buildinfo.ThirdPartyLicenseReport())
		return err
	}

	var err error
	ctx, cwd, err = selectConnection(ctx, socketPath, sshDestination, savedConnection, viaDestination, cwd, cwdExplicit)
	if err != nil {
		return err
	}
	if _, remote := connectionTarget(ctx); remote && stop {
		return fmt.Errorf("--stop is local-only; it cannot be used with a remote connection")
	}

	if stop {
		status, err := service.ProbeDaemonContext(ctx)
		if err != nil {
			return err
		}
		switch status.State {
		case service.DaemonStarting:
			return fmt.Errorf("daemon is still starting; retry once ready")
		case service.DaemonUnavailable:
			fmt.Println("daemon is not running")
			return nil
		default:
			return service.StopDaemonContext(ctx)
		}
	}

	if listSessions {
		return runListSessions(ctx, autolaunch)
	}

	if listModels {
		return runListModels(ctx, autolaunch)
	}

	if listRoots {
		return runListRoots(ctx, autolaunch)
	}

	if deleteLeaf != "" {
		return runDeleteLeaf(ctx, deleteLeaf, autolaunch)
	}

	if vacuum {
		return runVacuum(ctx, olderThan, dryRun, deep, autolaunch)
	}

	if listMacros {
		return runListMacros(ctx, listMacrosFilter, sessionID, autolaunch)
	}

	if macroInfoName != "" {
		return runMacroInfo(ctx, macroInfoName, sessionID, autolaunch)
	}

	if macroName != "" {
		return runMacroCall(ctx, macroName, macroParam, sessionID, autolaunch)
	}

	if showConfig {
		return runShowConfig(ctx, cwd, autolaunch)
	}

	if promptText == "" {
		return fmt.Errorf("%s", usageText())
	}

	return runPrompt(ctx, promptText, sessionID, cwd, noParent, toolsCSV, toolsExplicit, pluginsCSV, pluginsExplicit, modelRef, modelExplicit, thinkingLevel, thinkingExplicit, modeName, modeExplicit, autolaunch)
}

func dialAndHello(ctx context.Context, autolaunch bool) (*serviceClient, error) {
	return dialService(ctx, autolaunch, "")
}

func parseErrorFromEvent(e *protocol.Error) error {
	return fmt.Errorf("error: %s: %s", e.Code, e.Message)
}

func runListSessions(ctx context.Context, autolaunch bool) error {
	sc, err := dialAndHello(ctx, autolaunch)
	if err != nil {
		return err
	}
	defer sc.Close()

	leaves, err := sc.RPC().ListLeaves(context.Background(), "", "")
	if err != nil {
		return fmt.Errorf("listing leaves: %w", err)
	}

	var visibleLeaves []protocol.LeafInfo
	for _, l := range leaves {
		if !l.IsTemp {
			visibleLeaves = append(visibleLeaves, l)
		}
	}
	if len(visibleLeaves) == 0 {
		fmt.Println("No sessions found.")
		return nil
	}
	fmt.Printf("%-12s %-20s %-16s %-8s %s\n", "ID", "NAME", "MODEL", "STATUS", "UPDATED")
	for _, l := range visibleLeaves {
		name := l.Name
		if name == "" {
			name = "-"
		}
		fmt.Printf("%-12s %-20s %-16s %-8s %s\n", l.ID, name, l.Model, l.Status, l.UpdatedAt)
	}
	return nil
}

func runListModels(ctx context.Context, autolaunch bool) error {
	sc, err := dialAndHello(ctx, autolaunch)
	if err != nil {
		return err
	}
	defer sc.Close()

	models, err := sc.RPC().ListModels(context.Background())
	if err != nil {
		return fmt.Errorf("listing models: %w", err)
	}
	if len(models) == 0 {
		fmt.Println("No models found.")
		return nil
	}
	fmt.Printf("%-40s %-16s %s\n", "REF", "TYPE", "MAX CONTEXT")
	for _, m := range models {
		maxCtx := ""
		if m.MaxContext > 0 {
			maxCtx = fmt.Sprintf("%d", m.MaxContext)
		}
		fmt.Printf("%-40s %-16s %s\n", m.Ref, m.Type, maxCtx)
	}
	return nil
}

func runListRoots(ctx context.Context, autolaunch bool) error {
	sc, err := dialAndHello(ctx, autolaunch)
	if err != nil {
		return err
	}
	defer sc.Close()

	roots, err := sc.RPC().ListRoots(context.Background())
	if err != nil {
		return fmt.Errorf("listing roots: %w", err)
	}
	if len(roots) == 0 {
		fmt.Println("No roots found.")
		return nil
	}
	fmt.Printf("%-12s %-20s %-12s %s\n", "ID", "CWD", "ROOT_TURN", "UPDATED")
	for _, r := range roots {
		fmt.Printf("%-12s %-20s %-12s %s\n", r.ID, r.Cwd, r.RootTurnID, r.UpdatedAt)
	}
	return nil
}

func runDeleteLeaf(ctx context.Context, leafID string, autolaunch bool) error {
	sc, err := dialAndHello(ctx, autolaunch)
	if err != nil {
		return err
	}
	defer sc.Close()

	ld, err := sc.RPC().DeleteLeaf(context.Background(), leafID)
	if err != nil {
		return fmt.Errorf("deleting leaf: %w", err)
	}
	if ld.TurnID != "" {
		fmt.Printf("Deleted leaf %s (was at turn %s)\n", ld.LeafID, ld.TurnID)
	} else {
		fmt.Printf("Deleted leaf %s\n", ld.LeafID)
	}
	return nil
}

func parseOlderThan(dur string) (int64, error) {
	if len(dur) == 0 {
		return 0, fmt.Errorf("empty duration")
	}
	numStr := dur[:len(dur)-1]
	suffix := dur[len(dur)-1]
	var mult int64
	switch suffix {
	case 's':
		mult = 1
	case 'm':
		mult = 60
	case 'h':
		mult = 3600
	case 'd':
		mult = 86400
	default:
		return 0, fmt.Errorf("unknown duration suffix: %c (use s, m, h, or d)", suffix)
	}
	num, err := strconv.ParseInt(numStr, 10, 64)
	if err != nil {
		return 0, fmt.Errorf("invalid duration: %s", dur)
	}
	if num < 0 {
		return 0, fmt.Errorf("duration must be non-negative: %s", dur)
	}
	if num > int64(^uint64(0)>>1)/mult {
		return 0, fmt.Errorf("duration is too large: %s", dur)
	}
	return num * mult, nil
}

func runVacuum(ctx context.Context, olderThan string, dryRun, deep, autolaunch bool) error {
	sc, err := dialAndHello(ctx, autolaunch)
	if err != nil {
		return err
	}
	defer sc.Close()

	var olderThanSecs int64
	if olderThan != "" {
		secs, err := parseOlderThan(olderThan)
		if err != nil {
			return fmt.Errorf("parsing --older-than: %w", err)
		}
		olderThanSecs = secs
	}
	vr, err := runVacuumRPC(sc.RPC(), olderThanSecs, dryRun, deep)
	if err != nil {
		return err
	}
	if dryRun {
		fmt.Printf("Dry run: would prune %d roots and %d turns\n", vr.RootsPruned, vr.TurnsPruned)
	} else {
		fmt.Printf("Pruned %d roots and %d turns\n", vr.RootsPruned, vr.TurnsPruned)
	}
	return nil
}

func runVacuumRPC(rpc *ezagentapi.RPC, olderThan int64, dryRun, deep bool) (protocol.VacuumResult, error) {
	result, err := rpc.VacuumWithOptions(context.Background(), ezagentapi.VacuumOptions{
		OlderThan: olderThan,
		DryRun:    dryRun,
		Deep:      deep,
	})
	if err != nil {
		return protocol.VacuumResult{}, fmt.Errorf("vacuum: %w", err)
	}
	return result, nil
}

func freshSessionOrigin(parent *parentLaunchProfile) string {
	if parent != nil {
		return "subagent"
	}
	return "oneshot"
}

func writeSessionMetadata(w io.Writer, leafID, parentLeafID, origin string, update func(string, map[string]string) error) {
	metadata := map[string]string{"session_origin": origin}
	if parentLeafID != "" {
		metadata["parent_leaf"] = parentLeafID
	}
	if err := update(leafID, metadata); err != nil {
		fmt.Fprintf(w, "warning: session created, but origin/grouping metadata could not be saved: %v\n", err)
	}
}

func resolveFreshCWD(cwd string) (string, error) {
	if cwd == "" {
		resolved, err := os.Getwd()
		if err != nil {
			return "", fmt.Errorf("getting cwd: %w", err)
		}
		return filepath.Clean(resolved), nil
	}
	resolved, err := filepath.Abs(cwd)
	if err != nil {
		return "", fmt.Errorf("resolving cwd: %w", err)
	}
	return resolved, nil
}

func resolveFreshParent(ctx context.Context, sc *serviceClient, cwd string, noParent bool) (*parentLaunchProfile, error) {
	if noParent {
		return nil, nil
	}
	candidate := environmentLeafID(ctx)
	if candidate == "" {
		return nil, nil
	}
	leaves, err := sc.RPC().ListLeaves(ctx, "", cwd)
	if err != nil {
		return nil, nil // The environment candidate is intentionally best effort.
	}
	matched := false
	for _, leaf := range leaves {
		if leaf.ID == candidate && !leaf.IsTemp {
			matched = true
			break
		}
	}
	if !matched {
		return nil, nil
	}
	stats, err := sc.RPC().LeafStats(ctx, candidate)
	if err != nil {
		return nil, fmt.Errorf("reading parent session %q profile: %w", candidate, err)
	}
	if filepath.Clean(stats.RootCwd) != filepath.Clean(cwd) {
		return nil, nil
	}
	mode, _, err := sc.RPC().GetLeafConfig(ctx, candidate, "builtin.mode")
	if err != nil {
		return nil, fmt.Errorf("reading parent session %q mode: %w", candidate, err)
	}
	return &parentLaunchProfile{LeafID: candidate, Model: stats.Model, ThinkingLevel: stats.ThinkingLevel, Mode: mode}, nil
}

func validateFreshMode(ctx context.Context, sc *serviceClient, selected selectedLaunchProfile) error {
	result, err := sc.RPC().MacroCall(ctx, "", "builtin.setmode", "--mode")
	if err != nil {
		return fmt.Errorf("discovering modes for fresh-session preflight: %w", err)
	}
	if result.IsError {
		return fmt.Errorf("discovering modes for fresh-session preflight: %s", result.Result)
	}
	modes, err := protocol.ParseCSVRow(result.Result)
	if err != nil {
		return fmt.Errorf("parsing modes for fresh-session preflight: %w", err)
	}
	for _, mode := range modes {
		if mode == selected.Mode {
			return nil
		}
	}
	return fmt.Errorf("fresh-session preflight: %s %q is not available", launchValueDescription(selected.ModeSource, "--mode", "mode"), selected.Mode)
}

func validateResumeMode(ctx context.Context, sc *serviceClient, leafID string, selected selectedLaunchProfile) error {
	if !selected.ApplyMode || selected.Mode == "" {
		return nil
	}
	result, err := sc.RPC().MacroCall(ctx, leafID, "builtin.setmode", "--mode")
	if err != nil {
		return fmt.Errorf("discovering modes for resume preflight: %w", err)
	}
	if result.IsError {
		return fmt.Errorf("discovering modes for resume preflight: %s", result.Result)
	}
	modes, err := protocol.ParseCSVRow(result.Result)
	if err != nil {
		return fmt.Errorf("parsing modes for resume preflight: %w", err)
	}
	for _, mode := range modes {
		if mode == selected.Mode {
			return nil
		}
	}
	return fmt.Errorf("resume preflight: %s %q is not available", launchValueDescription(selected.ModeSource, "--mode", "mode"), selected.Mode)
}

func runPrompt(ctx context.Context, promptText, sessionID, cwd string, noParent bool, toolsCSV string, toolsExplicit bool, pluginsCSV string, pluginsExplicit bool, modelRef string, modelExplicit bool, thinkingLevel string, thinkingExplicit bool, modeName string, modeExplicit bool, autolaunch bool) error {
	// Fresh discovery is connection-scoped to the child CWD. Resume deliberately
	// retains the default connection scope; --cwd does not redefine saved config.
	if sessionID == "" {
		var err error
		cwd, err = freshCWD(ctx, cwd)
		if err != nil {
			return err
		}
	}
	dialCWD := ""
	if sessionID == "" {
		dialCWD = cwd
	}
	sc, err := dialService(ctx, autolaunch, dialCWD)
	if err != nil {
		return err
	}
	defer sc.Close()

	var leafID string
	var parentTurnID *string

	if sessionID != "" {
		var found bool
		leafID, parentTurnID, found, err = resolveSession(sc, sessionID)
		if err != nil {
			return err
		}
		if !found {
			return fmt.Errorf("session not found: %s", sessionID)
		}
		environmentLeafID := environmentLeafID(ctx)
		if environmentLeafID != "" {
			leaves, err := sc.RPC().ListLeavesWithMetadata(ctx, "", "", []string{"parent_leaf"})
			if err != nil {
				return fmt.Errorf("resume preflight: listing session ancestry: %w", err)
			}
			parents := make(map[string]string, len(leaves))
			for _, leaf := range leaves {
				parents[leaf.ID] = strings.TrimSpace(leaf.Metadata["parent_leaf"])
			}
			if resumeTargetProtected(environmentLeafID, leafID, parents) {
				return fmt.Errorf("resume preflight: -s/--leaf value %q targets EZ_AGENT_LEAF_ID value %q or one of its ancestors; create a fresh child with -p instead", leafID, environmentLeafID)
			}
		}
		stats, err := sc.RPC().LeafStats(ctx, leafID)
		if err != nil {
			return fmt.Errorf("resume preflight: reading saved profile: %w", err)
		}
		savedMode, _, err := sc.RPC().GetLeafConfig(ctx, leafID, "builtin.mode")
		if err != nil {
			return fmt.Errorf("resume preflight: reading saved mode: %w", err)
		}
		selected := selectResumeLaunchProfile(resumeLaunchSelection{
			Saved: selectedLaunchProfile{Model: stats.Model, ThinkingLevel: stats.ThinkingLevel, Mode: savedMode},
			Model: modelRef, ModelExplicit: modelExplicit,
			Thinking: thinkingLevel, ThinkingExplicit: thinkingExplicit,
			Mode: modeName, ModeExplicit: modeExplicit,
		})
		models, err := sc.RPC().ListModelsForLeaf(ctx, leafID)
		if err != nil {
			return fmt.Errorf("listing models for resume preflight: %w", err)
		}
		modelRefs, _ := frontend.LoadModelRefs(ctx, sc.RPC(), leafID)
		if err := validateLaunchModelRef(models, selected, modelRefs.BrowserRef(selected.Model)); err != nil {
			return fmt.Errorf("resume preflight: %w", err)
		}
		if err := validateResumeMode(ctx, sc, leafID, selected); err != nil {
			return err
		}
		toolsList := parseCSV(toolsCSV)
		if toolsExplicit {
			available, err := sc.RPC().ListTools(ctx, leafID)
			if err != nil {
				return fmt.Errorf("listing tools for resume preflight: %w", err)
			}
			if err := validateExplicitNames("tool", toolsList, available); err != nil {
				return fmt.Errorf("resume preflight: %w", err)
			}
		}
		pluginsList := parseCSV(pluginsCSV)
		if pluginsExplicit {
			available, err := sc.RPC().ListPlugins(ctx, leafID)
			if err != nil {
				return fmt.Errorf("listing plugins for resume preflight: %w", err)
			}
			if err := validateExplicitNames("plugin", pluginsList, available); err != nil {
				return fmt.Errorf("resume preflight: %w", err)
			}
		}

		// All deterministic resume checks above precede every leaf mutation.
		if modelExplicit {
			if _, err := sc.RPC().SetModel(ctx, leafID, selected.Model); err != nil {
				return fmt.Errorf("setting model: %w", err)
			}
		}
		applyDefaultThinking := modelExplicit && modelRef != stats.Model && !thinkingExplicit
		if thinkingExplicit || applyDefaultThinking {
			if _, err := sc.RPC().SetThinkingLevel(ctx, leafID, selected.ThinkingLevel); err != nil {
				return fmt.Errorf("setting thinking level: %w", err)
			}
		}
		if toolsExplicit {
			toolsJSON, _ := json.Marshal(toolsList)
			if err := sc.RPC().SetLeafConfig(ctx, leafID, "active_tools", string(toolsJSON)); err != nil {
				return fmt.Errorf("setting active_tools: %w", err)
			}
		}
		if pluginsExplicit {
			pluginsJSON, _ := json.Marshal(pluginsList)
			if err := sc.RPC().SetLeafConfig(ctx, leafID, "active_plugins", string(pluginsJSON)); err != nil {
				return fmt.Errorf("setting active_plugins: %w", err)
			}
		}
		modeName = selected.Mode
	} else {
		parent, err := resolveFreshParent(ctx, sc, cwd, noParent)
		if err != nil {
			return err
		}
		resolved, err := sc.RPC().ResolveModels(ctx, "")
		if err != nil {
			return fmt.Errorf("resolving fresh-session models: %w", err)
		}
		selected := selectFreshLaunchProfile(freshLaunchSelection{
			DefaultModel: resolved.Main, Parent: parent, NoParent: noParent,
			Model: modelRef, ModelExplicit: modelExplicit,
			Thinking: thinkingLevel, ThinkingExplicit: thinkingExplicit,
			Mode: modeName, ModeExplicit: modeExplicit,
		})
		models, err := sc.RPC().ListModels(ctx)
		if err != nil {
			return fmt.Errorf("listing models for fresh-session preflight: %w", err)
		}
		modelRefs, _ := frontend.LoadModelRefs(ctx, sc.RPC(), "")
		if err := validateLaunchModelRef(models, selected, modelRefs.BrowserRef(selected.Model)); err != nil {
			return fmt.Errorf("fresh-session preflight: %w", err)
		}
		if selected.ApplyMode && selected.Mode != "" {
			if err := validateFreshMode(ctx, sc, selected); err != nil {
				return err
			}
		}
		toolsList := parseCSV(toolsCSV)
		if toolsExplicit {
			available, err := sc.RPC().ListTools(ctx, "")
			if err != nil {
				return fmt.Errorf("listing tools for fresh-session preflight: %w", err)
			}
			if err := validateExplicitNames("tool", toolsList, available); err != nil {
				return fmt.Errorf("fresh-session preflight: %w", err)
			}
		}
		pluginsList := parseCSV(pluginsCSV)
		if pluginsExplicit {
			available, err := sc.RPC().ListPlugins(ctx, "")
			if err != nil {
				return fmt.Errorf("listing plugins for fresh-session preflight: %w", err)
			}
			if err := validateExplicitNames("plugin", pluginsList, available); err != nil {
				return fmt.Errorf("fresh-session preflight: %w", err)
			}
		}

		createCmd := protocol.CreateLeaf{
			Cwd: cwd, Autosubscribe: true,
			Model: selected.Model, ThinkingLevel: selected.ThinkingLevel,
		}
		if toolsExplicit {
			createCmd.ActiveTools = toolsList
			createCmd.ToolsExplicit = true
		}
		if pluginsExplicit {
			createCmd.ActivePlugins = pluginsList
			createCmd.PluginsExplicit = true
		}
		lc, err := sc.RPC().CreateLeaf(ctx, createCmd)
		if err != nil {
			return fmt.Errorf("creating leaf: %w", err)
		}
		leafID = lc.LeafID
		parentLeafID := ""
		if parent != nil {
			parentLeafID = parent.LeafID
		}
		writeSessionMetadata(os.Stderr, leafID, parentLeafID, freshSessionOrigin(parent), func(leafID string, metadata map[string]string) error {
			_, err := sc.RPC().UpdateLeafMeta(ctx, leafID, nil, metadata, nil)
			return err
		})
		modeName = selected.Mode
		modeExplicit = selected.ApplyMode
	}

	// Mode is leaf-scoped and validated by the canonical builtin macro. Wait for
	// its result before prompting so the on-user mode plugin sees the new value.
	if modeExplicit {
		mr, err := sc.RPC().MacroCall(context.Background(), leafID, "builtin.setmode", modeName)
		if err != nil {
			return fmt.Errorf("setting mode: %w", err)
		}
		if mr.IsError {
			return fmt.Errorf("setting mode: %s", mr.Result)
		}
	}

	if sessionID != "" {
		if _, err := sc.RPC().SwitchLeaf(context.Background(), leafID); err != nil {
			return fmt.Errorf("switching leaf: %w", err)
		}
	}

	// Send the prompt via RPC; PromptAccepted comes back as the RPC response.
	// The streaming events (agent_start, message_update, etc.) arrive as
	// typed events on the event channel.
	pa, err := sc.RPC().PromptText(context.Background(), leafID, promptText, parentTurnID)
	if err != nil {
		return fmt.Errorf("sending prompt: %w", err)
	}

	stream := newPromptStream(pa.LeafID, pa.RequestID, pa.TipTurnID, os.Stdout, wallClock{}, sc.sendEvent,
		reasoningStylingEnabled(int(os.Stdout.Fd()), os.LookupEnv, term.IsTerminal),
		func(leafID string) (protocol.LeafStatsResponse, error) {
			return sc.RPC().LeafStats(context.Background(), leafID)
		},
		func(leafID, baselineTip string) (canonicalPromptResult, error) {
			return readCanonicalPrompt(context.Background(), sc.RPC(), leafID, pa.RootID, baselineTip)
		})
	for {
		ev, err := sc.recvEvent()
		if err != nil {
			return stream.presentError(fmt.Errorf("reading event: %w", err))
		}
		done, err := stream.handle(ev)
		if err != nil {
			return stream.presentError(err)
		}
		if done {
			return nil
		}
	}
}

func resolveSession(sc *serviceClient, sessionID string) (string, *string, bool, error) {
	leaves, err := sc.RPC().ListLeaves(context.Background(), "", "")
	if err != nil {
		return "", nil, false, fmt.Errorf("listing leaves: %w", err)
	}
	trimmedID := strings.TrimSpace(sessionID)
	for _, l := range leaves {
		if l.ID == trimmedID {
			var tip *string
			if l.TurnID != "" {
				tip = &l.TurnID
			}
			return l.ID, tip, true, nil
		}
	}
	return "", nil, false, nil
}

func resolveSessionForMacro(sc *serviceClient, sessionID string) (string, *string, error) {
	leafID, tip, found, err := resolveSession(sc, sessionID)
	if err != nil {
		return "", nil, err
	}
	if !found {
		return "", nil, fmt.Errorf("session not found: %s", sessionID)
	}
	return leafID, tip, nil
}

func runMacroCall(ctx context.Context, macroName, paramString, sessionID string, autolaunch bool) error {
	sc, err := dialAndHello(ctx, autolaunch)
	if err != nil {
		return err
	}
	defer sc.Close()

	var leafID string
	if sessionID != "" {
		leafID, _, err = resolveSessionForMacro(sc, sessionID)
		if err != nil {
			return err
		}
	}

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	mr, err := sc.RPC().MacroCall(ctx, leafID, macroName, paramString)
	if err != nil {
		if errors.Is(ctx.Err(), context.DeadlineExceeded) {
			return fmt.Errorf("macro_call timed out: %s", macroName)
		}
		fmt.Fprintln(os.Stderr, err)
		return fmt.Errorf("macro_call failed: %w", err)
	}
	if mr.IsError {
		fmt.Fprintln(os.Stderr, mr.Result)
		return fmt.Errorf("macro %s returned error", mr.MacroName)
	}
	fmt.Println(mr.Result)
	return nil
}

func runListMacros(ctx context.Context, filter, sessionID string, autolaunch bool) error {
	sc, err := dialAndHello(ctx, autolaunch)
	if err != nil {
		return err
	}
	defer sc.Close()

	var leafID string
	if sessionID != "" {
		leafID, _, err = resolveSessionForMacro(sc, sessionID)
		if err != nil {
			return err
		}
	}

	macros, err := sc.RPC().ListMacros(context.Background(), leafID, filter)
	if err != nil {
		return fmt.Errorf("listing macros: %w", err)
	}
	if len(macros) == 0 {
		fmt.Println("No macros found.")
		return nil
	}
	for _, m := range macros {
		fmt.Println(m.Name)
	}
	return nil
}

func runMacroInfo(ctx context.Context, macroName, sessionID string, autolaunch bool) error {
	sc, err := dialAndHello(ctx, autolaunch)
	if err != nil {
		return err
	}
	defer sc.Close()

	var leafID string
	if sessionID != "" {
		leafID, _, err = resolveSessionForMacro(sc, sessionID)
		if err != nil {
			return err
		}
	}

	macros, err := sc.RPC().ListMacros(context.Background(), leafID, "")
	if err != nil {
		return fmt.Errorf("listing macros: %w", err)
	}
	var found *protocol.MacroInfo
	for i := range macros {
		if macros[i].Name == macroName {
			found = &macros[i]
			break
		}
	}
	if found == nil {
		return fmt.Errorf("macro not found: %s", macroName)
	}
	fmt.Printf("Name:        %s\n", found.Name)
	if found.Description != "" {
		fmt.Printf("Description: %s\n", found.Description)
	}
	if len(found.Triggers) > 0 {
		fmt.Printf("Triggers:    %s\n", strings.Join(found.Triggers, ", "))
	}
	if found.Timeout != "" {
		fmt.Printf("Timeout:     %s\n", found.Timeout)
	}
	if found.MaxTimeout != "" {
		fmt.Printf("MaxTimeout:  %s\n", found.MaxTimeout)
	}
	if found.Priority != 0 {
		fmt.Printf("Priority:    %d\n", found.Priority)
	}
	if found.Version != "" {
		fmt.Printf("Version:     %s\n", found.Version)
	}
	return nil
}

func runShowConfig(ctx context.Context, cwd string, autolaunch bool) error {
	sc, err := dialService(ctx, autolaunch, cwd)
	if err != nil {
		return err
	}
	defer sc.Close()

	ec, err := sc.RPC().GetEffectiveConfig(context.Background(), "")
	if err != nil {
		return fmt.Errorf("getting effective config: %w", err)
	}
	fmt.Printf("# Layers: %s\n", strings.Join(ec.Layers, " + "))
	if ec.Cwd != "" {
		fmt.Printf("# Cwd: %s\n", ec.Cwd)
	}
	if ec.ConfigError != "" {
		fmt.Printf("# ConfigError: %s\n", ec.ConfigError)
	}
	fmt.Print(ec.Config)
	return nil
}