pkg/service/server.go

package service

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"net"
	"os"
	"path/filepath"
	"reflect"
	"sort"
	"strings"
	"sync"
	"sync/atomic"
	"syscall"
	"time"

	"git.cafe/ezterry/ez-agent/internal/incident"

	"git.cafe/ezterry/ez-agent/pkg/ezagentapi"
	"git.cafe/ezterry/ez-agent/pkg/protocol"
	"git.cafe/ezterry/ez-agent/pkg/service/agent"
	"git.cafe/ezterry/ez-agent/pkg/service/config"
	"git.cafe/ezterry/ez-agent/pkg/service/session"
	"git.cafe/ezterry/ez-agent/pkg/watchdog"
)

type Connection struct {
	ID               string
	Name             string
	LeafID           string
	Cwd              string
	selectionVersion uint64      // guarded by Server.mu
	selectionMu      sync.Mutex  // serializes subscription changes and snapshot enqueue
	prepCwd          *cwdCapture // reader-owned
	prepSeq          uint64      // reader-owned
	capturedCwd      *cwdCapture // immutable request-local config view
	capturedCtx      context.Context
	helloDone        atomic.Bool

	AnnouncedTools    []string
	AnnouncedPlugins  []string
	AnnouncedMacros   []string
	requestedTools    []string
	requestedPlugins  []string
	requestedMacros   []string
	helloCh           chan struct{}
	announceCh        chan struct{}
	infoCh            chan struct{}
	pendingToolInfo   map[string]struct{}
	toolInfoWaiters   map[string]chan struct{} // Exact on-demand responses, guarded by chMu.
	pendingPluginInfo map[string]struct{}
	pendingMacroInfo  map[string]struct{}
	capabilityInfoSeq uint64

	apiConn          *ezagentapi.Conn
	chMu             sync.Mutex
	backgroundRPCs   sync.WaitGroup
	backgroundClosed bool // guarded by chMu

	conn    net.Conn
	process *os.Process

	// launchedService records the effective direct service definition that
	// started this daemon-owned process generation. It supplies configured
	// capabilities when the peer intentionally sends an empty Announce.
	launchedServiceName string
	launchedService     *config.ServiceConfig
}

func (c *Connection) ConnID() string { return c.ID }

func (c *Connection) closeHelloCh() {
	c.chMu.Lock()
	defer c.chMu.Unlock()
	if c.helloCh != nil {
		close(c.helloCh)
		c.helloCh = nil
	}
}

func (c *Connection) closeAnnounceCh() {
	c.chMu.Lock()
	defer c.chMu.Unlock()
	if c.announceCh != nil {
		close(c.announceCh)
		c.announceCh = nil
	}
}

func (c *Connection) closeInfoCh() {
	c.chMu.Lock()
	defer c.chMu.Unlock()
	if c.infoCh != nil {
		close(c.infoCh)
		c.infoCh = nil
	}
}

type Server struct {
	audit           *serviceAudit
	listener        net.Listener
	config          *config.Config
	configPath      string
	configMtime     time.Time
	authMtime       time.Time
	storage         *session.Storage
	registry        *Registry
	ipc             *IPCCaller
	wdMgr           *watchdog.Manager
	leaves          *leafOperations
	connections     map[string]*Connection
	toolInvocations map[string]*toolInvocation
	mu              sync.RWMutex
	reloadMu        sync.Mutex

	// admissionSendMu serializes delayed tool-steer responses with the first
	// publication of shutdown. It is never held while waiting for admission.
	admissionSendMu sync.Mutex

	subscriptions map[string]map[string]struct{}

	shutdown         chan struct{}
	shutdownComplete chan struct{}
	stopOnce         sync.Once
	socketPath       string
	socketInode      uint64
	pool             *ProcessPool

	projectCache map[string]*projectCacheEntry
	projectTrust *projectTrustStore

	// authMtimeFor is a test seam for deterministic stabilization checks.
	authMtimeFor func(*config.Config) time.Time
	// beforeRunCompletionPublication is a test seam for deterministic handoff races.
	beforeRunCompletionPublication func(agent.RunCompletion)
	// beforeLeafSnapshotEnqueue is a test seam for capture/send ordering.
	beforeLeafSnapshotEnqueue func(protocol.LeafUpdated)
	beforeLeafStatsEnqueue    func(protocol.LeafStatsResponse)
	// afterLeafAdmissionReserved is a test seam for deletion/admission ordering.
	afterLeafAdmissionReserved func(string)
	// afterProjectOnStartAttempt is a test seam for asynchronous project startup.
	afterProjectOnStartAttempt func(string)
	// connectionID allocates a fresh identity for each inbound or spawned peer.
	connectionID func() string
}

type projectCacheEntry struct {
	cfg          *config.Config
	candidateKey string
}

const agentIdleEvict = 5 * time.Minute

func sanitizeServiceCapabilities(cfg *config.Config) {
	if cfg == nil {
		return
	}
	for name, service := range cfg.Services {
		if service.Direct || (len(service.Tools) == 0 && len(service.Plugins) == 0 && len(service.Macros) == 0) {
			continue
		}
		slog.Warn("background service config capabilities are ignored", "service", name)
		service.Tools = nil
		service.Plugins = nil
		service.Macros = nil
		cfg.Services[name] = service
	}
}

func NewServer(cfg *config.Config, storage *session.Storage) *Server {
	sanitizeServiceCapabilities(cfg)
	reg := NewRegistry(cfg)
	s := &Server{
		config:           cfg,
		storage:          storage,
		registry:         reg,
		wdMgr:            watchdog.NewManager(),
		connections:      make(map[string]*Connection),
		subscriptions:    make(map[string]map[string]struct{}),
		shutdown:         make(chan struct{}),
		shutdownComplete: make(chan struct{}),
		pool:             NewProcessPool(),
		configPath:       config.ConfigPath(),
		projectCache:     make(map[string]*projectCacheEntry),
		projectTrust:     loadProjectTrustStore(config.StateDir()),
		authMtimeFor:     readAuthMtimeFor,
		connectionID:     freshConnectionID,
	}
	if s.projectTrust.loadErr != nil {
		slog.Warn("project trust store is unusable; project config remains quarantined", "path", s.projectTrust.path, "error", s.projectTrust.loadErr)
	}
	s.configMtime = s.readConfigMtime()
	s.authMtime = s.readAuthMtime()
	s.ipc = NewIPCCaller(reg, s.pool, s)
	s.leaves = newLeafOperations(storage, leafAgentDependencies{
		toolCaller: s.ipc, toolResolver: s.ipc, toolAborter: s.ipc,
		pluginCaller: s.ipc, pluginInfoResolver: s.ipc,
		macroCaller: s.ipc, macroInfoResolver: s.ipc,
		steerRouter: s,
	}, s)
	s.leaves.questions = newProjectQuestionOwner(s.projectTrust, func(leafID string) (string, error) {
		if storage == nil {
			return "", ErrPendingQuestionNotFound
		}
		leaf, err := storage.GetLeaf(leafID)
		if err != nil || leaf == nil {
			return "", err
		}
		root, err := storage.GetRoot(leaf.RootID)
		if err != nil || root == nil {
			return "", err
		}
		return root.Cwd, nil
	}, s.loadedOrFollowedLeafIDs)
	s.leaves.activeToolCalls = s.activeToolCallsForLeaf
	s.leaves.claimToolInvocationsForLeaf = func(leafID string) (int, func()) {
		return s.claimToolInvocations(func(inv *toolInvocation) bool { return inv.leafID == leafID })
	}
	s.leaves.hasToolInvocations = func(leafID string) bool {
		s.mu.RLock()
		defer s.mu.RUnlock()
		for _, inv := range s.toolInvocations {
			if inv.leafID == leafID {
				return true
			}
		}
		return false
	}
	s.leaves.cancelToolInvocationsForRoots = func(ids []string) {
		roots := make(map[string]bool, len(ids))
		for _, id := range ids {
			roots[id] = true
		}
		_, cancel := s.claimToolInvocations(func(inv *toolInvocation) bool { return roots[inv.rootID] })
		cancel()
	}
	s.leaves.backgroundWakeConfigForCwd = s.resolveConfigForCwdContext
	s.leaves.killBackground = s.sendBackgroundKill
	s.leaves.backgroundCallPending = func(leafID, taskID, connID string) (bool, bool) {
		for _, pc := range reg.GetPendingCallsForLeaf(leafID) {
			if pc.ToolCallID == taskID && pc.ConnID == connID {
				return true, pc.ToolName == "run-cmd" || pc.ToolName == "bash"
			}
		}
		return false, false
	}
	return s
}

func (s *Server) readConfigMtime() time.Time {
	info, err := os.Stat(s.configPath)
	if err != nil {
		return time.Time{}
	}
	return info.ModTime()
}

func (s *Server) readAuthMtime() time.Time {
	return s.authMtimeFor(s.configSnapshot())
}

func readAuthMtimeFor(cfg *config.Config) time.Time {
	authPath := cfg.AuthFilePath()
	info, err := os.Stat(authPath)
	if err != nil {
		return time.Time{}
	}
	return info.ModTime()
}

// checkAuthReload re-reads auth.yaml if its mtime has changed, updating
// only the Auth map in the current config. This picks up credential changes
// (OAuth login by configurator, token refresh by another daemon instance)
// without requiring a full config reload. The project cache is cleared so
// localized configs pick up the new auth on next access.
func (s *Server) checkAuthReload() {
	s.reloadMu.Lock()
	defer s.reloadMu.Unlock()
	s.checkAuthReloadLocked()
}

func (s *Server) checkAuthReloadLocked() {
	mtime := s.readAuthMtime()
	s.mu.RLock()
	oldMtime, old := s.authMtime, s.config
	s.mu.RUnlock()
	if mtime.Equal(oldMtime) {
		return
	}
	cfg, err := old.CloneWithReloadedAuth()
	if err != nil {
		slog.Warn("failed to reload auth, keeping cached version", "error", err)
		return
	}
	s.mu.Lock()
	s.config = cfg
	s.authMtime = mtime
	s.projectCache = make(map[string]*projectCacheEntry)
	s.mu.Unlock()
	slog.Info("reloaded auth credentials", "path", cfg.AuthFilePath())
}

func (s *Server) checkUserConfigReload() {
	s.reloadMu.Lock()
	defer s.reloadMu.Unlock()
	s.checkUserConfigReloadLocked()
}

func (s *Server) checkUserConfigReloadLocked() {
	mtime := s.readConfigMtime()
	s.mu.RLock()
	oldMtime := s.configMtime
	s.mu.RUnlock()
	if mtime.Equal(oldMtime) {
		return
	}
	cfg, authMtime, err := s.loadStableGlobalConfig()
	if err != nil {
		slog.Warn("failed to reload user config, keeping cached version", "error", err)
		return
	}
	s.publishUserConfigReloadLocked(cfg, mtime, authMtime)
	slog.Info("reloaded user config", "path", s.configPath)
}

const maxAuthStabilizationAttempts = 3

// loadStableGlobalConfig loads complete config, then brackets a fresh auth
// load with file stamps. This avoids recording an auth edit that the Config
// did not actually load, including when config changes auth_file.
func (s *Server) loadStableGlobalConfig() (*config.Config, time.Time, error) {
	cfg, err := config.LoadGlobal(s.configPath)
	if err != nil {
		return nil, time.Time{}, err
	}
	for attempt := 0; attempt < maxAuthStabilizationAttempts; attempt++ {
		before := s.authMtimeFor(cfg)
		refreshed, err := cfg.CloneWithReloadedAuth()
		if err != nil {
			return nil, time.Time{}, err
		}
		after := s.authMtimeFor(refreshed)
		if before.Equal(after) {
			return refreshed, after, nil
		}
		cfg = refreshed
	}
	return nil, time.Time{}, fmt.Errorf("auth file did not stabilize after %d attempts", maxAuthStabilizationAttempts)
}

// publishUserConfigReload publishes a config already loaded from disk. Keeping
// loading separate from publication gives reload behavior a focused test seam.
func (s *Server) publishUserConfigReload(cfg *config.Config, mtime time.Time) {
	s.reloadMu.Lock()
	defer s.reloadMu.Unlock()
	s.publishUserConfigReloadLocked(cfg, mtime, readAuthMtimeFor(cfg))
}

func (s *Server) publishUserConfigReloadLocked(cfg *config.Config, mtime, authMtime time.Time) {
	sanitizeServiceCapabilities(cfg)
	s.mu.Lock()
	old := s.config
	s.config = cfg
	s.configMtime = mtime
	s.authMtime = authMtime
	s.registry.ApplyConfig(cfg)
	s.projectCache = make(map[string]*projectCacheEntry)
	relevant := !reflect.DeepEqual(old.Services, cfg.Services) ||
		!reflect.DeepEqual(old.ToolOverrides, cfg.ToolOverrides) ||
		!reflect.DeepEqual(old.Defaults.Tools, cfg.Defaults.Tools) ||
		!reflect.DeepEqual(old.Defaults.Plugins, cfg.Defaults.Plugins)
	s.mu.Unlock()
	if relevant && s.leaves != nil {
		s.leaves.invalidateAllToolCaches()
	}
}

// configSnapshot is the synchronized accessor for the published global config.
func (s *Server) configSnapshot() *config.Config {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.config
}

func (s *Server) LocalizedConfig(cwd string) *config.Config {
	s.reloadMu.Lock()
	defer s.reloadMu.Unlock()
	return s.localizedConfigLocked(cwd)
}

