pkg/service/registry.go

package service

import (
	"fmt"
	"sort"
	"sync"
	"time"

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

type ToolProvider struct {
	ConnID       string
	Info         protocol.ToolInfo
	Source       string
	ConfigSource string
	Announced    bool
}

type PluginProvider struct {
	ConnID       string
	Info         protocol.PluginInfo
	Source       string
	ConfigSource string
	Announced    bool
}

type MacroProvider struct {
	ConnID       string
	Info         protocol.MacroInfo
	Source       string
	ConfigSource string
	Announced    bool
}

type ToolCallResult struct {
	Result     protocol.ToolResult
	Err        error
	OnAdmitted func(*protocol.SteerAccepted, error)
}

type ToolCallAckResult struct {
	Ack protocol.ToolAck
	Err error
}

type PendingCall struct {
	// ToolCallID is the trusted daemon invocation ID used only for runtime IPC.
	ToolCallID         string
	ProviderToolCallID string
	ToolName           string
	LeafID             string
	SourceTurnID       string
	GenericInvocation  bool
	ConnID             string
	ResultCh           chan ToolCallResult
	AckCh              chan ToolCallAckResult
	Acked              bool
	claimed            bool
	resultMu           sync.Mutex
	resultCancelled    error
}

// publishResult coordinates a claimed result with cancellation between claim and publication.
func (pc *PendingCall) publishResult(result ToolCallResult) {
	pc.resultMu.Lock()
	err := pc.resultCancelled
	if err == nil {
		select {
		case pc.ResultCh <- result:
		default:
		}
	}
	pc.resultMu.Unlock()
	if err != nil && result.OnAdmitted != nil {
		result.OnAdmitted(nil, err)
	}
}

func (pc *PendingCall) cancelResult(err error) {
	pc.resultMu.Lock()
	pc.resultCancelled = err
	var result ToolCallResult
	select {
	case result = <-pc.ResultCh:
	default:
	}
	pc.resultMu.Unlock()
	if result.OnAdmitted != nil {
		result.OnAdmitted(nil, err)
	}
}

type PluginCallResult struct {
	Result protocol.PluginResultIPC
	Err    error
}

type PendingPluginCall struct {
	PluginCallID string
	LeafID       string
	ConnID       string
	ResultCh     chan PluginCallResult
	claimed      bool
}

type MacroCallResult struct {
	Result protocol.MacroResultIPC
	Err    error
}

type PendingMacroCall struct {
	MacroCallID  string
	LeafID       string
	ConnID       string
	OriginConnID string
	ResultCh     chan MacroCallResult
	claimed      bool
}

type Registry struct {
	cfg                *config.Config
	services           map[string]config.ServiceConfig
	mu                 sync.RWMutex
	infoCond           *sync.Cond
	tools              map[string]*ToolProvider
	plugins            map[string]*PluginProvider
	macros             map[string]*MacroProvider
	pendingCalls       map[string]*PendingCall
	pendingPluginCalls map[string]*PendingPluginCall
	pendingMacroCalls  map[string]*PendingMacroCall
}

func NewRegistry(cfg *config.Config) *Registry {
	r := &Registry{
		cfg:                cfg,
		tools:              make(map[string]*ToolProvider),
		plugins:            make(map[string]*PluginProvider),
		macros:             make(map[string]*MacroProvider),
		pendingCalls:       make(map[string]*PendingCall),
		pendingPluginCalls: make(map[string]*PendingPluginCall),
		pendingMacroCalls:  make(map[string]*PendingMacroCall),
	}
	r.infoCond = sync.NewCond(&r.mu)
	r.registerConfigDefaults()
	return r
}

func (r *Registry) registerConfigDefaults() {
	r.mu.Lock()
	defer r.mu.Unlock()
	r.applyConfigLocked(r.cfg)
}

// ApplyConfig reconciles only config-derived registry state. Runtime routing,
// pending calls, live announcements, waiters, and the registry identity remain
// untouched.
func (r *Registry) ApplyConfig(cfg *config.Config) {
	r.mu.Lock()
	defer r.mu.Unlock()
	r.applyConfigLocked(cfg)
	r.infoCond.Broadcast()
}

func (r *Registry) applyConfigLocked(cfg *config.Config) {
	services := make(map[string]config.ServiceConfig)
	if cfg != nil {
		for connName, service := range cfg.Services {
			services[connName] = service
		}
	}
	toolSources := make(map[string]string)
	pluginSources := make(map[string]string)
	macroSources := make(map[string]string)
	for connName, dc := range services {
		source := "config:direct:" + connName
		for _, name := range dc.Tools {
			toolSources[name] = source
		}
		for _, name := range dc.Plugins {
			pluginSources[name] = source
		}
		for _, name := range dc.Macros {
			if config.IsReservedProviderExportMacro(name) {
				continue
			}
			macroSources[name] = source
		}
	}
	for name, p := range r.tools {
		p.ConfigSource = toolSources[name]
		if p.ConfigSource == "" && !p.Announced && p.ConnID == "" {
			delete(r.tools, name)
		}
	}
	for name, source := range toolSources {
		if p := r.tools[name]; p != nil {
			p.ConfigSource = source
			if !p.Announced && p.ConnID == "" {
				p.Source = source
			}
		} else {
			r.tools[name] = &ToolProvider{Info: protocol.ToolInfo{Name: name}, Source: source, ConfigSource: source}
		}
	}
	for name, p := range r.plugins {
		p.ConfigSource = pluginSources[name]
		if p.ConfigSource == "" && !p.Announced && p.ConnID == "" {
			delete(r.plugins, name)
		}
	}
	for name, source := range pluginSources {
		if p := r.plugins[name]; p != nil {
			p.ConfigSource = source
			if !p.Announced && p.ConnID == "" {
				p.Source = source
			}
		} else {
			r.plugins[name] = &PluginProvider{Info: protocol.PluginInfo{Name: name}, Source: source, ConfigSource: source}
		}
	}
	for name, p := range r.macros {
		if p.Source == "provider-export" {
			continue
		}
		p.ConfigSource = macroSources[name]
		if p.ConfigSource == "" && !p.Announced && p.ConnID == "" {
			delete(r.macros, name)
		}
	}
	for name, source := range macroSources {
		if p := r.macros[name]; p != nil {
			p.ConfigSource = source
			if !p.Announced && p.ConnID == "" {
				p.Source = source
			}
		} else {
			r.macros[name] = &MacroProvider{Info: protocol.MacroInfo{Name: name}, Source: source, ConfigSource: source}
		}
	}
	r.cfg = cfg
	r.services = services
}

// RegisterServiceCapabilities binds the effective definition that launched a
// process generation. These are runtime claims, not additions to the global
// config registry: project-only entries have no ConfigSource and disappear on
// disconnect, while inherited global stubs retain ConfigSource and revert to
// it. Existing live owners are never replaced, preserving first-live-wins.
func (r *Registry) RegisterServiceCapabilities(connID, serviceName string, svc config.ServiceConfig) {
	r.mu.Lock()
	defer r.mu.Unlock()

	source := "runtime-config:" + serviceName + ":" + connID
	for _, name := range svc.Tools {
		if existing := r.tools[name]; existing != nil {
			if existing.ConnID == "" {
				existing.ConnID = connID
				existing.Source = source
			}
			continue
		}
		r.tools[name] = &ToolProvider{ConnID: connID, Info: protocol.ToolInfo{Name: name}, Source: source}
	}
	for _, name := range svc.Plugins {
		if existing := r.plugins[name]; existing != nil {
			if existing.ConnID == "" {
				existing.ConnID = connID
				existing.Source = source
			}
			continue
		}
		r.plugins[name] = &PluginProvider{ConnID: connID, Info: protocol.PluginInfo{Name: name}, Source: source}
	}
	for _, name := range svc.Macros {
		if config.IsReservedProviderExportMacro(name) {
			continue
		}
		if existing := r.macros[name]; existing != nil {
			if existing.ConnID == "" {
				existing.ConnID = connID
				existing.Source = source
			}
			continue
		}
		r.macros[name] = &MacroProvider{ConnID: connID, Info: protocol.MacroInfo{Name: name}, Source: source}
	}
	r.infoCond.Broadcast()
}

func (r *Registry) RegisterAnnounce(connID string, ann protocol.Announce) {
	r.mu.Lock()
	defer r.mu.Unlock()

	source := "announce:" + connID

	for _, name := range ann.Tools {
		if existing, exists := r.tools[name]; exists {
			if existing.ConnID != "" && existing.ConnID != connID {
				continue
			}
			existing.ConnID = connID
			existing.Source = source
			existing.Announced = true
			continue
		}
		r.tools[name] = &ToolProvider{
			ConnID: connID,
			Info: protocol.ToolInfo{
				Name: name,
			},
			Source:    source,
			Announced: true,
		}
	}

	for _, name := range ann.Plugins {
		if existing, exists := r.plugins[name]; exists {
			if existing.ConnID != "" && existing.ConnID != connID {
				continue
			}
			existing.ConnID = connID
			existing.Source = source
			existing.Announced = true
			continue
		}
		r.plugins[name] = &PluginProvider{
			ConnID: connID,
			Info: protocol.PluginInfo{
				Name: name,
			},
			Source:    source,
			Announced: true,
		}
	}

	for _, name := range ann.Macros {
		if config.IsReservedProviderExportMacro(name) {
			continue
		}
		if existing, exists := r.macros[name]; exists {
			if existing.ConnID != "" && existing.ConnID != connID {
				continue
			}
			existing.ConnID = connID
			existing.Source = source
			existing.Announced = true
			continue
		}
		r.macros[name] = &MacroProvider{
			ConnID: connID,
			Info: protocol.MacroInfo{
				Name: name,
			},
			Source:    source,
			Announced: true,
		}
	}
}

func (r *Registry) UpdateToolInfo(connID string, tools []protocol.ToolInfo) {
	r.mu.Lock()
	defer r.mu.Unlock()

	for i := range tools {
		ti := tools[i]
		if existing, exists := r.tools[ti.Name]; exists {
			if existing.ConnID != "" && existing.ConnID != connID {
				continue
			}
			existing.ConnID = connID
			existing.Info = ti
		}
	}
	r.infoCond.Broadcast()
}

func (r *Registry) UpdatePluginInfo(connID string, plugins []protocol.PluginInfo) {
	r.mu.Lock()
	defer r.mu.Unlock()

	for i := range plugins {
		pi := plugins[i]
		if existing, exists := r.plugins[pi.Name]; exists {
			if existing.ConnID != "" && existing.ConnID != connID {
				continue
			}
			existing.ConnID = connID
			existing.Info = pi
		}
	}
	r.infoCond.Broadcast()
}

func (r *Registry) UpdateMacroInfo(connID string, macros []protocol.MacroInfo) {
	r.mu.Lock()
	defer r.mu.Unlock()

	for i := range macros {
		mi := macros[i]
		if config.IsReservedProviderExportMacro(mi.Name) {
			continue
		}
		if existing, exists := r.macros[mi.Name]; exists {
			if existing.ConnID != "" && existing.ConnID != connID {
				continue
			}
			existing.ConnID = connID
			existing.Info = mi
		}
	}
	r.infoCond.Broadcast()
}

func (r *Registry) ReleaseConnection(connID string) {
	r.mu.Lock()
	defer r.mu.Unlock()

	for name, tp := range r.tools {
		if tp.ConnID == connID {
			tp.Announced = false
			if tp.ConfigSource != "" {
				tp.ConnID = ""
				tp.Info = protocol.ToolInfo{Name: name}
				tp.Source = tp.ConfigSource
			} else {
				delete(r.tools, name)
			}
		}
	}
	for name, pp := range r.plugins {
		if pp.ConnID == connID {
			pp.Announced = false
			if pp.ConfigSource != "" {
				pp.ConnID = ""
				pp.Info = protocol.PluginInfo{Name: name}
				pp.Source = pp.ConfigSource
			} else {
				delete(r.plugins, name)
			}
		}
	}
	for name, mp := range r.macros {
		if mp.ConnID == connID {
			mp.Announced = false
			if mp.ConfigSource != "" {
				mp.ConnID = ""
				mp.Info = protocol.MacroInfo{Name: name}
				mp.Source = mp.ConfigSource
			} else {
				delete(r.macros, name)
			}
		}
	}
	r.infoCond.Broadcast()
}

func (r *Registry) UnregisterConnection(connID string) {
	r.ReleaseConnection(connID)
}

func (r *Registry) FindDirectConnByConnName(connName string) *config.ServiceConfig {
	r.mu.RLock()
	defer r.mu.RUnlock()
	if r.services == nil {
		return nil
	}
	if dc, ok := r.services[connName]; ok {
		return &dc
	}
	return nil
}

func (r *Registry) WaitToolInfo(name string, timeout time.Duration) *protocol.ToolInfo {
	deadline := time.Now().Add(timeout)
	r.mu.Lock()
	defer r.mu.Unlock()
	stopDeadlineWakeup := r.wakeInfoWaitersAt(deadline)
	defer stopDeadlineWakeup()
	for {
		if tp, ok := r.tools[name]; ok && tp.Info.Description != "" {
			info := r.ResolveMergedToolInfoLocked(name)
			return info
		}
		if time.Now().After(deadline) {
			return r.ResolveMergedToolInfoLocked(name)
		}
		r.infoCond.Wait()
	}
}

func (r *Registry) WaitPluginInfo(name string, timeout time.Duration) *protocol.PluginInfo {
	deadline := time.Now().Add(timeout)
	r.mu.Lock()
	defer r.mu.Unlock()
	stopDeadlineWakeup := r.wakeInfoWaitersAt(deadline)
	defer stopDeadlineWakeup()
	for {
		if pp, ok := r.plugins[name]; ok && pp.Info.Description != "" {
			return &pp.Info
		}
		if time.Now().After(deadline) {
			if pp, ok := r.plugins[name]; ok {
				return &pp.Info
			}
			return nil
		}
		r.infoCond.Wait()
	}
}

func (r *Registry) WaitMacroInfo(name string, timeout time.Duration) *protocol.MacroInfo {
	deadline := time.Now().Add(timeout)
	r.mu.Lock()
	defer r.mu.Unlock()
	stopDeadlineWakeup := r.wakeInfoWaitersAt(deadline)
	defer stopDeadlineWakeup()
	for {
		if mp, ok := r.macros[name]; ok && (mp.Info.Description != "" || len(mp.Info.Triggers) > 0) {
			return r.ResolveMergedMacroInfoLocked(name)
		}
		if time.Now().After(deadline) {
			return r.ResolveMergedMacroInfoLocked(name)
		}
		r.infoCond.Wait()
	}
}

// wakeInfoWaitersAt makes a bounded metadata wait observe its deadline even
// when no registry mutation occurs. The callback takes the condition lock so
// waiters still recheck registry state and the deadline while holding r.mu.
func (r *Registry) wakeInfoWaitersAt(deadline time.Time) func() {
	timer := time.AfterFunc(time.Until(deadline), func() {
		r.mu.Lock()
		r.infoCond.Broadcast()
		r.mu.Unlock()
	})
	return func() { timer.Stop() }
}

func (r *Registry) ResolveMergedToolInfo(name string) *protocol.ToolInfo {
	r.mu.RLock()
	defer r.mu.RUnlock()
	return r.ResolveMergedToolInfoLocked(name)
}

func (r *Registry) GetToolsForLeaf(toolNames []string) []protocol.ToolInfo {
	r.mu.RLock()
	defer r.mu.RUnlock()

	var tools []protocol.ToolInfo
	for _, name := range toolNames {
		if info := r.ResolveMergedToolInfoLocked(name); info != nil {
			tools = append(tools, *info)
		}
	}
	return tools
}

func (r *Registry) ResolveMergedMacroInfo(name string) *protocol.MacroInfo {
	r.mu.RLock()
	defer r.mu.RUnlock()
	return r.ResolveMergedMacroInfoLocked(name)
}

func (r *Registry) ResolveMergedMacroInfoLocked(name string) *protocol.MacroInfo {
	info := &protocol.MacroInfo{
		Name:       name,
		Timeout:    "5s",
		MaxTimeout: "",
	}

	if mp, ok := r.macros[name]; ok {
		info.Description = mp.Info.Description
		info.Priority = mp.Info.Priority
		info.Version = mp.Info.Version
		info.Triggers = mp.Info.Triggers
		info.Internal = mp.Info.Internal
		if mp.Info.Timeout != "" {
			info.Timeout = mp.Info.Timeout
		}
		if mp.Info.MaxTimeout != "" {
			info.MaxTimeout = mp.Info.MaxTimeout
		}
	}

	return info
}

func (r *Registry) ResolveMergedToolInfoForConfig(name string, cfg *config.Config) *protocol.ToolInfo {
	r.mu.RLock()
	defer r.mu.RUnlock()
	return r.resolveMergedToolInfoLocked(name, cfg)
}

func (r *Registry) ResolveMergedToolInfoLocked(name string) *protocol.ToolInfo {
	return r.resolveMergedToolInfoLocked(name, r.cfg)
}

func (r *Registry) resolveMergedToolInfoLocked(name string, cfg *config.Config) *protocol.ToolInfo {
	var runtime *protocol.ToolInfo
	if tp, ok := r.tools[name]; ok {
		info := tp.Info
		runtime = &info
	}
	info := mergeToolInfoForConfig(name, runtime, cfg)
	return &info
}

func mergeToolInfoForConfig(name string, runtime *protocol.ToolInfo, cfg *config.Config) protocol.ToolInfo {
	info := protocol.ToolInfo{
		Name:       name,
		Timeout:    "30s",
		MaxTimeout: "-1",
	}

	if runtime != nil {
		info.Description = runtime.Description
		info.Parameters = runtime.Parameters
		info.ToolHint = runtime.ToolHint
		if runtime.Timeout != "" {
			info.Timeout = runtime.Timeout
		}
		if runtime.MaxTimeout != "" {
			info.MaxTimeout = runtime.MaxTimeout
		}
	}

	if cfg != nil {
		if override, ok := cfg.ToolOverrides[name]; ok {
			if override.Description != "" {
				info.Description = override.Description
			}
			if override.Parameters != nil {
				info.Parameters = override.Parameters
			}
			if override.Timeout != "" {
				info.Timeout = override.Timeout
			}
			if override.MaxTimeout != "" {
				info.MaxTimeout = override.MaxTimeout
			}
		}
	}

	return info
}

func (r *Registry) findBuiltinLocked(kind, name string) (string, *config.ServiceConfig) {
	if r.services == nil {
		return "", nil
	}

	for connName, dc := range r.services {
		var list []string
		if kind == "tool" {
			list = dc.Tools
		} else if kind == "plugin" {
			list = dc.Plugins
		} else {
			list = dc.Macros
		}
		for _, n := range list {
			if n == name {
				return connName, &dc
			}
		}
	}
	return "", nil
}

func (r *Registry) FindTool(name string) (*ToolProvider, string, error) {
	r.mu.RLock()
	defer r.mu.RUnlock()

	if tp, ok := r.tools[name]; ok {
		if tp.ConnID == "" {
			connName, dc := r.findBuiltinLocked("tool", name)
			if dc != nil {
				return tp, connName, nil
			}
		}
		return tp, "", nil
	}

	connName, dc := r.findBuiltinLocked("tool", name)
	if dc != nil {
		return nil, connName, nil
	}

	return nil, "", fmt.Errorf("tool not found: %s", name)
}

func (r *Registry) FindPlugin(name string) (*PluginProvider, string, error) {
	r.mu.RLock()
	defer r.mu.RUnlock()

	if pp, ok := r.plugins[name]; ok {
		if pp.ConnID == "" {
			connName, dc := r.findBuiltinLocked("plugin", name)
			if dc != nil {
				return pp, connName, nil
			}
		}
		return pp, "", nil
	}

	connName, dc := r.findBuiltinLocked("plugin", name)
	if dc != nil {
		return nil, connName, nil
	}

	return nil, "", fmt.Errorf("plugin not found: %s", name)
}

func (r *Registry) FindDirectConnForTool(name string) (string, *config.ServiceConfig) {
	r.mu.RLock()
	defer r.mu.RUnlock()
	return r.findBuiltinLocked("tool", name)
}

func (r *Registry) FindMacro(name string) (*MacroProvider, string, error) {
	r.mu.RLock()
	defer r.mu.RUnlock()

	if mp, ok := r.macros[name]; ok {
		if mp.ConnID == "" {
			connName, dc := r.findBuiltinLocked("macro", name)
			if dc != nil {
				return mp, connName, nil
			}
		}
		return mp, "", nil
	}

	connName, dc := r.findBuiltinLocked("macro", name)
	if dc != nil {
		return nil, connName, nil
	}

	return nil, "", fmt.Errorf("macro not found: %s", name)
}

func (r *Registry) RuntimeMacroInfo(name, connID string) *protocol.MacroInfo {
	r.mu.RLock()
	defer r.mu.RUnlock()
	mp := r.macros[name]
	if mp == nil || mp.ConnID == "" || mp.ConnID != connID {
		return nil
	}
	info := mp.Info
	return &info
}

func (r *Registry) FindDirectConnForMacro(name string) (string, *config.ServiceConfig) {
	r.mu.RLock()
	defer r.mu.RUnlock()
	return r.findBuiltinLocked("macro", name)
}

// ReservePendingCall records a daemon-generated invocation ID. It never
// replaces an active call: callers must fail the invocation if this returns
// false.
func (r *Registry) ReservePendingCall(pc *PendingCall) bool {
	r.mu.Lock()
	defer r.mu.Unlock()
	return r.reservePendingCallLocked(pc)
}

func (r *Registry) reservePendingCallLocked(pc *PendingCall) bool {
	if _, exists := r.pendingCalls[pc.ToolCallID]; exists {
		return false
	}
	r.pendingCalls[pc.ToolCallID] = pc
	return true
}

func (r *Registry) RegisterPendingCall(pc *PendingCall) bool {
	return r.ReservePendingCall(pc)
}

func (r *Registry) UnregisterPendingCall(toolCallID string) {
	r.mu.Lock()
	defer r.mu.Unlock()
	delete(r.pendingCalls, toolCallID)
}

func (r *Registry) ClaimPendingCallForConnValidated(toolCallID, connID string, validate func(*PendingCall) error) (*PendingCall, error, bool) {
	r.mu.Lock()
	defer r.mu.Unlock()
	pc, ok := r.pendingCalls[toolCallID]
	if !ok || pc.claimed || pc.ConnID != connID {
		return nil, nil, false
	}
	validationErr := validate(pc)
	pc.claimed = true
	delete(r.pendingCalls, toolCallID)
	return pc, validationErr, true
}
func (r *Registry) ClaimPendingCall(toolCallID string) (*PendingCall, bool) {
	r.mu.Lock()
	defer r.mu.Unlock()
	pc, ok := r.pendingCalls[toolCallID]
	if !ok || pc.claimed {
		return nil, false
	}
	pc.claimed = true
	delete(r.pendingCalls, toolCallID)
	return pc, true
}

func (r *Registry) AckPendingCall(toolCallID string, owner ...string) (*PendingCall, bool) {
	r.mu.Lock()
	defer r.mu.Unlock()
	pc, ok := r.pendingCalls[toolCallID]
	if !ok || pc.claimed || pc.Acked || (len(owner) > 0 && pc.ConnID != owner[0]) {
		return nil, false
	}
	pc.Acked = true
	return pc, true
}

func (r *Registry) RegisterPendingPluginCall(pc *PendingPluginCall) {
	r.mu.Lock()
	defer r.mu.Unlock()
	r.pendingPluginCalls[pc.PluginCallID] = pc
}

func (r *Registry) UnregisterPendingPluginCall(pluginCallID string) {
	r.mu.Lock()
	defer r.mu.Unlock()
	delete(r.pendingPluginCalls, pluginCallID)
}

func (r *Registry) ClaimPendingPluginCall(pluginCallID string, owner ...string) (*PendingPluginCall, bool) {
	r.mu.Lock()
	defer r.mu.Unlock()
	ppc, ok := r.pendingPluginCalls[pluginCallID]
	if !ok || ppc.claimed || (len(owner) > 0 && ppc.ConnID != owner[0]) {
		return nil, false
	}
	ppc.claimed = true
	delete(r.pendingPluginCalls, pluginCallID)
	return ppc, true
}

func (r *Registry) RegisterPendingMacroCall(pc *PendingMacroCall) {
	r.mu.Lock()
	defer r.mu.Unlock()
	r.pendingMacroCalls[pc.MacroCallID] = pc
}

func (r *Registry) UnregisterPendingMacroCall(macroCallID string) {
	r.mu.Lock()
	defer r.mu.Unlock()
	delete(r.pendingMacroCalls, macroCallID)
}

func (r *Registry) ClaimPendingMacroCall(macroCallID string, owner ...string) (*PendingMacroCall, bool) {
	r.mu.Lock()
	defer r.mu.Unlock()
	pmc, ok := r.pendingMacroCalls[macroCallID]
	if !ok || pmc.claimed || (len(owner) > 0 && pmc.ConnID != owner[0]) {
		return nil, false
	}
	pmc.claimed = true
	delete(r.pendingMacroCalls, macroCallID)
	return pmc, true
}

func (r *Registry) FindDirectConnForPlugin(name string) (string, *config.ServiceConfig) {
	r.mu.RLock()
	defer r.mu.RUnlock()
	return r.findBuiltinLocked("plugin", name)
}

func (r *Registry) GetPendingCallsForLeaf(leafID string) []*PendingCall {
	r.mu.RLock()
	defer r.mu.RUnlock()
	var calls []*PendingCall
	for _, pc := range r.pendingCalls {
		if pc.LeafID == leafID {
			calls = append(calls, pc)
		}
	}
	return calls
}

// ActiveToolCallsForLeaf returns an immutable, argument-free public snapshot.
// Sorting by tool_call_id makes the projection deterministic across map order.
func (r *Registry) ActiveToolCallsForLeaf(leafID string) []protocol.ActiveToolCall {
	r.mu.RLock()
	defer r.mu.RUnlock()
	calls := make([]protocol.ActiveToolCall, 0)
	for _, pc := range r.pendingCalls {
		if pc.LeafID == leafID && !pc.claimed && !pc.GenericInvocation {
			calls = append(calls, protocol.ActiveToolCall{
				ToolCallID: pc.ToolCallID,
				Name:       pc.ToolName,
				TurnID:     pc.SourceTurnID,
			})
		}
	}
	sort.Slice(calls, func(i, j int) bool { return calls[i].ToolCallID < calls[j].ToolCallID })
	return calls
}

func (r *Registry) GetPendingMacroCallsForLeaf(leafID string) []*PendingMacroCall {
	r.mu.RLock()
	defer r.mu.RUnlock()
	var calls []*PendingMacroCall
	for _, pc := range r.pendingMacroCalls {
		if pc.LeafID == leafID {
			calls = append(calls, pc)
		}
	}
	return calls
}

// claimMacroCallsForConn claims the eager disconnect sweep. Delivery and
// watchdog cancellation follow after the registry lock is released.
func (r *Registry) claimMacroCallsForConn(connID string) []*PendingMacroCall {
	r.mu.Lock()
	defer r.mu.Unlock()
	var calls []*PendingMacroCall
	for id, pmc := range r.pendingMacroCalls {
		if pmc.ConnID == connID && !pmc.claimed {
			pmc.claimed = true
			calls = append(calls, pmc)
			delete(r.pendingMacroCalls, id)
		}
	}
	return calls
}

func completeDisconnectedMacros(calls []*PendingMacroCall, onAbort func(string)) {
	for _, pmc := range calls {
		select {
		case pmc.ResultCh <- MacroCallResult{Err: fmt.Errorf("macro aborted: connection closed")}:
		default:
		}
		if onAbort != nil {
			onAbort(pmc.MacroCallID)
		}
	}
}

func (r *Registry) AbortPendingMacroCallsForConn(connID string, onAbort func(macroCallID string)) {
	completeDisconnectedMacros(r.claimMacroCallsForConn(connID), onAbort)
}

func (r *Registry) AllToolNames() []string {
	r.mu.RLock()
	defer r.mu.RUnlock()
	seen := make(map[string]bool)
	for name := range r.tools {
		seen[name] = true
	}
	if r.services != nil {
		for _, dc := range r.services {
			for _, name := range dc.Tools {
				seen[name] = true
			}
		}
	}
	for _, name := range r.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 (r *Registry) AllPluginNames() []string {
	r.mu.RLock()
	defer r.mu.RUnlock()
	seen := make(map[string]bool)
	for name := range r.plugins {
		seen[name] = true
	}
	if r.services != nil {
		for _, dc := range r.services {
			for _, name := range dc.Plugins {
				seen[name] = true
			}
		}
	}
	for _, name := range r.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 (r *Registry) AllMacroNames() []string {
	r.mu.RLock()
	defer r.mu.RUnlock()
	seen := make(map[string]bool)
	for name := range r.macros {
		seen[name] = true
	}
	if r.services != nil {
		for _, dc := range r.services {
			for _, name := range dc.Macros {
				seen[name] = true
			}
		}
	}
	out := make([]string, 0, len(seen))
	for name := range seen {
		out = append(out, name)
	}
	sort.Strings(out)
	return out
}

func (r *Registry) Shutdown() {
	r.mu.Lock()
	defer r.mu.Unlock()
	r.tools = make(map[string]*ToolProvider)
	r.plugins = make(map[string]*PluginProvider)
	r.macros = make(map[string]*MacroProvider)
	// Capability waiters observe their captured connection's closure. Keep
	// terminal claims available until that path (or a racing result) completes.
}

// PendingCallOwned validates liveness against the exact admitted connection.
func (r *Registry) PendingCallOwned(kind, id, connID string) bool {
	r.mu.RLock()
	defer r.mu.RUnlock()
	switch kind {
	case "tool":
		pc := r.pendingCalls[id]
		return pc != nil && !pc.claimed && pc.ConnID == connID
	case "plugin":
		pc := r.pendingPluginCalls[id]
		return pc != nil && !pc.claimed && pc.ConnID == connID
	case "macro":
		pc := r.pendingMacroCalls[id]
		return pc != nil && !pc.claimed && pc.ConnID == connID
	}
	return false
}

// AbortPendingCallsForConn retires all outstanding work before a replacement
// provider can be used. Completion already claimed before EOF remains final.
func (r *Registry) AbortPendingCallsForConn(connID string, cancelWatchdog func(kind, id string)) {
	r.mu.Lock()
	var tools []*PendingCall
	var plugins []*PendingPluginCall
	for id, pc := range r.pendingCalls {
		if pc.ConnID == connID {
			pc.claimed = true
			delete(r.pendingCalls, id)
			tools = append(tools, pc)
		}
	}
	for id, pc := range r.pendingPluginCalls {
		if pc.ConnID == connID {
			pc.claimed = true
			delete(r.pendingPluginCalls, id)
			plugins = append(plugins, pc)
		}
	}
	r.mu.Unlock()
	for _, pc := range tools {
		if cancelWatchdog != nil {
			cancelWatchdog("tool", pc.ToolCallID)
		}
		select {
		case pc.ResultCh <- ToolCallResult{Err: fmt.Errorf("tool aborted: connection closed")}:
		default:
		}
	}
	for _, pc := range plugins {
		if cancelWatchdog != nil {
			cancelWatchdog("plugin", pc.PluginCallID)
		}
		select {
		case pc.ResultCh <- PluginCallResult{Err: fmt.Errorf("plugin aborted: connection closed")}:
		default:
		}
	}
	r.AbortPendingMacroCallsForConn(connID, func(id string) {
		if cancelWatchdog != nil {
			cancelWatchdog("macro", id)
		}
	})
}

// SetProviderExports is called only with the provider owner's inventory. Peer
// registration and metadata paths can never claim these entries.
func (r *Registry) SetProviderExports(infos []protocol.MacroInfo) {
	r.mu.Lock()
	defer r.mu.Unlock()
	for name, p := range r.macros {
		if p.Source == "provider-export" {
			delete(r.macros, name)
		}
	}
	for _, info := range infos {
		if _, err := config.ParseProviderExportMacro(info.Name); err == nil {
			r.macros[info.Name] = &MacroProvider{Info: info, Source: "provider-export"}
		}
	}
	r.infoCond.Broadcast()
}