func (s *Server) localizedConfigLocked(cwd string) *config.Config {
	global := s.configSnapshot()
	if cwd == "" {
		return global
	}
	candidate, err := inspectProjectConfig(cwd)
	if err != nil || candidate == nil {
		if err != nil {
			slog.Warn("failed to inspect project config; quarantining it", "cwd", cwd, "error", err)
		}
		return global
	}
	decision, ok := s.projectTrust.decision(candidate)
	if !ok || decision != protocol.QuestionReplyTrust {
		return global
	}

	s.mu.RLock()
	entry, ok := s.projectCache[cwd]
	s.mu.RUnlock()

	if ok && entry.candidateKey == candidate.key() {
		return entry.cfg
	}

	cfg, err := config.LoadLayeredProjectData(s.configPath, candidate.Data)
	if err != nil {
		slog.Warn("failed to load project config", "cwd", cwd, "error", err)
		if ok {
			return entry.cfg
		}
		return s.configSnapshot()
	}

	sanitizeServiceCapabilities(cfg)
	s.mu.Lock()
	s.projectCache[cwd] = &projectCacheEntry{cfg: cfg, candidateKey: candidate.key()}
	s.mu.Unlock()

	return cfg
}

func validateRootCwd(cwd string) error {
	if cwd == "" {
		return fmt.Errorf("cwd is required")
	}
	if !filepath.IsAbs(cwd) {
		return fmt.Errorf("cwd must be an absolute path: %s", cwd)
	}
	info, err := os.Stat(cwd)
	if err != nil {
		return fmt.Errorf("cwd does not exist: %s", cwd)
	}
	if !info.IsDir() {
		return fmt.Errorf("cwd is not a directory: %s", cwd)
	}
	return nil
}

func (s *Server) resolveConfigFromLeaf(c *Connection, leaf *session.Leaf) *config.Config {
	var cwd string
	if leaf == nil && c != nil {
		cwd = s.connectionCwd(c)
	}
	s.reloadMu.Lock()
	defer s.reloadMu.Unlock()

	// Reload and localization form one serialized request snapshot.
	s.checkUserConfigReloadLocked()
	s.checkAuthReloadLocked()

	if leaf != nil {
		root, err := s.storage.GetRoot(leaf.RootID)
		if err == nil && root != nil && root.Cwd != "" {
			return s.localizedConfigLocked(root.Cwd)
		}
		return s.configSnapshot()
	}

	if cwd != "" {
		return s.localizedConfigLocked(cwd)
	}

	return s.configSnapshot()
}

func (s *Server) resolveConfigForCwd(cwd string) *config.Config {
	s.reloadMu.Lock()
	defer s.reloadMu.Unlock()
	s.checkUserConfigReloadLocked()
	s.checkAuthReloadLocked()
	return s.localizedConfigLocked(cwd)
}

// Pending loss input must not remain blocked on the configuration reload lock
// after abort or shutdown. It already captured cwd while storage was open.
func (s *Server) resolveConfigForCwdContext(ctx context.Context, cwd string) (*config.Config, error) {
	for !s.reloadMu.TryLock() {
		select {
		case <-ctx.Done():
			return nil, ctx.Err()
		case <-time.After(10 * time.Millisecond):
		}
	}
	defer s.reloadMu.Unlock()
	if err := ctx.Err(); err != nil {
		return nil, err
	}
	s.checkUserConfigReloadLocked()
	s.checkAuthReloadLocked()
	return s.localizedConfigLocked(cwd), nil
}

func (s *Server) resolveConfig(c *Connection, leafID string) *config.Config {
	var leaf *session.Leaf
	if leafID != "" {
		leaf, _ = s.storage.GetLeaf(leafID)
	}
	return s.resolveConfigFromLeaf(c, leaf)
}

// Start begins accepting on a pre-bound Unix listener. RunDaemon binds this
// listener before storage maintenance and hands it over after bootstrap stops.
func (s *Server) Start(listener net.Listener) error {
	if listener == nil {
		return fmt.Errorf("starting server: nil listener")
	}
	unixListener, ok := listener.(*net.UnixListener)
	if !ok {
		return fmt.Errorf("starting server: listener must be a Unix listener")
	}
	socketPath := unixListener.Addr().String()
	s.listener = listener

	info, err := os.Stat(socketPath)
	if err != nil {
		return fmt.Errorf("stat socket: %w", err)
	}
	stat, ok := info.Sys().(*syscall.Stat_t)
	if !ok {
		return fmt.Errorf("could not get socket inode")
	}
	s.socketPath = socketPath
	s.socketInode = stat.Ino

	slog.Info("listening on socket", "path", socketPath)

	go s.acceptLoop()
	go s.watchSocket()
	go s.evictIdleAgents()
	// Startup services are best effort and must not delay socket readiness.
	s.startOnStartServices(s.configSnapshot(), "global")
	return nil
}

func (s *Server) watchSocket() {
	ticker := time.NewTicker(5 * time.Second)
	defer ticker.Stop()
	for {
		select {
		case <-s.shutdown:
			return
		case <-ticker.C:
			info, err := os.Stat(s.socketPath)
			if err != nil {
				slog.Warn("socket removed, shutting down", "path", s.socketPath)
				s.Stop()
				return
			}
			stat, ok := info.Sys().(*syscall.Stat_t)
			if !ok || stat.Ino != s.socketInode {
				slog.Warn("socket replaced (inode changed), shutting down", "path", s.socketPath)
				s.Stop()
				return
			}
		}
	}
}

func (s *Server) SocketPath() string {
	return s.socketPath
}

func (s *Server) acceptLoop() {
	for {
		conn, err := s.listener.Accept()
		if err != nil {
			select {
			case <-s.shutdown:
				return
			default:
				slog.Error("accept error", "error", err)
				return
			}
		}
		c := s.registerIncomingConnection(conn)
		slog.Debug("client connected", "conn_id", c.ID)
		go func() {
			if err := c.apiConn.Start(); err != nil {
				slog.Debug("client connection ended during startup", "conn_id", c.ID, "error", err)
			}
			_ = c.apiConn.Wait()
			s.cleanupConnection(c)
		}()
	}
}

func freshConnectionID() string { return session.NewID("c_") }

func (s *Server) registerIncomingConnection(conn net.Conn) *Connection {
	c := &Connection{ID: s.connectionID(), conn: conn}
	c.apiConn = ezagentapi.AcceptServiceConnRW(conn, conn.Close, s.directConnServiceOptions(c))

	s.mu.Lock()
	defer s.mu.Unlock()
	s.connections[c.ID] = c
	return c
}

func (s *Server) cleanupConnection(c *Connection) {
	slog.Debug("client disconnecting", "conn_id", c.ID)
	c.chMu.Lock()
	c.backgroundClosed = true
	c.chMu.Unlock()
	_, cancelInvocations := s.claimToolInvocations(func(inv *toolInvocation) bool { return inv.origin == c && inv.defaultsOrigin })
	cancelInvocations()
	if c.apiConn != nil {
		_ = c.apiConn.Close()
	}
	c.backgroundRPCs.Wait()
	s.mu.Lock()
	current := s.connections[c.ID] == c
	if current {
		delete(s.connections, c.ID)
		for leafID, subs := range s.subscriptions {
			delete(subs, c.ID)
			if len(subs) == 0 {
				delete(s.subscriptions, leafID)
			}
		}
		c.LeafID = ""
		s.registry.ReleaseConnection(c.ID)
	}
	s.mu.Unlock()
	if current {
		s.registry.AbortPendingCallsForConn(c.ID, func(kind, id string) {
			s.wdMgr.Cancel(watchdog.Key{Type: kind, ID: id})
		})
		if s.leaves != nil {
			s.leaves.cleanupProgressOwner(c.ID)
			s.leaves.cleanupBackgroundOwner(c.ID)
		}
	}

	c.closeHelloCh()
	c.closeAnnounceCh()
	c.closeInfoCh()
	if c.apiConn != nil {
		c.apiConn.Close()
	}
	if c.process != nil {
		c.process.Kill()
	}
	if c.conn != nil {
		c.conn.Close()
	}
	s.pool.Remove(c)
}

func serviceCapabilityNames(svc *config.ServiceConfig, kind string) []string {
	if svc == nil {
		return nil
	}
	switch kind {
	case "tools":
		return svc.Tools
	case "plugins":
		return svc.Plugins
	case "macros":
		return svc.Macros
	default:
		return nil
	}
}

func (s *Server) connectionConfiguredNames(c *Connection, kind string) []string {
	if c.launchedService == nil {
		return nil
	}
	return serviceCapabilityNames(c.launchedService, kind)
}

func (s *Server) fetchCapabilityInfo(c *Connection) {
	effectiveTools := effectiveSet(c.AnnouncedTools, s.connectionConfiguredNames(c, "tools"))
	effectivePlugins := effectiveSet(c.AnnouncedPlugins, s.connectionConfiguredNames(c, "plugins"))
	effectiveMacros := effectiveSet(c.AnnouncedMacros, s.connectionConfiguredNames(c, "macros"))

	c.chMu.Lock()
	newTools := subtractSet(effectiveTools, c.requestedTools)
	newPlugins := subtractSet(effectivePlugins, c.requestedPlugins)
	newMacros := subtractSet(effectiveMacros, c.requestedMacros)
	c.requestedTools = effectiveTools
	c.requestedPlugins = effectivePlugins
	c.requestedMacros = effectiveMacros

	toolRequestID := c.trackCapabilityInfoRequestLocked("tool", len(newTools) > 0)
	pluginRequestID := c.trackCapabilityInfoRequestLocked("plugin", len(newPlugins) > 0)
	macroRequestID := c.trackCapabilityInfoRequestLocked("macro", len(newMacros) > 0)
	if c.capabilityInfoReadyLocked() {
		if c.infoCh != nil {
			close(c.infoCh)
			c.infoCh = nil
		}
		c.chMu.Unlock()
		return
	}
	if c.infoCh == nil {
		c.infoCh = make(chan struct{})
	}
	c.chMu.Unlock()

	if toolRequestID != "" {
		_ = c.apiConn.SendToolInfoRequest(context.Background(), newTools, toolRequestID)
	}
	if pluginRequestID != "" {
		_ = c.apiConn.SendPluginInfoRequest(context.Background(), newPlugins, pluginRequestID)
	}
	if macroRequestID != "" {
		_ = c.apiConn.SendMacroInfoRequest(context.Background(), newMacros, macroRequestID)
	}
}

// trackCapabilityInfoRequestLocked records one correlated metadata request.
// chMu must be held by the caller. A category can have several in-flight
// requests after later cumulative announces; each must respond before startup
// metadata readiness is complete.
func (c *Connection) trackCapabilityInfoRequestLocked(kind string, needed bool) string {
	if !needed {
		return ""
	}
	c.capabilityInfoSeq++
	requestID := fmt.Sprintf("%si_%s_%d", kind[:1], c.ID, c.capabilityInfoSeq)
	var pending *map[string]struct{}
	switch kind {
	case "tool":
		pending = &c.pendingToolInfo
	case "plugin":
		pending = &c.pendingPluginInfo
	case "macro":
		pending = &c.pendingMacroInfo
	default:
		panic("unknown capability info kind: " + kind)
	}
	if *pending == nil {
		*pending = make(map[string]struct{})
	}
	(*pending)[requestID] = struct{}{}
	return requestID
}

// capabilityInfoReadyLocked reports whether every metadata request generated
// for the connection's current cumulative capability set has replied. chMu
// must be held by the caller.
func (c *Connection) capabilityInfoReadyLocked() bool {
	return len(c.pendingToolInfo) == 0 && len(c.pendingPluginInfo) == 0 && len(c.pendingMacroInfo) == 0
}

func subtractSet(full, already []string) []string {
	seen := make(map[string]bool, len(already))
	for _, name := range already {
		seen[name] = true
	}
	var out []string
	for _, name := range full {
		if !seen[name] {
			out = append(out, name)
		}
	}
	return out
}

func effectiveSet(announced, configNames []string) []string {
	seen := make(map[string]bool)
	var out []string
	for _, name := range announced {
		if !seen[name] {
			seen[name] = true
			out = append(out, name)
		}
	}
	for _, name := range configNames {
		if !seen[name] {
			seen[name] = true
			out = append(out, name)
		}
	}
	return out
}

func (s *Server) SendToLeaf(leafID string, send func(*ezagentapi.Conn) error) {
	s.mu.RLock()
	connections := make([]*Connection, 0, len(s.subscriptions[leafID]))
	for connID := range s.subscriptions[leafID] {
		if c, ok := s.connections[connID]; ok {
			connections = append(connections, c)
		}
	}
	s.mu.RUnlock()
	for _, c := range connections {
		send(c.apiConn)
	}
}

// loadedOrFollowedLeafIDs returns only leaves with process-local runtime state
// or a current subscriber. Dormant leaves reconcile trust on their next
// snapshot/config sync instead of being eagerly loaded by a decision fan-out.
func (s *Server) loadedOrFollowedLeafIDs() []string {
	seen := make(map[string]struct{})
	if s.leaves != nil {
		for leafID := range s.leaves.agentEntries() {
			seen[leafID] = struct{}{}
		}
	}
	s.mu.RLock()
	for leafID, subscribers := range s.subscriptions {
		if len(subscribers) != 0 {
			seen[leafID] = struct{}{}
		}
	}
	s.mu.RUnlock()
	leafIDs := make([]string, 0, len(seen))
	for leafID := range seen {
		leafIDs = append(leafIDs, leafID)
	}
	sort.Strings(leafIDs)
	return leafIDs
}

func (s *Server) switchLeaf(c *Connection, newLeafID string) bool {
	return s.switchLeafVersion(c, newLeafID, 0, false)
}

func (s *Server) switchLeafVersion(c *Connection, newLeafID string, version uint64, ordered bool) bool {
	return s.switchLeafVersionCwd(c, newLeafID, version, ordered, nil)
}

func (s *Server) switchLeafVersionCwd(c *Connection, newLeafID string, version uint64, ordered bool, cwd *string) bool {
	c.selectionMu.Lock()
	defer c.selectionMu.Unlock()
	s.mu.Lock()
	// Startup subscriptions may have waited on a leaf gate across disconnect.
	if s.connections[c.ID] != c {
		s.mu.Unlock()
		return false
	}
	oldLeafID := c.LeafID
	if ordered && version < c.selectionVersion {
		// A superseded subscription can still carry an ordered cwd update.
		if cwd != nil {
			c.Cwd = *cwd
		}
		s.mu.Unlock()
		return false
	}
	if ordered {
		c.selectionVersion = version
	}
	if cwd != nil {
		c.Cwd = *cwd
	}
	if oldLeafID != "" {
		if subs, ok := s.subscriptions[oldLeafID]; ok {
			delete(subs, c.ID)
			if len(subs) == 0 {
				delete(s.subscriptions, oldLeafID)
			}
		}
	}
	if s.subscriptions[newLeafID] == nil {
		s.subscriptions[newLeafID] = make(map[string]struct{})
	}
	s.subscriptions[newLeafID][c.ID] = struct{}{}
	c.LeafID = newLeafID
	s.mu.Unlock()

	// A project-scoped on_start service becomes relevant when a leaf joins the
	// root cwd. Activation is best effort and must not delay the switch path.
	if s.pool != nil && s.config != nil {
		go s.startOnStartServicesForLeaf(newLeafID)
	}
	return true
}

func (s *Server) isCurrentConnection(c *Connection) bool {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.connections[c.ID] == c
}

// sendLeafSnapshot replays one subscribed destination. The leaf gate protects
// existence and fresh snapshot enqueue; the Agent stream barrier keeps later
// terminal events behind the captured running replay. The gate is released
// before the bounded replay frames are enqueued.
func (s *Server) sendLeafSnapshot(c *Connection, leafID string) {
	s.leaves.replaySnapshot(leafID, func() bool { return s.isCurrentConnection(c) }, func(update protocol.LeafUpdated) bool {
		return s.enqueueLeafSnapshotLocked(update, c)
	}, func(replay leafStreamReplay) {
		s.enqueueLeafReplay(c, leafID, replay)
	})
}

// switchLeafWithSnapshot makes validation, subscription installation,
// acknowledgement, and authoritative snapshot enqueue deletion-exclusive. It
// acquires the stream barrier before exposing the new subscription, so a live
// event cannot enter the connection ahead of its replay. Only the acknowledgement
// and one snapshot are enqueued under the leaf gate; stream/history replay runs
// after releasing it.
func (s *Server) switchLeafWithSnapshot(c *Connection, leafID, requestID string, acknowledge bool) bool {
	before := func() bool {
		if !s.switchLeaf(c, leafID) {
			return false
		}
		if acknowledge {
			if err := c.apiConn.SendLeafSwitched(context.Background(), leafID, requestID); err != nil {
				_ = c.apiConn.Close()
				return false
			}
		}
		return true
	}
	return s.leaves.replaySnapshot(leafID, before, func(update protocol.LeafUpdated) bool {
		return s.enqueueLeafSnapshotLocked(update, c)
	}, func(replay leafStreamReplay) {
		s.enqueueLeafReplay(c, leafID, replay)
	})
}

func (s *Server) enqueueLeafReplay(c *Connection, leafID string, replay leafStreamReplay) bool {
	if !s.isCurrentConnection(c) {
		return false
	}
	send := func(err error) bool {
		if err == nil {
			return true
		}
		_ = c.apiConn.Close()
		return false
	}
	if snap := replay.Stream; snap != nil {
		if !send(c.apiConn.SendAgentStart(context.Background(), leafID)) ||
			!send(c.apiConn.SendTurnStart(context.Background(), leafID, snap.TurnID)) ||
			!send(c.apiConn.SendMessageStart(context.Background(), leafID, snap.TurnID, []protocol.ContentBlock{})) {
			return false
		}
		if snap.Thinking != "" && !send(c.apiConn.SendMessageUpdate(context.Background(), leafID, snap.TurnID, "reasoning_delta", protocol.TextDelta{Type: "reasoning_delta", Text: snap.Thinking}, 0)) {
			return false
		}
		if snap.Content != "" && !send(c.apiConn.SendMessageUpdate(context.Background(), leafID, snap.TurnID, "text_delta", protocol.TextDelta{Type: "text_delta", Text: snap.Content}, 0)) {
			return false
		}
	}
	for _, turn := range replay.Turns {
		if !send(c.apiConn.SendTurnContent(context.Background(), turn)) {
			return false
		}
	}
	return true
}

func (s *Server) dropFeedVersion(c *Connection, leafID string, version uint64, ordered bool) bool {
	if leafID == "" {
		return false
	}
	c.selectionMu.Lock()
	defer c.selectionMu.Unlock()
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.connections[c.ID] != c || c.LeafID != leafID || (ordered && version < c.selectionVersion) {
		return false
	}
	if ordered {
		c.selectionVersion = version
	}
	if subs, ok := s.subscriptions[leafID]; ok {
		delete(subs, c.ID)
		if len(subs) == 0 {
			delete(s.subscriptions, leafID)
		}
	}
	c.LeafID = ""
	return true
}

func (s *Server) RouteInformational(leafID, connID string, ev interface{}) error {
	s.mu.RLock()
	c, ok := s.connections[connID]
	s.mu.RUnlock()
	if !ok || c == nil {
		return nil
	}
	info, ok := ev.(protocol.Informational)
	if !ok {
		return fmt.Errorf("unsupported informational event %T", ev)
	}
	return c.apiConn.SendInformational(context.Background(), info)
}

// NotifyRunCompleted preserves the public RunNotifier API. Leaf operations own
// completion publication ordering.
func (s *Server) NotifyRunCompleted(completion agent.RunCompletion) {
	s.leaves.NotifyRunCompleted(completion)
}

func (s *Server) enqueuePromptCompleted(completion agent.RunCompletion) {
	if s.beforeRunCompletionPublication != nil {
		s.beforeRunCompletionPublication(completion)
	}
	s.mu.RLock()
	c := s.connections[completion.OriginConnID]
	s.mu.RUnlock()
	if c != nil {
		err := c.apiConn.SendPromptCompleted(context.Background(), completion.LeafID, completion.RootID, completion.Reason, completion.Message, completion.RequestID)
		if completion.Reason == "abort" {
			outcome := incident.Cancel
			if err != nil {
				outcome = incident.Fail
			}
			s.audit.emit("abort_completion", incident.Completed, outcome, safeIDs(completion.LeafID, completion.RequestID), false)
		}
	}
}

func (s *Server) enqueueLeafRewound(connID, leafID, oldTipTurnID, newTipTurnID string, replay bool, requestID string) {
	s.mu.RLock()
	c := s.connections[connID]
	s.mu.RUnlock()
	if c != nil {
		_ = c.apiConn.SendLeafRewound(context.Background(), leafID, oldTipTurnID, newTipTurnID, replay, requestID)
	}
}

func (s *Server) Stop() {
	s.stopOnce.Do(func() {
		defer s.audit.repanic("stop_boundary", incident.Data{})
		if s.storage != nil {
			s.storage.FreezeLeafAlerts()
		}
		if s.shutdownComplete != nil {
			defer close(s.shutdownComplete)
		}
		// Suppress follow-up admission and lifecycle notifications before child
		// shutdown can release provider ownership or wake completion waiters.
		if s.leaves != nil {
			s.leaves.mu.Lock()
			s.leaves.closing = true
			s.leaves.mu.Unlock()
		}
		_, cancelInvocations := s.claimToolInvocations(func(*toolInvocation) bool { return true })
		cancelInvocations()
		// Exclude new and in-flight child publication before shutdown is visible.
		endPool := s.audit.phase("pool_close", shutdownPhaseBudget, incident.Data{}, true)
		s.pool.Shutdown()
		endPool(false)
		endAdmission := s.audit.phase("admission_close", shutdownPhaseBudget, incident.Data{}, true)
		s.admissionSendMu.Lock()
		close(s.shutdown)
		s.admissionSendMu.Unlock()
		endAdmission(false)
		s.mu.RLock()
		backgroundConnections := make([]*Connection, 0, len(s.connections))
		for _, c := range s.connections {
			backgroundConnections = append(backgroundConnections, c)
		}
		s.mu.RUnlock()
		for _, c := range backgroundConnections {
			c.chMu.Lock()
			c.backgroundClosed = true
			c.chMu.Unlock()
			c.backgroundRPCs.Wait()
		}
		if s.leaves != nil {
			endAgents := s.audit.phase("agents_close", shutdownPhaseBudget, incident.Data{}, true)
			s.leaves.closeAllAgents()
			endAgents(false)
		}
		endRegistry := s.audit.phase("registry_close", shutdownPhaseBudget, incident.Data{}, true)
		s.registry.Shutdown()
		endRegistry(false)
		endTransport := s.audit.phase("transport_close", shutdownPhaseBudget, incident.Data{}, true)
		transportFailed := false
		if s.listener != nil {
			if err := s.listener.Close(); err != nil && !errors.Is(err, net.ErrClosed) {
				transportFailed = true
			}
		}
		s.mu.Lock()
		for _, c := range s.connections {
			if c.conn != nil {
				if err := c.conn.Close(); err != nil && !errors.Is(err, net.ErrClosed) && !errors.Is(err, io.ErrClosedPipe) {
					transportFailed = true
				}
			}
		}
		s.connections = make(map[string]*Connection)
		s.mu.Unlock()
		s.pool.Shutdown()
		endTransport(transportFailed)
	})
}

func (s *Server) evictIdleAgents() {
	ticker := time.NewTicker(1 * time.Minute)
	defer ticker.Stop()
	for {
		select {
		case <-s.shutdown:
			return
		case <-ticker.C:
			hasSubscribers := func(leafID string) bool {
				s.mu.RLock()
				subscribed := len(s.subscriptions[leafID]) > 0
				s.mu.RUnlock()
				return subscribed
			}
			if count := s.leaves.evictIdle(time.Now(), agentIdleEvict, hasSubscribers); count > 0 {
				slog.Info("evicting idle agents", "count", count)
			}
		}
	}
}

func (s *Server) localizedToolNames(cfg *config.Config) []string {
	seen := make(map[string]bool)
	s.registry.mu.RLock()
	for name := range s.registry.tools {
		seen[name] = true
	}
	s.registry.mu.RUnlock()
	if cfg.Services != nil {
		for _, dc := range cfg.Services {
			for _, name := range dc.Tools {
				seen[name] = true
			}
		}
	}
	for _, name := range cfg.Defaults.Tools {
		seen[name] = true
	}
	out := make([]string, 0, len(seen))
	for name := range seen {
		out = append(out, name)
	}
	sort.Strings(out)
	return out
}

func (s *Server) localizedPluginNames(cfg *config.Config) []string {
	seen := make(map[string]bool)
	s.registry.mu.RLock()
	for name := range s.registry.plugins {
		seen[name] = true
	}
	s.registry.mu.RUnlock()
	if cfg.Services != nil {
		for _, dc := range cfg.Services {
			for _, name := range dc.Plugins {
				seen[name] = true
			}
		}
	}
	for _, name := range cfg.Defaults.Plugins {
		seen[name] = true
	}
	out := make([]string, 0, len(seen))
	for name := range seen {
		out = append(out, name)
	}
	sort.Strings(out)
	return out
}

func triggerMatches(triggers []string, filter string) bool {
	for _, t := range triggers {
		if t == filter {
			return true
		}
	}
	return false
}

func (s *Server) localizedMacroNames(cfg *config.Config) []string {
	seen := make(map[string]bool)
	s.registry.mu.RLock()
	for name := range s.registry.macros {
		seen[name] = true
	}
	s.registry.mu.RUnlock()
	if cfg.Services != nil {
		for _, dc := range cfg.Services {
			for _, name := range dc.Macros {
				seen[name] = true
			}
		}
	}
	if cfg.Defaults.Triggers != nil {
		for _, names := range cfg.Defaults.Triggers {
			for _, name := range names {
				seen[name] = true
			}
		}
	}
	out := make([]string, 0, len(seen))
	for name := range seen {
		out = append(out, name)
	}
	sort.Strings(out)
	return out
}

func (s *Server) serviceSpawnCallbacks() SpawnCallbacks {
	return SpawnCallbacks{
		connectionID: s.connectionID,
		RegisterConn: func(c *Connection) {
			s.mu.Lock()
			s.connections[c.ID] = c
			s.mu.Unlock()
		},
		CleanupConn: func(c *Connection) {
			s.cleanupConnection(c)
		},
		ServiceOptions: func(c *Connection) ezagentapi.ServiceOptions {
			return s.directConnServiceOptions(c)
		},
		CredentialEnvironmentNames: func() []string {
			s.mu.RLock()
			cfg := s.config
			s.mu.RUnlock()
			if cfg == nil {
				return nil
			}
			return cfg.CredentialEnvironmentNames()
		},
	}
}

func (s *Server) startOnStartServicesForLeaf(leafID string) {
	leaf, err := s.storage.GetLeaf(leafID)
	if err != nil || leaf == nil {
		return
	}
	root, err := s.storage.GetRoot(leaf.RootID)
	if err != nil || root == nil {
		return
	}
	s.startOnStartServices(s.LocalizedConfig(root.Cwd), root.Cwd)
}

func (s *Server) startOnStartServices(cfg *config.Config, scope string) {
	if cfg == nil {
		return
	}
	for name, serviceCfg := range cfg.Services {
		if !serviceCfg.OnStart {
			continue
		}
		name, serviceCfg := name, serviceCfg
		go func() {
			if scope != "global" && s.afterProjectOnStartAttempt != nil {
				defer s.afterProjectOnStartAttempt(name)
			}
			if err := s.pool.StartService(name, &serviceCfg, s.serviceSpawnCallbacks()); err != nil {
				slog.Warn("on_start service failed", "service", name, "scope", scope, "error", err)
			}
		}()
	}
}

func (s *Server) ensureDirectConn(connName string, dc *config.ServiceConfig) (*Connection, error) {
	return s.pool.GetOrSpawn(connName, dc, s.serviceSpawnCallbacks())
}

func (s *Server) handleShutdownTyped(c *Connection, shutdown protocol.Shutdown) error {
	s.Stop()
	return nil
}

func (s *Server) handleAbortTyped(c *Connection, cmd protocol.Abort) error {
	return s.handleAbortContext(context.Background(), c, cmd)
}

func (s *Server) handleAbortContext(ctx context.Context, c *Connection, cmd protocol.Abort) error {
	data := safeIDs(cmd.LeafID, cmd.RequestID)
	defer s.audit.repanic("abort_boundary", data)
	done := s.audit.operationPhase("abort_rpc", serviceWaitBudget, data, true)
	var operationErr, deliveryErr error
	defer func() { done(requestPhaseError(operationErr, deliveryErr)) }()
	if cmd.LeafID == "" {
		operationErr = session.ErrLeafNotFound
		deliveryErr = s.audit.response("abort_response", data, c.apiConn.SendError(ctx, "leaf_not_found", "leaf_id is required", cmd.RequestID))
		return nil
	}
	operationErr = s.leaves.abort(leafAbortRequest{
		Context: ctx, LeafID: cmd.LeafID, RequestID: cmd.RequestID,
		PublishAccepted: func(result *protocol.AbortReceived) {
			s.audit.emit("abort_rpc", incident.Decision, incident.Cancel, data, false)
			deliveryErr = s.audit.response("abort_response", data, c.apiConn.SendAbortReceived(ctx, result.LeafID, result.RequestID))
		},
		PublishFailure: func(err error) {
			s.audit.emit("abort_rpc", incident.Decision, incident.Stop, data, false)
			deliveryErr = s.audit.response("abort_response", data, c.apiConn.SendError(ctx, leafOperationErrorCode(err, "nothing_to_abort"), leafOperationErrorMessage(err), cmd.RequestID))
		},
	})
	return nil
}

func (s *Server) handleAddToolTyped(c *Connection, cmd protocol.AddTool) error {
	if cmd.LeafID == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "leaf_id is required", cmd.RequestID)
		return nil
	}
	if cmd.ToolName == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "tool_name is required", cmd.RequestID)
		return nil
	}

	_ = s.leaves.addTool(cmd.LeafID, cmd.ToolName, func() {
		_ = c.apiConn.SendToolAdded(context.Background(), cmd.LeafID, cmd.ToolName, cmd.RequestID)
	}, func(err error) {
		_ = c.apiConn.SendError(context.Background(), leafOperationErrorCode(err, "provider_error"), err.Error(), cmd.RequestID)
	})
	return nil
}

func (s *Server) handleCreateLeafTyped(c *Connection, cmd protocol.CreateLeaf) error {
	return s.handleCreateLeafContext(context.Background(), c, cmd)
}

func (s *Server) handleCreateLeafContext(ctx context.Context, c *Connection, cmd protocol.CreateLeaf) error {
	state, hasState := ctx.Value(connectionContextKey{}).(connectionContext)
	if cmd.Cwd == "" && cmd.SourceTurnID == "" && hasState {
		cmd.Cwd, _ = state.cwd.wait(ctx)
	}
	if (cmd.Cwd == "" && cmd.SourceTurnID == "") || (cmd.Cwd != "" && cmd.SourceTurnID != "") {
		c.apiConn.SendError(context.Background(), "parse_error", "exactly one of cwd or source_turn_id is required", cmd.RequestID)
		return nil
	}
	if cmd.Cwd != "" {
		if err := validateRootCwd(cmd.Cwd); err != nil {
			_ = c.apiConn.SendError(context.Background(), "parse_error", err.Error(), cmd.RequestID)
			return nil
		}
	}
	var leafID string
	var subscribed bool
	_ = s.leaves.createLeaf(leafCreateRequest{
		Command:       cmd,
		ResolveConfig: s.resolveConfigForCwd,
		Subscribe:     func(id string) { subscribed = s.switchLeafVersion(c, id, state.version, hasState) },
		PublishCreated: func(rootID, id, model string, isTemp bool) {
			leafID = id
			_ = c.apiConn.SendLeafCreated(context.Background(), rootID, id, model, isTemp, cmd.RequestID)
		},
		PublishSnapshot: func(update protocol.LeafUpdated) bool {
			if !subscribed {
				return false
			}
			return s.enqueueSubscribedSnapshot(c, update)
		},
		PublishReplay: func(replay leafStreamReplay) { s.enqueueSubscribedReplay(c, leafID, replay) },
		PublishFailure: func(err error) {
			_ = c.apiConn.SendError(context.Background(), leafOperationErrorCode(err, "provider_error"), leafOperationErrorMessage(err), cmd.RequestID)
		},
	})
	return nil
}

func (s *Server) handleDeleteLeafTyped(c *Connection, cmd protocol.DeleteLeaf) error {
	if cmd.LeafID == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "leaf_id is required", cmd.RequestID)
		return nil
	}
	_ = s.leaves.deleteLeaf(leafDeleteRequest{
		LeafID: cmd.LeafID,
		PublishDeleted: func(turnID string) {
			_ = c.apiConn.SendLeafDeleted(context.Background(), cmd.LeafID, turnID, cmd.RequestID)
		},
		PublishFailure: func(err error) {
			message := leafOperationErrorMessage(err)
			if errors.Is(err, errLeafDeleteBusy) {
				message = fmt.Sprintf("leaf %s is in use", cmd.LeafID)
			}
			_ = c.apiConn.SendError(context.Background(), leafOperationErrorCode(err, "leaf_not_found"), message, cmd.RequestID)
		},
	})
	return nil
}

func (s *Server) handleRewindLeafTyped(c *Connection, cmd protocol.RewindLeaf) error {
	if cmd.LeafID == "" {
		_ = c.apiConn.SendError(context.Background(), "parse_error", "leaf_id is required", cmd.RequestID)
		return nil
	}
	if cmd.CurrentTipTurnID == "" {
		_ = c.apiConn.SendError(context.Background(), "parse_error", "current_tip_turn_id is required", cmd.RequestID)
		return nil
	}
	if !cmd.HasNewTipTurnID() {
		_ = c.apiConn.SendError(context.Background(), "parse_error", "new_tip_turn_id is required (use an empty string for the root boundary)", cmd.RequestID)
		return nil
	}

	_ = s.leaves.rewind(context.Background(), rewindLeafRequest{
		RequesterLive: func() bool { return s.isCurrentConnection(c) },
		LeafID:        cmd.LeafID, CurrentTipTurnID: cmd.CurrentTipTurnID,
		NewTipTurnID: cmd.NewTipTurnID, Replay: cmd.Replay,
		Origin: c, RequestID: cmd.RequestID,
		ResolveConfig: func(leaf *session.Leaf) *config.Config {
			return s.resolveConfigFromLeaf(c, leaf)
		},
		PublishFailure: func(err error) {
			code, message := "provider_error", err.Error()
			switch {
			case errors.Is(err, errInvalidRewindModel):
				code = "invalid_model"
			case errors.Is(err, errRewindAdmissionBusy):
				code, message = "leaf_busy", fmt.Sprintf("leaf %s is busy", cmd.LeafID)
			case errors.Is(err, agent.ErrLeafBusy), errors.Is(err, agent.ErrAgentClosed):
				code = "leaf_busy"
			case errors.Is(err, session.ErrLeafTipChanged):
				code = "turn_conflict"
			case errors.Is(err, session.ErrRewindTargetNotAncestor):
				code = "invalid_rewind_target"
			case strings.HasPrefix(err.Error(), "leaf not found:"):
				code = "leaf_not_found"
			}
			_ = c.apiConn.SendError(context.Background(), code, message, cmd.RequestID)
		},
	})
	return nil
}

func (s *Server) handleDropFeedTyped(c *Connection, cmd protocol.DropFeed) error {
	return s.handleDropFeedContext(context.Background(), c, cmd)
}

func (s *Server) handleDropFeedContext(ctx context.Context, c *Connection, cmd protocol.DropFeed) error {
	if cmd.LeafID == "" {
		c.apiConn.SendError(context.Background(), "leaf_not_found", "leaf_id is required", cmd.RequestID)
		return nil
	}
	state, ordered := ctx.Value(connectionContextKey{}).(connectionContext)
	if !s.dropFeedVersion(c, cmd.LeafID, state.version, ordered) {
		c.apiConn.SendError(context.Background(), "leaf_not_found", "can only drop feed on current leaf", cmd.RequestID)
		return nil
	}
	c.apiConn.SendFeedDropped(context.Background(), cmd.LeafID, cmd.RequestID)

	return nil
}

func (s *Server) handleGetLeafConfigTyped(c *Connection, cmd protocol.GetLeafConfig) error {
	if cmd.LeafID == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "leaf_id is required", cmd.RequestID)
		return nil
	}
	if cmd.Key == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "key is required", cmd.RequestID)
		return nil
	}
	value, err := s.storage.GetLeafConfig(cmd.LeafID, cmd.Key)
	if err != nil {
		c.apiConn.SendError(context.Background(), "provider_error", err.Error(), cmd.RequestID)
		return nil
	}
	c.apiConn.SendLeafConfigValue(context.Background(), cmd.Key, value, cmd.RequestID)

	return nil
}

func (s *Server) handleGetToolInfoTyped(c *Connection, cmd protocol.GetToolInfo) error {
	return s.handleGetToolInfoContext(context.Background(), c, cmd)
}

func (s *Server) handleGetToolInfoContext(ctx context.Context, c *Connection, cmd protocol.GetToolInfo) error {

	names := cmd.Names
	if len(names) == 0 {
		if cmd.LeafID == "" {
			c.apiConn.SendError(context.Background(), "bad_request", "leaf_id or names is required", cmd.RequestID)
			return nil
		}
		value, err := s.storage.GetLeafConfig(cmd.LeafID, "active_tools")
		if err == nil && value != "" {
			_ = json.Unmarshal([]byte(value), &names)
		}
		if names == nil {
			names = s.resolveConfig(c, cmd.LeafID).Defaults.Tools
		}
	}

	seen := make(map[string]bool, len(names))
	unique := make([]string, 0, len(names))
	for _, name := range names {
		name = strings.TrimSpace(name)
		if name == "" || seen[name] {
			continue
		}
		seen[name] = true
		unique = append(unique, name)
	}

	c.apiConn.SendToolInfoValue(context.Background(), s.ipc.ResolveToolInfoContext(ctx, unique), cmd.RequestID)

	return nil
}

func (s *Server) handleGetTurnTyped(c *Connection, cmd protocol.GetTurn) error {
	if cmd.TurnID == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "turn_id is required", cmd.RequestID)
		return nil
	}

	turn, err := s.storage.GetTurn(cmd.TurnID)
	if err != nil {
		c.apiConn.SendError(context.Background(), "turn_not_found", err.Error(), cmd.RequestID)
		return nil
	}

	tc := turn.ToTurnContent()
	tc.RequestID = cmd.RequestID
	c.apiConn.SendTurnContent(context.Background(), tc)

	return nil
}

func (s *Server) handleLeafStatsTyped(c *Connection, cmd protocol.LeafStats) error {
	return s.handleLeafStatsContext(context.Background(), c, cmd)
}

func (s *Server) handleLeafStatsContext(ctx context.Context, c *Connection, cmd protocol.LeafStats) (result error) {
	data := safeIDs(cmd.LeafID, cmd.RequestID)
	defer s.audit.repanic("stats_boundary", data)
	done := s.audit.operationPhase("stats_rpc", serviceWaitBudget, data, false)
	var operationErr error
	defer func() { done(requestPhaseError(operationErr, result)) }()
	if cmd.LeafID == "" {
		operationErr = session.ErrLeafNotFound
		return s.audit.response("stats_response", data, c.apiConn.SendError(ctx, "parse_error", "leaf_id is required", cmd.RequestID))
	}
	return s.leaves.leafStatsContext(ctx, cmd.LeafID, cmd.RequestID, func(stats protocol.LeafStatsResponse) error {
		if hook := s.beforeLeafStatsEnqueue; hook != nil {
			hook(stats)
		}
		s.audit.emit("stats_rpc", incident.Decision, incident.Continue, data, false)
		return s.audit.response("stats_response", data, c.apiConn.SendLeafStats(ctx, stats, cmd.RequestID))
	}, func(err error) error {
		operationErr = err
		s.audit.emit("stats_rpc", incident.Decision, incident.Fail, data, false)
		return s.audit.response("stats_response", data, c.apiConn.SendError(ctx, "leaf_not_found", err.Error(), cmd.RequestID))
	})
}

func (s *Server) handleListHistoryTyped(c *Connection, cmd protocol.ListHistory) error {
	if cmd.LeafID == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "leaf_id is required", cmd.RequestID)
		return nil
	}

	tipTurnID, results, err := s.storage.ListHistorySnapshot(cmd.LeafID)
	if err != nil {
		c.apiConn.SendError(context.Background(), "provider_error", err.Error(), cmd.RequestID)
		return nil
	}

	turns := make([]protocol.TurnSummary, len(results))
	for i, r := range results {
		turns[i] = protocol.TurnSummary{
			ID:    r.ID,
			Kind:  r.Kind,
			State: r.State,
			Seq:   r.Seq,
		}
	}

	c.apiConn.SendHistoryList(context.Background(), cmd.LeafID, tipTurnID, turns, cmd.RequestID)

	return nil
}

func (s *Server) handleListTurnTreeTyped(c *Connection, cmd protocol.ListTurnTree) error {
	if cmd.RootID == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "root_id is required", cmd.RequestID)
		return nil
	}

	results, err := s.storage.ListTurnTree(cmd.RootID)
	if err != nil {
		code := "provider_error"
		if strings.HasPrefix(err.Error(), "root not found:") {
			code = "root_not_found"
		}
		c.apiConn.SendError(context.Background(), code, err.Error(), cmd.RequestID)
		return nil
	}

	turns := make([]protocol.TurnTreeNode, len(results))
	for i, result := range results {
		turns[i] = protocol.TurnTreeNode{
			ID: result.ID, ParentID: result.ParentID, Kind: result.Kind,
			State: result.State, Seq: result.Seq, Timestamp: result.Timestamp,
			Model: result.Model, Provider: result.Provider,
			StopReason: result.StopReason, ToolName: result.ToolName,
		}
	}
	c.apiConn.SendTurnTreeList(context.Background(), cmd.RootID, turns, cmd.RequestID)
	return nil
}

func (s *Server) handleListLeavesTyped(c *Connection, cmd protocol.ListLeaves) error {

	var rootID *string
	if cmd.RootID != "" {
		rootID = &cmd.RootID
	}

	leaves, err := s.storage.ListLeavesWithMetadata(rootID, cmd.Cwd, cmd.MetadataKeys)
	if err != nil {
		c.apiConn.SendError(context.Background(), "provider_error", err.Error(), cmd.RequestID)
		return nil
	}

	leafInfos := make([]protocol.LeafInfo, len(leaves))
	for i, l := range leaves {
		status := "unloaded"
		if ag := s.leaves.resolveOpenAgent(l.ID); ag != nil {
			status = leafPresenceStateForWire(ag.State())
		}
		status = s.leaves.backgroundState(l.ID, status)
		leafInfos[i] = protocol.LeafInfo{
			ID:        l.ID,
			RootID:    l.RootID,
			Name:      l.Name,
			TurnID:    l.TurnID,
			Model:     l.Model,
			Status:    status,
			UpdatedAt: l.UpdatedAt,
			IsTemp:    l.IsTemp,
			Metadata:  l.Metadata,
		}
	}

	c.apiConn.SendLeafList(context.Background(), leafInfos, cmd.RequestID)

	return nil
}

func (s *Server) handleListMacrosTyped(c *Connection, cmd protocol.ListMacros) error {
	return s.handleListMacrosContext(context.Background(), c, cmd)
}

func (s *Server) handleListMacrosContext(ctx context.Context, c *Connection, cmd protocol.ListMacros) error {

	cfg := s.resolveConfig(c, cmd.LeafID)
	names := s.localizedMacroNames(cfg)
	var infos []protocol.MacroInfo
	if cmd.Filter == "" {
		// Ordinary listing is a cache-only inventory operation. Descriptions and
		// triggers are optional metadata, so a provider that has not supplied
		// them must not hold the client RPC open.
		infos = make([]protocol.MacroInfo, 0, len(names))
		for _, name := range names {
			if info := s.registry.ResolveMergedMacroInfo(name); info != nil {
				infos = append(infos, *info)
			}
		}
	} else {
		// Filtered discovery needs triggers and may actively resolve metadata.
		infos = s.ipc.ResolveMacroInfoContext(ctx, names)
	}
	for i := range infos {
		if infos[i].Timeout == "" {
			infos[i].Timeout = "5s"
		}
	}

	if cmd.Filter != "" {
		filtered := make([]protocol.MacroInfo, 0, len(infos))
		for _, info := range infos {
			if triggerMatches(info.Triggers, cmd.Filter) {
				filtered = append(filtered, info)
			}
		}
		infos = filtered
	}

	c.apiConn.SendMacroList(context.Background(), infos, cmd.RequestID)

	return nil
}

func (s *Server) handleListModelsTyped(c *Connection, cmd protocol.ListModels) error {

	cfg := s.resolveConfig(c, cmd.LeafID)
	models := cfg.AllModels()

	entries := make([]protocol.ModelEntry, 0, len(models))
	for _, ref := range models {
		providerName, modelID, _ := cfg.ParseModel(ref)
		pc, _ := cfg.GetProvider(providerName)
		entry := protocol.ModelEntry{Ref: ref}
		if m, ok := pc.FindModel(modelID); ok {
			entry.ThinkingLevels = m.ThinkingLevels
			entry.ZDRSupported = m.ZDRSupported
			if m.MaxContext > 0 {
				entry.MaxContext = m.MaxContext
			}
			if m.MaxTokens > 0 {
				entry.MaxTokens = m.MaxTokens
			}
		}
		if entry.MaxContext == 0 {
			entry.MaxContext = pc.MaxContext
		}
		if entry.MaxTokens == 0 {
			entry.MaxTokens = pc.MaxTokens
		}
		entries = append(entries, entry)
	}

	c.apiConn.SendModelList(context.Background(), entries, cmd.RequestID)

	return nil
}

func (s *Server) handleListPluginsTyped(c *Connection, cmd protocol.ListPlugins) error {

	cfg := s.resolveConfig(c, cmd.LeafID)

	c.apiConn.SendPluginList(context.Background(), s.localizedPluginNames(cfg), cmd.RequestID)

	return nil
}

func (s *Server) handleListProvidersTyped(c *Connection, cmd protocol.ListProviders) error {

	cfg := s.resolveConfig(c, cmd.LeafID)

	out := make([]protocol.ProviderListEntry, 0, len(cfg.Providers))
	for name, pc := range cfg.Providers {
		models := make([]protocol.ModelInfo, 0, len(pc.Models))
		for _, m := range pc.Models {
			models = append(models, protocol.ModelInfo{
				Name:           m.Name,
				MaxContext:     m.MaxContext,
				MaxTokens:      m.MaxTokens,
				ThinkingLevels: m.ThinkingLevels,
				ZDRSupported:   m.ZDRSupported,
			})
		}
		out = append(out, protocol.ProviderListEntry{
			Name:    name,
			Type:    pc.Type,
			BaseURL: pc.BaseURL,
			Models:  models,
		})
	}

	c.apiConn.SendProviderList(context.Background(), out, cmd.RequestID)

	return nil
}

func (s *Server) handleListQueuedTyped(c *Connection, cmd protocol.ListQueued) error {

	if cmd.LeafID == "" {
		c.apiConn.SendError(context.Background(), "leaf_not_found", "leaf_id is required", cmd.RequestID)
		return nil
	}

	if _, err := s.storage.GetLeaf(cmd.LeafID); err != nil {
		c.apiConn.SendError(context.Background(), "leaf_not_found", fmt.Sprintf("leaf not found: %s", cmd.LeafID), cmd.RequestID)
		return nil
	}

	ag := s.leaves.resolveOpenAgent(cmd.LeafID)
	if ag == nil {
		c.apiConn.SendError(context.Background(), "leaf_not_loaded", fmt.Sprintf("leaf not loaded: %s", cmd.LeafID), cmd.RequestID)
		return nil
	}

	messages, err := ag.ListQueued()
	if err != nil {
		c.apiConn.SendError(context.Background(), "provider_error", err.Error(), cmd.RequestID)
		return nil
	}

	c.apiConn.SendQueuedList(context.Background(), messages, cmd.RequestID)

	return nil
}

func (s *Server) handleListCwdTyped(c *Connection, cmd protocol.ListCwd) error {
	cwds, err := s.storage.ListCwds()
	if err != nil {
		return c.apiConn.SendError(context.Background(), "provider_error", err.Error(), cmd.RequestID)
	}
	return c.apiConn.SendCwdList(context.Background(), cwds, cmd.RequestID)
}

func (s *Server) handleListRootsTyped(c *Connection, cmd protocol.ListRoots) error {

	roots, err := s.storage.ListRoots()
	if err != nil {
		c.apiConn.SendError(context.Background(), "provider_error", err.Error(), cmd.RequestID)
		return nil
	}

	rootInfos := make([]protocol.RootInfo, len(roots))
	for i, r := range roots {
		rootInfos[i] = protocol.RootInfo{
			ID:         r.ID,
			Cwd:        r.Cwd,
			RootTurnID: r.RootTurnID,
			CreatedAt:  r.CreatedAt,
			UpdatedAt:  r.UpdatedAt,
			Config:     r.Config,
		}
	}

	c.apiConn.SendRootList(context.Background(), rootInfos, cmd.RequestID)

	return nil
}

func (s *Server) handleListToolsTyped(c *Connection, cmd protocol.ListTools) error {

	cfg := s.resolveConfig(c, cmd.LeafID)

	c.apiConn.SendToolList(context.Background(), s.localizedToolNames(cfg), cmd.RequestID)

	return nil
}

func (s *Server) handleMacroCallTyped(c *Connection, cmd protocol.MacroCall) error {
	return s.handleMacroCallContext(context.Background(), c, cmd)
}

func (s *Server) handleMacroCallContext(ctx context.Context, c *Connection, cmd protocol.MacroCall) error {

	if cmd.MacroName == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "macro_name is required", cmd.RequestID)
		return nil
	}

	if cmd.RequestID == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "request_id is required", "")
		return nil
	}

	// Macros do not resolve an LLM model, but direct macro definitions are part
	// of the effective config. Reload/localize from the persisted leaf root (or
	// requester cwd when there is no leaf) and pin that snapshot for dispatch.
	cfg := s.resolveConfig(c, cmd.LeafID)
	admission, err := s.ipc.AdmitMacroForConfig(cmd.MacroName, cfg)
	if err != nil {
		c.apiConn.SendError(context.Background(), "macro_not_found", err.Error(), cmd.RequestID)
		return nil
	}

	go func() {
		macroCallID, result, err := s.ipc.CallMacroAdmitted(ctx, admission, cmd.MacroName, cmd.ParamString, cmd.LeafID, c.ID)
		resp := protocol.MacroResult{
			Type:        "macro_result",
			MacroCallID: macroCallID,
			MacroName:   cmd.MacroName,
			RequestID:   cmd.RequestID,
		}
		if err != nil {
			resp.Result = err.Error()
			resp.IsError = true
		} else {
			resp.Result = result
		}
		c.apiConn.SendMacroCallResult(context.Background(), resp, resp.RequestID)
	}()

	return nil
}

func (s *Server) handleNotifyLeafTyped(c *Connection, cmd protocol.NotifyLeaf) error {
	if cmd.LeafID == "" {
		c.apiConn.SendError(context.Background(), "leaf_not_found", "leaf_id is required", "")
		return nil
	}
	level := cmd.Level
	if level == "" {
		level = "info"
	}
	message := cmd.Message
	if cmd.Title != "" {
		if message != "" {
			message = cmd.Title + ": " + message
		} else {
			message = cmd.Title
		}
	}
	if err := s.leaves.notifyLeaf(cmd.LeafID, level, message); err != nil {
		_ = c.apiConn.SendError(context.Background(), "leaf_not_found", err.Error(), "")
	}
	return nil
}

func validateUserTurnBoundary(turn protocol.PendingTurn) error {
	if err := protocol.ValidateUserPendingTurn(turn); err != nil {
		return err
	}
	return nil
}

func validateSteerTurnBoundary(turn protocol.PendingTurn) error {
	if turn.Kind == "" {
		return fmt.Errorf("steer turn is required")
	}
	if turn.Kind == session.KindUser {
		return validateUserTurnBoundary(turn)
	}
	if err := protocol.ValidateToolResultPendingTurn(turn); err != nil {
		return err
	}
	return nil
}

func validateToolResultBoundary(result protocol.ToolResult) error {
	if result.Turn.Kind == "" {
		return fmt.Errorf("tool_result turn is required")
	}
	if err := protocol.ValidateToolResultPendingTurn(result.Turn); err != nil {
		return err
	}
	return nil
}

func (s *Server) completeToolResult(c *Connection, expectedLeafID string, result protocol.ToolResult, onAdmitted func(*protocol.SteerAccepted, error)) error {
	result.Turn = withBackgroundProgress(result.Turn, false)
	initial := s.leaves.initialBackgroundResult(result.ToolCallID)
	if initial != nil {
		next := onAdmitted
		onAdmitted = func(accepted *protocol.SteerAccepted, err error) {
			if err == nil && accepted == nil {
				err = errors.New("initial background result was not admitted")
			}
			initial.settle(err)
			if next != nil {
				next(accepted, err)
			}
		}
	}
	pc, validationErr, ok := s.registry.ClaimPendingCallForConnValidated(result.ToolCallID, c.ID, func(pc *PendingCall) error {
		if expectedLeafID != "" && pc.LeafID != expectedLeafID {
			return fmt.Errorf("tool call does not belong to steer leaf")
		}
		if err := validateToolResultBoundary(result); err != nil {
			return err
		}
		if (result.Turn.ToolCallID != "" && result.Turn.ToolCallID != pc.ToolCallID) || (result.Turn.ToolName != "" && result.Turn.ToolName != pc.ToolName) {
			return fmt.Errorf("non-empty tool result inner tool_call_id and tool_name must match the outstanding call")
		}
		if initial != nil {
			initial.claim(usableBackgroundInitial(result.Turn))
		}
		return nil
	})
	if !ok {
		return fmt.Errorf("tool call is not outstanding or is owned by another connection")
	}
	s.wdMgr.Cancel(watchdog.Key{Type: "tool", ID: result.ToolCallID})
	if validationErr != nil {
		select {
		case pc.ResultCh <- ToolCallResult{Err: fmt.Errorf("invalid tool result: %w", validationErr)}:
		default:
		}
		return validationErr
	}
	result.Turn.Kind = session.KindToolResult
	result.Turn.ToolCallID = pc.ProviderToolCallID
	result.Turn.ToolName = pc.ToolName
	pc.publishResult(ToolCallResult{Result: result, OnAdmitted: onAdmitted})
	return nil
}

func (s *Server) handlePromptTyped(c *Connection, cmd protocol.Prompt) error {
	return s.handlePromptContext(context.Background(), c, cmd)
}

func (s *Server) handlePromptContext(ctx context.Context, c *Connection, cmd protocol.Prompt) error {
	data := safeIDs(cmd.LeafID, cmd.RequestID)
	defer s.audit.repanic("prompt_boundary", data)
	done := s.audit.operationPhase("prompt_rpc", serviceWaitBudget, data, false)
	var operationErr, deliveryErr error
	defer func() { done(requestPhaseError(operationErr, deliveryErr)) }()
	if cmd.LeafID == "" {
		operationErr = session.ErrLeafNotFound
		deliveryErr = s.audit.response("prompt_response", data, c.apiConn.SendError(ctx, "leaf_not_found", "leaf_id is required", cmd.RequestID))
		return nil
	}
	if err := validateUserTurnBoundary(cmd.Turn); err != nil {
		operationErr = expectedLeafRejection{err}
		deliveryErr = s.audit.response("prompt_response", data, c.apiConn.SendError(ctx, "parse_error", err.Error(), cmd.RequestID))
		return nil
	}
	operationErr = s.leaves.prompt(leafPromptRequest{
		RequesterLive: func() bool { return s.isCurrentConnection(c) },
		LeafID:        cmd.LeafID, ParentTurnID: cmd.ParentTurnID, Turn: cmd.Turn,
		RequestID: cmd.RequestID, Origin: c,
		ResolveConfig: func(leaf *session.Leaf) *config.Config { return s.resolveConfigFromLeaf(c, leaf) },
		AfterReserved: s.afterLeafAdmissionReserved,
		PublishAccepted: func(rootID, leafID string, turnIDs []string, tipTurnID string) {
			s.audit.emit("prompt_rpc", incident.Decision, incident.Continue, data, false)
			deliveryErr = s.audit.response("prompt_response", data, c.apiConn.SendPromptAccepted(ctx, rootID, leafID, turnIDs, tipTurnID, cmd.RequestID))
		},
		PublishFailure: func(err error) {
			s.audit.emit("prompt_rpc", incident.Decision, incident.Fail, data, false)
			message := err.Error()
			if errors.Is(err, errLeafModelInvalid) {
				message = leafOperationErrorMessage(err)
			}
			deliveryErr = s.audit.response("prompt_response", data, c.apiConn.SendError(ctx, leafOperationErrorCode(err, "provider_error"), message, cmd.RequestID))
		},
	})
	return nil
}

func (s *Server) handleRemoveToolTyped(c *Connection, cmd protocol.RemoveTool) error {
	if cmd.LeafID == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "leaf_id is required", cmd.RequestID)
		return nil
	}
	if cmd.ToolName == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "tool_name is required", cmd.RequestID)
		return nil
	}

	_ = s.leaves.removeTool(cmd.LeafID, cmd.ToolName, func() {
		_ = c.apiConn.SendToolRemoved(context.Background(), cmd.LeafID, cmd.ToolName, cmd.RequestID)
	}, func(err error) {
		_ = c.apiConn.SendError(context.Background(), leafOperationErrorCode(err, "provider_error"), err.Error(), cmd.RequestID)
	})
	return nil
}

func (s *Server) handleRenameLeafTyped(c *Connection, cmd protocol.RenameLeaf) error {
	return s.handleRenameLeafContext(context.Background(), c, cmd)
}

func (s *Server) handleRenameLeafContext(ctx context.Context, c *Connection, cmd protocol.RenameLeaf) error {
	data := safeIDs(cmd.LeafID, cmd.RequestID)
	defer s.audit.repanic("rename_boundary", data)
	done := s.audit.operationPhase("rename_rpc", serviceWaitBudget, data, false)
	poolDone := s.audit.poolWait(s.storage, data)
	defer poolDone()
	var operationErr, deliveryErr error
	defer func() { done(requestPhaseError(operationErr, deliveryErr)) }()
	if cmd.LeafID == "" {
		operationErr = session.ErrLeafNotFound
		deliveryErr = s.audit.response("rename_response", data, c.apiConn.SendError(ctx, "parse_error", "leaf_id is required", cmd.RequestID))
		return nil
	}
	operationErr = s.leaves.renameLeaf(cmd.LeafID, cmd.Name, func() {
		s.audit.emit("rename_rpc", incident.Decision, incident.Continue, data, false)
		deliveryErr = s.audit.response("rename_response", data, c.apiConn.SendLeafRenamed(ctx, cmd.LeafID, cmd.Name, cmd.RequestID))
	}, func(err error) {
		s.audit.emit("rename_rpc", incident.Decision, incident.Fail, data, false)
		deliveryErr = s.audit.response("rename_response", data, c.apiConn.SendError(ctx, leafOperationErrorCode(err, "provider_error"), err.Error(), cmd.RequestID))
	})
	return nil
}

func (s *Server) handleResolveModelsTyped(c *Connection, cmd protocol.ResolveModels) error {

	var leaf *session.Leaf
	if cmd.LeafID != "" {
		leaf, _ = s.storage.GetLeaf(cmd.LeafID)
	}

	cfg := s.resolveConfigFromLeaf(c, leaf)

	var leafModel string
	if leaf != nil {
		leafModel = leaf.Model
	}

	main, small, audit := cfg.ResolveModels(leafModel)

	c.apiConn.SendResolvedModels(context.Background(), protocol.ResolvedModels{
		Type:      "resolved_models",
		Main:      main,
		Small:     small,
		Audit:     audit,
		RequestID: cmd.RequestID,
	}, cmd.RequestID)

	return nil
}

func (s *Server) handleSetLeafConfigTyped(c *Connection, cmd protocol.SetLeafConfig) error {
	if cmd.LeafID == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "leaf_id is required", cmd.RequestID)
		return nil
	}
	if cmd.Key == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "key is required", cmd.RequestID)
		return nil
	}
	_ = s.leaves.setLeafConfig(cmd.LeafID, cmd.Key, cmd.Value, func() {
		_ = c.apiConn.SendLeafConfigSet(context.Background(), cmd.Key, cmd.Value, cmd.RequestID)
	}, func(err error) {
		_ = c.apiConn.SendError(context.Background(), "provider_error", err.Error(), cmd.RequestID)
	})
	return nil
}

func (s *Server) handleSetModelTyped(c *Connection, cmd protocol.SetModel) error {
	if cmd.LeafID == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "leaf_id is required", cmd.RequestID)
		return nil
	}
	if cmd.Model == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "model is required", cmd.RequestID)
		return nil
	}

	_ = s.leaves.setModel(cmd.LeafID, cmd.Model, func(leaf *session.Leaf) *config.Config {
		return s.resolveConfigFromLeaf(c, leaf)
	}, func(thinking string) {
		_ = c.apiConn.SendModelSet(context.Background(), cmd.LeafID, cmd.Model, thinking, cmd.RequestID)
	}, func(err error) {
		_ = c.apiConn.SendError(context.Background(), leafOperationErrorCode(err, "provider_error"), leafOperationErrorMessage(err), cmd.RequestID)
	})
	return nil
}

func (s *Server) shutdownSignal() <-chan struct{} { return s.shutdown }

func (s *Server) enqueueToolAdmission(connID string, send func(*ezagentapi.Conn) error) {
	s.admissionSendMu.Lock()
	defer s.admissionSendMu.Unlock()
	select {
	case <-s.shutdown:
		return
	default:
	}
	s.mu.RLock()
	c := s.connections[connID]
	s.mu.RUnlock()
	if c != nil {
		_ = send(c.apiConn)
	}
}

func (s *Server) enqueueToolSteerAccepted(connID, requestID string, accepted *protocol.SteerAccepted) {
	s.enqueueToolAdmission(connID, func(api *ezagentapi.Conn) error {
		return api.SendSteerAccepted(context.Background(), accepted.LeafID, accepted.TurnIDs, accepted.TipTurnID, requestID)
	})
}

func (s *Server) enqueueToolSteerFailure(connID, requestID string, err error) {
	s.enqueueToolAdmission(connID, func(api *ezagentapi.Conn) error {
		return api.SendError(context.Background(), "turn_conflict", err.Error(), requestID)
	})
}

func (s *Server) handleSteerTyped(c *Connection, cmd protocol.Steer) error {
	select {
	case <-s.shutdown:
		return nil
	default:
	}
	if cmd.Turn.Advanced != nil {
		id := protocol.BackgroundBashTaskID(cmd.Turn.Advanced.OtherMeta)
		if id != "" {
			s.leaves.mu.RLock()
			owner, owned := s.leaves.background[id]
			s.leaves.mu.RUnlock()
			if !owned || owner != (backgroundOwner{cmd.LeafID, c.ID}) {
				if s.leaves.backgroundCompletionCancelled(id, cmd.LeafID, c.ID) {
					return s.handleSteerReady(c, cmd)
				}
				return c.apiConn.SendError(context.Background(), "turn_conflict", "background task is not owned by this connection and leaf", cmd.RequestID)
			}
		}
		if initial := s.leaves.initialBackgroundResult(id); initial != nil {
			release, err := s.leaves.reserveAdmissionResult(cmd.LeafID)
			if err != nil {
				return c.apiConn.SendError(context.Background(), "turn_conflict", err.Error(), cmd.RequestID)
			}
			// Response callback order is not FIFO. Do not occupy that callback lane
			// while waiting for the preceding tool result to enter the agent queue.
			go func() {
				defer release()
				ctx, cancel := context.WithCancel(context.Background())
				defer cancel()
				select {
				case <-initial.done:
					if initial.err == nil {
						_ = s.handleSteerReady(c, cmd)
						return
					}
				case <-c.apiConn.Closed():
				case <-s.shutdown:
				}
				_ = c.apiConn.SendError(ctx, "turn_conflict", "initial background result was not admitted", cmd.RequestID)
			}()
			return nil
		}
	}
	return s.handleSteerReady(c, cmd)
}

func (s *Server) handleSteerReady(c *Connection, cmd protocol.Steer) error {
	select {
	case <-s.shutdown:
		return nil
	default:
	}
	if cmd.Turn.Advanced != nil && s.leaves.backgroundCompletionCancelled(protocol.BackgroundBashTaskID(cmd.Turn.Advanced.OtherMeta), cmd.LeafID, c.ID) {
		_ = c.apiConn.SendError(context.Background(), "leaf_aborting", "background task was cancelled", cmd.RequestID)
		return nil
	}
	if cmd.LeafID == "" {
		_ = c.apiConn.SendError(context.Background(), "leaf_not_found", "leaf_id is required", cmd.RequestID)
		return nil
	}
	if cmd.Turn.Kind == session.KindUser {
		if err := validateUserTurnBoundary(cmd.Turn); err != nil {
			_ = c.apiConn.SendError(context.Background(), "parse_error", err.Error(), cmd.RequestID)
			return nil
		}
	} else if cmd.Turn.Kind == "" {
		_ = c.apiConn.SendError(context.Background(), "parse_error", "steer turn is required", cmd.RequestID)
		return nil
	} else if cmd.Turn.Kind != session.KindToolResult {
		_ = c.apiConn.SendError(context.Background(), "invalid_turn", "turn.kind must be user or tool_result", cmd.RequestID)
		return nil
	}
	_ = s.leaves.steer(leafSteerRequest{
		RequesterLive: func() bool { return s.isCurrentConnection(c) },
		LeafID:        cmd.LeafID, ParentTurnID: cmd.ParentTurnID, Turn: cmd.Turn,
		RequestID: cmd.RequestID, Origin: c,
		ResolveConfig: func(leaf *session.Leaf) *config.Config { return s.resolveConfigFromLeaf(c, leaf) },
		AfterReserved: s.afterLeafAdmissionReserved,
		CompleteToolResult: func(onAdmitted func(*protocol.SteerAccepted, error)) error {
			return s.completeToolResult(c, cmd.LeafID, protocol.ToolResult{Type: "tool_result", ToolCallID: cmd.Turn.ToolCallID, Turn: cmd.Turn}, onAdmitted)
		},
		PublishAccepted: func(accepted *protocol.SteerAccepted) {
			_ = c.apiConn.SendSteerAccepted(context.Background(), accepted.LeafID, accepted.TurnIDs, accepted.TipTurnID, accepted.RequestID)
		},
		PublishFailure: func(err error) {
			_ = c.apiConn.SendError(context.Background(), leafOperationErrorCode(err, "turn_conflict"), leafOperationErrorMessage(err), cmd.RequestID)
		},
	})
	return nil
}

func (s *Server) handleSwitchLeafTyped(c *Connection, cmd protocol.SwitchLeaf) error {
	return s.handleSwitchLeafContext(context.Background(), c, cmd)
}

func (s *Server) handleSwitchLeafContext(ctx context.Context, c *Connection, cmd protocol.SwitchLeaf) error {
	if cmd.LeafID == "" {
		c.apiConn.SendError(context.Background(), "leaf_not_found", "leaf_id is required", cmd.RequestID)
		return nil
	}
	state, ordered := ctx.Value(connectionContextKey{}).(connectionContext)
	if ordered {
		return s.orderedSwitchLeaf(ctx, c, cmd, state.version)
	}
	if !s.switchLeafWithSnapshot(c, cmd.LeafID, cmd.RequestID, true) && c.apiConn.Err() == nil {
		c.apiConn.SendError(context.Background(), "leaf_not_found", fmt.Sprintf("leaf not found: %s", cmd.LeafID), cmd.RequestID)
	}
	return nil
}

func (s *Server) handleVacuumTyped(c *Connection, cmd protocol.Vacuum) error {

	opts := session.VacuumOpts{
		DryRun: cmd.DryRun,
		Deep:   cmd.Deep,
	}
	if cmd.OlderThan > 0 {
		opts.OlderThan = time.Duration(cmd.OlderThan) * time.Second
	}

	_ = s.leaves.vacuum(leafVacuumRequest{
		Options: opts, DryRun: cmd.DryRun,
		PublishResult: func(result session.VacuumResult) {
			_ = c.apiConn.SendVacuumResult(context.Background(), protocol.VacuumResult{
				Type: "vacuum_result", RootsPruned: result.RootsPruned,
				TurnsPruned: result.TurnsPruned, RequestID: cmd.RequestID,
			}, cmd.RequestID)
		},
		PublishFailure: func(err error) {
			_ = c.apiConn.SendError(context.Background(), "provider_error", err.Error(), cmd.RequestID)
		},
	})
	return nil
}

func (s *Server) handleListLeafConfigTyped(c *Connection, cmd protocol.ListLeafConfig) error {
	if cmd.LeafID == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "leaf_id is required", cmd.RequestID)
		return nil
	}
	entries, err := s.storage.ListLeafConfig(cmd.LeafID)
	if err != nil {
		c.apiConn.SendError(context.Background(), "provider_error", err.Error(), cmd.RequestID)
		return nil
	}
	configs := make([]protocol.LeafConfigListEntry, len(entries))
	for i, e := range entries {
		configs[i] = protocol.LeafConfigListEntry{Key: e.Key, Value: e.Value}
	}
	c.apiConn.SendLeafConfigList(context.Background(), configs, cmd.RequestID)

	return nil
}

func (s *Server) handleDeleteLeafConfigTyped(c *Connection, cmd protocol.DeleteLeafConfig) error {
	if cmd.LeafID == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "leaf_id is required", cmd.RequestID)
		return nil
	}
	if cmd.Key == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "key is required", cmd.RequestID)
		return nil
	}
	_ = s.leaves.deleteLeafConfig(cmd.LeafID, cmd.Key, func() {
		_ = c.apiConn.SendLeafConfigDeleted(context.Background(), cmd.Key, cmd.RequestID)
	}, func(err error) {
		_ = c.apiConn.SendError(context.Background(), "provider_error", err.Error(), cmd.RequestID)
	})
	return nil
}

func (s *Server) handleCreateVirtualRootTyped(c *Connection, cmd protocol.CreateVirtualRoot) error {
	if cmd.LeafID == "" {
		_ = c.apiConn.SendError(context.Background(), "parse_error", "leaf_id is required", cmd.RequestID)
		return nil
	}
	if _, err := protocol.EncodeVirtualRootMetadata(cmd.Metadata); err != nil {
		_ = c.apiConn.SendError(context.Background(), "parse_error", err.Error(), cmd.RequestID)
		return nil
	}
	_ = s.leaves.createVirtualRoot(virtualRootRequest{
		LeafID: cmd.LeafID, Reason: cmd.Reason, PendingTurns: cmd.PendingTurns, Metadata: cmd.Metadata,
		PublishCreated: func(rootID, model string) {
			_ = c.apiConn.SendVirtualRootCreated(context.Background(), rootID, cmd.LeafID, model, cmd.RequestID)
		},
		PublishFailure: func(err error) {
			_ = c.apiConn.SendError(context.Background(), "internal_error", err.Error(), cmd.RequestID)
		},
	})
	return nil
}

func (s *Server) handleUpdateLeafMetaTyped(c *Connection, cmd protocol.UpdateLeafMeta) error {
	if cmd.LeafID == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "leaf_id is required", cmd.RequestID)
		return nil
	}
	if cmd.Name != nil && *cmd.Name == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "name cannot be empty", cmd.RequestID)
		return nil
	}
	if cmd.Name == nil && len(cmd.SetConfig) == 0 && len(cmd.DeleteConfig) == 0 {
		c.apiConn.SendError(context.Background(), "parse_error", "at least one of name, set_config, delete_config is required", cmd.RequestID)
		return nil
	}
	_ = s.leaves.updateLeafMeta(cmd.LeafID, cmd.Name, cmd.SetConfig, cmd.DeleteConfig, func(updated protocol.LeafMetaUpdated) {
		updated.RequestID = cmd.RequestID
		_ = c.apiConn.SendLeafMetaUpdated(context.Background(), updated, updated.RequestID)
	}, func(err error) {
		_ = c.apiConn.SendError(context.Background(), leafOperationErrorCode(err, "provider_error"), err.Error(), cmd.RequestID)
	})
	return nil
}

func (s *Server) handleListConnectionsTyped(c *Connection, cmd protocol.ListConnections) error {

	s.mu.RLock()
	conns := make([]*Connection, 0, len(s.connections))
	for _, conn := range s.connections {
		conns = append(conns, conn)
	}
	s.mu.RUnlock()
	out := make([]protocol.ConnectionListEntry, 0, len(conns))
	for _, conn := range conns {
		out = append(out, protocol.ConnectionListEntry{
			ID:      conn.ID,
			Name:    conn.Name,
			LeafID:  conn.LeafID,
			Tools:   effectiveSet(conn.AnnouncedTools, s.connectionConfiguredNames(conn, "tools")),
			Plugins: effectiveSet(conn.AnnouncedPlugins, s.connectionConfiguredNames(conn, "plugins")),
			Macros:  effectiveSet(conn.AnnouncedMacros, s.connectionConfiguredNames(conn, "macros")),
		})
	}

	c.apiConn.SendConnectionList(context.Background(), out, cmd.RequestID) /*
		Type:        "connection_list",
		Connections: out,
		RequestID:   cmd.RequestID,
	})*/

	return nil
}

func (s *Server) handleEffectiveConfigTyped(c *Connection, cmd protocol.GetEffectiveConfig) error {

	cfg := s.resolveConfig(c, cmd.LeafID)

	var cwd string
	var layers []string
	if cmd.LeafID != "" {
		leaf, err := s.storage.GetLeaf(cmd.LeafID)
		if err == nil && leaf != nil {
			root, err := s.storage.GetRoot(leaf.RootID)
			if err == nil && root != nil {
				cwd = root.Cwd
			}
		}
	}
	if cmd.LeafID == "" && cwd == "" {
		cwd = s.connectionCwd(c)
	}

	layers = s.effectiveConfigLayers(cwd)

	yamlStr, err := cfg.MarshalYAML()
	if err != nil {
		c.apiConn.SendError(context.Background(), "config_error", err.Error(), cmd.RequestID)
		return nil
	}

	c.apiConn.SendEffectiveConfig(context.Background(), protocol.EffectiveConfig{
		Type:        "effective_config",
		Cwd:         cwd,
		Config:      yamlStr,
		Layers:      layers,
		ConfigError: cfg.ConfigError,
		RequestID:   cmd.RequestID,
	}, cmd.RequestID)

	return nil
}

func (s *Server) effectiveConfigLayers(cwd string) []string {
	layers := []string{"builtin"}
	if _, err := os.Stat(s.configPath); err == nil {
		layers = append(layers, "user")
	}
	if cwd == "" {
		return layers
	}
	candidate, err := inspectProjectConfig(cwd)
	if err != nil || candidate == nil {
		return layers
	}
	if decision, ok := s.projectTrust.decision(candidate); ok && decision == protocol.QuestionReplyTrust {
		layers = append(layers, "project")
	}
	return layers
}

func (s *Server) handleSetThinkingLevelTyped(c *Connection, cmd protocol.SetThinkingLevel) error {
	if cmd.LeafID == "" {
		c.apiConn.SendError(context.Background(), "parse_error", "leaf_id is required", cmd.RequestID)
		return nil
	}

	_ = s.leaves.setThinkingLevel(cmd.LeafID, cmd.Level, func(leaf *session.Leaf) *config.Config {
		return s.resolveConfigFromLeaf(c, leaf)
	}, func(level string) {
		_ = c.apiConn.SendThinkingLevelSet(context.Background(), cmd.LeafID, level, cmd.RequestID)
	}, func(err error) {
		_ = c.apiConn.SendError(context.Background(), leafOperationErrorCode(err, "provider_error"), err.Error(), cmd.RequestID)
	})
	return nil
}

func (s *Server) handleQuestionReplyTyped(c *Connection, reply protocol.QuestionReply) error {
	if err := reply.Validate(); err != nil {
		return c.apiConn.SendError(context.Background(), "parse_error", err.Error(), reply.RequestID)
	}
	return s.leaves.resolvePendingQuestion(reply, func([]string) {
		// The durable decision must invalidate cached pre-decision resolution
		// before another operation can reuse it.
		s.mu.Lock()
		s.projectCache = make(map[string]*projectCacheEntry)
		s.mu.Unlock()
		if s.leaves != nil {
			s.leaves.invalidateAllToolCaches()
		}
	}, func() error {
		return c.apiConn.SendQuestionReplyAck(context.Background(), reply)
	}, func(affected []string) {
		// Re-resolve each affected leaf after snapshot fan-out. ProcessPool keeps
		// an already-running service generation in place, so an in-flight request
		// is never rerouted to a newly trusted override.
		if reply.Reply == protocol.QuestionReplyTrust {
			for _, leafID := range affected {
				s.startOnStartServicesForLeaf(leafID)
			}
		}
	}, func(err error) error {
		code := "question_reply_failed"
		if errors.Is(err, ErrPendingQuestionNotFound) {
			code = "question_not_found"
		}
		return c.apiConn.SendError(context.Background(), code, err.Error(), reply.RequestID)
	})
}

func (s *Server) markInfoReceived(c *Connection, kind, requestID string) {
	c.chMu.Lock()
	var pending map[string]struct{}
	switch kind {
	case "tool":
		pending = c.pendingToolInfo
		if waiter := c.toolInfoWaiters[requestID]; waiter != nil {
			delete(c.toolInfoWaiters, requestID)
			close(waiter)
		}
	case "plugin":
		pending = c.pendingPluginInfo
	case "macro":
		pending = c.pendingMacroInfo
	}
	// Responses to on-demand metadata requests do not participate in the
	// connection startup/readiness barrier. Only a request issued by
	// fetchCapabilityInfo can complete that barrier.
	if pending != nil {
		delete(pending, requestID)
	}
	if c.capabilityInfoReadyLocked() && c.infoCh != nil {
		close(c.infoCh)
		c.infoCh = nil
	}
	c.chMu.Unlock()
}

// updateConnectionCapabilities excludes late publication after disconnect.
// The update may acquire Registry.mu, but must not perform transport work.
func (s *Server) updateConnectionCapabilities(c *Connection, update func()) bool {
	s.mu.RLock()
	defer s.mu.RUnlock()
	if s.connections[c.ID] != c {
		return false
	}
	update()
	return true
}

func (s *Server) connectionHandlers(c *Connection) ezagentapi.Handlers {
	return ezagentapi.Handlers{
		ConcurrentRPCs:  true,
		OnRequestQueued: s.observeRequestQueued,
		OnAnnounce: func(ctx context.Context, ann protocol.Announce) error {
			if !s.updateConnectionCapabilities(c, func() { s.registry.RegisterAnnounce(c.ID, ann) }) {
				return nil
			}
			c.AnnouncedTools = ann.Tools
			c.AnnouncedPlugins = ann.Plugins
			c.AnnouncedMacros = ann.Macros
			c.closeAnnounceCh()
			s.fetchCapabilityInfo(c)
			return nil
		},
		PrepareInbound: s.prepareConnectionInbound(c),
		OnCreateLeaf: func(ctx context.Context, cmd protocol.CreateLeaf) error {
			return s.handleCreateLeafContext(ctx, c, cmd)
		},
		OnUpdateCwd: func(ctx context.Context, cmd protocol.UpdateCwd) error { return nil },
		OnListCwd:   func(ctx context.Context, cmd protocol.ListCwd) error { return s.handleListCwdTyped(c, cmd) },
		OnRewindLeaf: func(ctx context.Context, cmd protocol.RewindLeaf) error {
			return s.handleRewindLeafTyped(c, cmd)
		},
		OnPrompt: func(ctx context.Context, cmd protocol.Prompt) error {
			return s.handlePromptContext(ctx, c, cmd)
		},
		OnBackgroundTaskAdd: func(ctx context.Context, cmd protocol.BackgroundTaskAdd) error {
			return s.handleBackground(c, true, cmd.RequestID, cmd.LeafID, cmd.TaskID)
		},
		OnBackgroundTaskRemove: func(ctx context.Context, cmd protocol.BackgroundTaskRemove) error {
			return s.handleBackground(c, false, cmd.RequestID, cmd.LeafID, cmd.TaskID)
		},
		OnSteer: func(ctx context.Context, cmd protocol.Steer) error { return s.handleSteerTyped(c, cmd) },
		OnAbort: func(ctx context.Context, cmd protocol.Abort) error {
			return s.handleAbortContext(ctx, c, cmd)
		},
		OnToolInvoke: func(ctx context.Context, cmd protocol.ToolInvoke) error {
			return s.handleToolInvoke(ctx, c, cmd)
		},
		OnReportProgress: func(ctx context.Context, cmd protocol.ReportProgress) error {
			if err := s.handleReportProgress(c, cmd); err != nil {
				// report_progress remains one-way: rejection is delivered as an
				// asynchronous protocol error, never as a method response.
				_ = c.apiConn.SendError(ctx, "progress_rejected", err.Error(), "")
			}
			return nil
		},
		OnQuestionReply: func(ctx context.Context, reply protocol.QuestionReply) error {
			return s.handleQuestionReplyTyped(c, reply)
		},
		OnShutdown:     func(ctx context.Context, cmd ezagentapi.Shutdown) error { s.Stop(); return nil },
		OnListLeaves:   func(ctx context.Context, cmd protocol.ListLeaves) error { return s.handleListLeavesTyped(c, cmd) },
		OnListRoots:    func(ctx context.Context, cmd protocol.ListRoots) error { return s.handleListRootsTyped(c, cmd) },
		OnListQueued:   func(ctx context.Context, cmd protocol.ListQueued) error { return s.handleListQueuedTyped(c, cmd) },
		OnListHistory:  func(ctx context.Context, cmd protocol.ListHistory) error { return s.handleListHistoryTyped(c, cmd) },
		OnListTurnTree: func(ctx context.Context, cmd protocol.ListTurnTree) error { return s.handleListTurnTreeTyped(c, cmd) },
		OnLeafStats: func(ctx context.Context, cmd protocol.LeafStats) error {
			return s.handleLeafStatsContext(ctx, c, cmd)
		},
		OnDeleteLeaf:    func(ctx context.Context, cmd protocol.DeleteLeaf) error { return s.handleDeleteLeafTyped(c, cmd) },
		OnVacuum:        func(ctx context.Context, cmd protocol.Vacuum) error { return s.handleVacuumTyped(c, cmd) },
		OnGetLeafConfig: func(ctx context.Context, cmd protocol.GetLeafConfig) error { return s.handleGetLeafConfigTyped(c, cmd) },
		OnLeafFiles:     func(ctx context.Context, cmd protocol.LeafFiles) error { return s.handleLeafFilesTyped(c, cmd) },
		OnSetLeafConfig: func(ctx context.Context, cmd protocol.SetLeafConfig) error { return s.handleSetLeafConfigTyped(c, cmd) },
		OnListLeafConfig: func(ctx context.Context, cmd protocol.ListLeafConfig) error {
			return s.handleListLeafConfigTyped(c, cmd)
		},
		OnDeleteLeafConfig: func(ctx context.Context, cmd protocol.DeleteLeafConfig) error {
			return s.handleDeleteLeafConfigTyped(c, cmd)
		},
		OnSwitchLeaf: func(ctx context.Context, cmd protocol.SwitchLeaf) error {
			return s.handleSwitchLeafContext(ctx, c, cmd)
		},
		OnDropFeed: func(ctx context.Context, cmd protocol.DropFeed) error { return s.handleDropFeedContext(ctx, c, cmd) },
		OnCreateVirtualRoot: func(ctx context.Context, cmd protocol.CreateVirtualRoot) error {
			return s.handleCreateVirtualRootTyped(c, cmd)
		},
		OnRenameLeaf: func(ctx context.Context, cmd protocol.RenameLeaf) error {
			return s.handleRenameLeafContext(ctx, c, cmd)
		},
		OnUpdateLeafMeta: func(ctx context.Context, cmd protocol.UpdateLeafMeta) error {
			return s.handleUpdateLeafMetaTyped(c, cmd)
		},
		OnNotifyLeaf: func(ctx context.Context, cmd protocol.NotifyLeaf) error { return s.handleNotifyLeafTyped(c, cmd) },
		OnGetSupportedFiletypes: func(ctx context.Context, cmd protocol.GetSupportedFiletypes) error {
			return c.apiConn.SendSupportedFiletypes(ctx, cmd.RequestID)
		},
		OnAddTool:    func(ctx context.Context, cmd protocol.AddTool) error { return s.handleAddToolTyped(c, cmd) },
		OnRemoveTool: func(ctx context.Context, cmd protocol.RemoveTool) error { return s.handleRemoveToolTyped(c, cmd) },
		OnListTools: func(ctx context.Context, cmd protocol.ListTools) error {
			return s.handleListToolsTyped(configConnection(ctx, c), cmd)
		},
		OnGetToolInfo: func(ctx context.Context, cmd protocol.GetToolInfo) error {
			return s.handleGetToolInfoContext(ctx, configConnection(ctx, c), cmd)
		},
		OnListPlugins: func(ctx context.Context, cmd protocol.ListPlugins) error {
			return s.handleListPluginsTyped(configConnection(ctx, c), cmd)
		},
		OnListMacros: func(ctx context.Context, cmd protocol.ListMacros) error {
			return s.handleListMacrosContext(ctx, configConnection(ctx, c), cmd)
		},
		OnMacroCallRequest: func(ctx context.Context, cmd protocol.MacroCall) error {
			return s.handleMacroCallContext(ctx, configConnection(ctx, c), cmd)
		},
		OnListConnections: func(ctx context.Context, cmd protocol.ListConnections) error {
			return s.handleListConnectionsTyped(c, cmd)
		},
		OnListModels: func(ctx context.Context, cmd protocol.ListModels) error {
			return s.handleListModelsTyped(configConnection(ctx, c), cmd)
		},
		OnListProviders: func(ctx context.Context, cmd protocol.ListProviders) error {
			return s.handleListProvidersTyped(configConnection(ctx, c), cmd)
		},
		OnResolveModels: func(ctx context.Context, cmd protocol.ResolveModels) error {
			return s.handleResolveModelsTyped(configConnection(ctx, c), cmd)
		},
		OnGetEffectiveConfig: func(ctx context.Context, cmd protocol.GetEffectiveConfig) error {
			return s.handleEffectiveConfigTyped(configConnection(ctx, c), cmd)
		},
		OnGetAttachmentChunk: func(ctx context.Context, cmd protocol.GetAttachmentChunk) error {
			return s.handleGetAttachmentChunk(ctx, c, cmd)
		},
		OnGetTurn:  func(ctx context.Context, cmd protocol.GetTurn) error { return s.handleGetTurnTyped(c, cmd) },
		OnSetModel: func(ctx context.Context, cmd protocol.SetModel) error { return s.handleSetModelTyped(c, cmd) },
		OnSetThinkingLevel: func(ctx context.Context, cmd protocol.SetThinkingLevel) error {
			return s.handleSetThinkingLevelTyped(c, cmd)
		},
		OnToolInfoResponse: func(ctx context.Context, resp protocol.ToolInfoResponse) error {
			if !s.updateConnectionCapabilities(c, func() { s.registry.UpdateToolInfo(c.ID, resp.Tools) }) {
				return nil
			}
			s.markInfoReceived(c, "tool", resp.RequestID)
			s.invalidateAllToolCaches()
			return nil
		},
		OnPluginInfoResponse: func(ctx context.Context, resp protocol.PluginInfoResponse) error {
			if !s.updateConnectionCapabilities(c, func() { s.registry.UpdatePluginInfo(c.ID, resp.Plugins) }) {
				return nil
			}
			s.markInfoReceived(c, "plugin", resp.RequestID)
			s.invalidateAllToolCaches()
			return nil
		},
		OnMacroInfoResponse: func(ctx context.Context, resp protocol.MacroInfoResponse) error {
			if !s.updateConnectionCapabilities(c, func() { s.registry.UpdateMacroInfo(c.ID, resp.Macros) }) {
				return nil
			}
			s.markInfoReceived(c, "macro", resp.RequestID)
			return nil
		},
		OnToolResult: func(ctx context.Context, result protocol.ToolResult) error {
			if err := s.completeToolResult(c, "", result, nil); err != nil {
				return c.apiConn.SendError(ctx, "parse_error", err.Error(), "")
			}
			return nil
		},
		OnToolAck: func(ctx context.Context, ack protocol.ToolAck) error {
			if pc, ok := s.registry.AckPendingCall(ack.ToolCallID, c.ID); ok {
				select {
				case pc.AckCh <- ToolCallAckResult{Ack: ack}:
				default:
				}
			}
			return nil
		},
		OnPluginResult: func(ctx context.Context, result protocol.PluginResultIPC) error {
			if pc, ok := s.registry.ClaimPendingPluginCall(result.PluginCallID, c.ID); ok {
				s.wdMgr.Cancel(watchdog.Key{Type: "plugin", ID: result.PluginCallID})
				select {
				case pc.ResultCh <- PluginCallResult{Result: result}:
				default:
				}
			}
			return nil
		},
		OnMacroResultIPC: func(ctx context.Context, result protocol.MacroResultIPC) error {
			if pc, ok := s.registry.ClaimPendingMacroCall(result.MacroCallID, c.ID); ok {
				s.wdMgr.Cancel(watchdog.Key{Type: "macro", ID: result.MacroCallID})
				select {
				case pc.ResultCh <- MacroCallResult{Result: result}:
				default:
				}
			}
			return nil
		},
		OnHeartbeat: func(ctx context.Context, hb protocol.OpHeartbeat) error {
			if s.registry.PendingCallOwned(hb.Kind, hb.CallID, c.ID) {
				s.wdMgr.Heartbeat(watchdog.Key{Type: hb.Kind, ID: hb.CallID})
			}
			return nil
		},
		OnToolAbortAck: func(ctx context.Context, ack protocol.ToolAbortAck) error {
			if pc, _, ok := s.registry.ClaimPendingCallForConnValidated(ack.ToolCallID, c.ID, func(*PendingCall) error { return nil }); ok {
				s.wdMgr.Cancel(watchdog.Key{Type: "tool", ID: ack.ToolCallID})
				select {
				case pc.ResultCh <- ToolCallResult{Err: fmt.Errorf("tool aborted: ack received")}:
				default:
				}
			}
			return nil
		},
		OnUnsupportedMessage: func(ctx context.Context, msg ezagentapi.UnsupportedMessage) error {
			return c.apiConn.SendError(ctx, "unknown_command", fmt.Sprintf("unknown command type: %s", msg.Type), protocol.ExtractRequestID(msg.Raw))
		},
		OnError: func(ctx context.Context, err error) {
			var dec ezagentapi.DecodeError
			if errors.As(err, &dec) {
				_ = c.apiConn.SendError(ctx, "parse_error", dec.Err.Error(), protocol.ExtractRequestID(dec.Raw))
				return
			}
			// Expected disconnect/cancellation is not an incident. Never inspect
			// or format an unexpected error for the audit recorder.
			if ctx.Err() == nil && !expectedRequestCancellation(err) {
				s.audit.emit("boundary", incident.Unexpected, incident.Fail, incident.Data{}, true)
			} else {
				s.audit.emit("boundary", incident.Completed, incident.Cancel, incident.Data{}, false)
			}
		},
	}
}

func (s *Server) directConnServiceOptions(c *Connection) ezagentapi.ServiceOptions {
	return ezagentapi.ServiceOptions{
		ServerID:    "ez1",
		StateDir:    config.StateDir(),
		ConfigError: s.configSnapshot().ConfigError,
		OnHello: func(ctx context.Context, hello ezagentapi.ServiceHello) (ezagentapi.HelloAck, error) {
			ack := ezagentapi.HelloAck{ServerID: "ez1", StateDir: config.StateDir(), ConnectionID: c.ID, ConfigError: s.configSnapshot().ConfigError, Ready: true, Message: "READY"}
			s.mu.Lock()
			if s.connections[c.ID] != c {
				s.mu.Unlock()
				return ack, nil
			}
			c.Name = hello.Hello.Name
			c.LeafID = hello.Hello.LeafID
			c.Cwd = hello.Hello.Cwd
			s.mu.Unlock()
			c.helloDone.Store(true)
			c.closeHelloCh()
			if c.launchedService != nil {
				s.updateConnectionCapabilities(c, func() {
					s.registry.RegisterServiceCapabilities(c.ID, c.launchedServiceName, *c.launchedService)
				})
			}
			if hello.Hello.LeafID != "" {
				leafID := hello.Hello.LeafID
				c.chMu.Lock()
				if c.backgroundClosed {
					c.chMu.Unlock()
					return ack, nil
				}
				c.backgroundRPCs.Add(1)
				c.chMu.Unlock()
				go func() {
					defer c.backgroundRPCs.Done()
					select {
					case <-c.apiConn.Ready():
						s.orderedHelloSubscription(ctx, c, leafID)
					case <-c.apiConn.Closed():
					case <-s.shutdown:
					case <-ctx.Done():
					}
				}()
			}
			return ack, nil
		},
		Handlers: s.connectionHandlers(c),
	}
}

func (s *Server) AbortPendingCallsForLeaf(leafID string) {
	toAbort := s.registry.GetPendingCallsForLeaf(leafID)

	connByID := make(map[string]*Connection)
	s.mu.RLock()
	for _, pc := range toAbort {
		if c, ok := s.connections[pc.ConnID]; ok && c != nil {
			connByID[pc.ConnID] = c
		}
	}
	s.mu.RUnlock()

	for connID, c := range connByID {
		for _, pc := range toAbort {
			if pc.ConnID == connID {
				c.apiConn.SendToolAbort(context.Background(), pc.ToolCallID)
			}
		}
	}

	for _, pc := range toAbort {
		key := watchdog.Key{Type: "tool", ID: pc.ToolCallID}
		s.wdMgr.CancelWithError(key)
	}
}

func (s *Server) CallPlugin(ctx context.Context, name, leafID, rootID, cwd, role string, turns []protocol.PendingTurn, configMap map[string]string) ([]protocol.PendingTurn, error) {
	return s.ipc.CallPlugin(ctx, name, leafID, rootID, cwd, role, turns, configMap)
}

func (s *Server) invalidateAllToolCaches() {
	if s.leaves != nil {
		s.leaves.invalidateAllToolCaches()
	}
}

// observeRequestQueued runs on frame receipt, before callback-lane contention.
// The returned timer completion runs after handlerMu acquisition, before the
// selected handler's own start observation. RPC response routing bypasses both.
func (s *Server) observeRequestQueued(receipt ezagentapi.RequestReceipt) func() {
	var prefix string
	switch receipt.Kind {
	case "leaf_stats":
		prefix = "stats"
	case "abort":
		prefix = "abort"
	case "prompt":
		prefix = "prompt"
	case "rename_leaf":
		prefix = "rename"
	default:
		return nil
	}
	data := safeIDs(receipt.LeafID, receipt.RequestID)
	s.audit.emit(prefix+"_receive", incident.Started, incident.Observe, data, false)
	done := s.audit.phase(prefix+"_dispatch", serviceWaitBudget, data, receipt.Kind == "abort")
	return func() { done(false) }
}

func (s *Server) handleLeafFilesTyped(c *Connection, cmd protocol.LeafFiles) error {
	ctx := context.Background()
	var missing string
	switch {
	case cmd.RequestID == "":
		missing = "request_id is required"
	case cmd.LeafID == "":
		missing = "leaf_id is required"
	case cmd.Key == "":
		missing = "key is required"
	case cmd.Operation != "attach":
		missing = "operation must be attach"
	}
	if missing != "" {
		return c.apiConn.SendError(ctx, "parse_error", missing, cmd.RequestID)
	}
	file, err := s.storage.AttachLeafFile(cmd.LeafID, cmd.Key)
	if err != nil {
		code := "provider_error"
		if errors.Is(err, session.ErrLeafNotFound) {
			code = "leaf_not_found"
		}
		return c.apiConn.SendError(ctx, code, err.Error(), cmd.RequestID)
	}
	return c.apiConn.SendLeafFilesResult(ctx, cmd.LeafID, cmd.RequestID, protocol.LeafFileDescriptor{FileID: file.FileID, Key: file.Key, Path: file.Path})
}