pkg/service/ipc.go

package service

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log/slog"
	"reflect"
	"strings"
	"sync"
	"time"

	"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/tools"
	"git.cafe/ezterry/ez-agent/pkg/watchdog"
)

type IPCCaller struct {
	registry              *Registry
	pool                  *ProcessPool
	server                *Server
	ensureDirect          func(string, *config.ServiceConfig) (*Connection, error)
	recoverDirect         func(context.Context, string, *config.ServiceConfig, *Connection) (*Connection, error)
	beforeMacroDispatch   func()
	beforeMacroCloseClaim func()
	beforeToolAdmission   func()
	beforeToolCloseClaim  func()
	beforeToolAbort       func()
	afterToolTimeouts     func(time.Duration, time.Duration)
}

func (c *IPCCaller) ensureDirectConn(name string, dc *config.ServiceConfig) (*Connection, error) {
	if c.ensureDirect != nil {
		return c.ensureDirect(name, dc)
	}
	return c.server.ensureDirectConn(name, dc)
}

func NewIPCCaller(registry *Registry, pool *ProcessPool, server *Server) *IPCCaller {
	return &IPCCaller{
		registry: registry,
		pool:     pool,
		server:   server,
	}
}

func (c *IPCCaller) liveToolProvider(name string) (*Connection, *ToolProvider) {
	tp, _, err := c.registry.FindTool(name)
	if err != nil || tp == nil || tp.ConnID == "" {
		return nil, tp
	}
	return c.lookupConn(tp.ConnID), tp
}

func (c *IPCCaller) livePluginProvider(name string) (*Connection, *PluginProvider) {
	pp, _, err := c.registry.FindPlugin(name)
	if err != nil || pp == nil || pp.ConnID == "" {
		return nil, pp
	}
	return c.lookupConn(pp.ConnID), pp
}

func (c *IPCCaller) liveMacroProvider(name string) (*Connection, *MacroProvider) {
	mp, _, err := c.registry.FindMacro(name)
	if err != nil || mp == nil || mp.ConnID == "" {
		return nil, mp
	}
	return c.lookupConn(mp.ConnID), mp
}

func (c *IPCCaller) resolveConnection(kind, name string) (*Connection, *ToolProvider, *PluginProvider, *MacroProvider, error) {
	if kind == "tool" {
		tp, builtinName, err := c.registry.FindTool(name)
		if err != nil {
			return nil, nil, nil, nil, err
		}
		if tp != nil && tp.ConnID != "" {
			conn := c.lookupConn(tp.ConnID)
			if conn != nil {
				return conn, tp, nil, nil, nil
			}
		}
		if builtinName != "" || (tp != nil && tp.ConnID == "") {
			dcName, dc := c.registry.FindDirectConnForTool(name)
			if dc != nil {
				if _, err := c.ensureDirectConn(dcName, dc); err != nil {
					return nil, nil, nil, nil, fmt.Errorf("ensure direct conn for tool %s: %w", name, err)
				}
				if owner, tp2 := c.liveToolProvider(name); owner != nil {
					return owner, tp2, nil, nil, nil
				}
				return nil, nil, nil, nil, fmt.Errorf("tool connection not available after service start: %s", name)
			}
		}
		return nil, nil, nil, nil, fmt.Errorf("tool connection not available: %s", name)
	}

	if kind == "plugin" {
		pp, builtinName, err := c.registry.FindPlugin(name)
		if err != nil {
			return nil, nil, nil, nil, err
		}
		if pp != nil && pp.ConnID != "" {
			conn := c.lookupConn(pp.ConnID)
			if conn != nil {
				return conn, nil, pp, nil, nil
			}
		}
		if builtinName != "" || (pp != nil && pp.ConnID == "") {
			dcName, dc := c.registry.FindDirectConnForPlugin(name)
			if dc != nil {
				if _, err := c.ensureDirectConn(dcName, dc); err != nil {
					return nil, nil, nil, nil, fmt.Errorf("ensure direct conn for plugin %s: %w", name, err)
				}
				if owner, pp2 := c.livePluginProvider(name); owner != nil {
					return owner, nil, pp2, nil, nil
				}
				return nil, nil, nil, nil, fmt.Errorf("plugin connection not available after service start: %s", name)
			}
		}
		return nil, nil, nil, nil, fmt.Errorf("plugin connection not available: %s", name)
	}

	mp, builtinName, err := c.registry.FindMacro(name)
	if err != nil {
		return nil, nil, nil, nil, err
	}
	if mp != nil && mp.ConnID != "" {
		conn := c.lookupConn(mp.ConnID)
		if conn != nil {
			return conn, nil, nil, mp, nil
		}
	}
	if builtinName != "" || (mp != nil && mp.ConnID == "") {
		dcName, dc := c.registry.FindDirectConnForMacro(name)
		if dc != nil {
			if _, err := c.ensureDirectConn(dcName, dc); err != nil {
				return nil, nil, nil, nil, fmt.Errorf("ensure direct conn for macro %s: %w", name, err)
			}
			if owner, mp2 := c.liveMacroProvider(name); owner != nil {
				return owner, nil, nil, mp2, nil
			}
			return nil, nil, nil, nil, fmt.Errorf("macro connection not available after service start: %s", name)
		}
	}
	return nil, nil, nil, nil, fmt.Errorf("macro connection not available: %s", name)
}

func (c *IPCCaller) lookupConn(connID string) *Connection {
	c.server.mu.RLock()
	defer c.server.mu.RUnlock()
	conn, ok := c.server.connections[connID]
	if !ok || conn == nil {
		return nil
	}
	return conn
}

func (c *IPCCaller) captureToolOwner(name string) (*Connection, protocol.ToolInfo, bool) {
	c.server.mu.RLock()
	defer c.server.mu.RUnlock()
	c.registry.mu.RLock()
	defer c.registry.mu.RUnlock()
	provider := c.registry.tools[name]
	if provider == nil || provider.ConnID == "" {
		return nil, protocol.ToolInfo{}, false
	}
	conn := c.server.connections[provider.ConnID]
	if conn == nil {
		return nil, protocol.ToolInfo{}, false
	}
	return conn, provider.Info, true
}

var errOfferedToolDisconnected = errors.New("offered tool provider is no longer connected")

func (c *IPCCaller) reserveBoundToolCall(name string, conn *Connection, cfg *config.Config, pending *PendingCall, offered *protocol.ToolInfo) (protocol.ToolInfo, error) {
	c.server.mu.RLock()
	defer c.server.mu.RUnlock()
	c.registry.mu.Lock()
	defer c.registry.mu.Unlock()
	if c.server.connections[conn.ID] != conn || toolConnectionClosed(conn) {
		return protocol.ToolInfo{}, fmt.Errorf("%w: %s", errOfferedToolDisconnected, name)
	}
	provider := c.registry.tools[name]
	if provider == nil || provider.ConnID != conn.ID {
		return protocol.ToolInfo{}, fmt.Errorf("offered tool provider no longer owns tool: %s", name)
	}
	info := mergeToolInfoForConfig(name, &provider.Info, cfg)
	if offered != nil && (info.Description != offered.Description || !reflect.DeepEqual(info.Parameters, offered.Parameters)) {
		return protocol.ToolInfo{}, fmt.Errorf("recovered tool definition differs from offered tool: %s", name)
	}
	if !c.registry.reservePendingCallLocked(pending) {
		return protocol.ToolInfo{}, fmt.Errorf("tool call admission failed: trusted invocation ID collision")
	}
	return info, nil
}

type boundToolCaller struct {
	caller      *IPCCaller
	toolName    string
	mu          sync.Mutex
	conn        *Connection
	cfg         *config.Config
	offered     protocol.ToolInfo
	serviceName string
	service     *config.ServiceConfig
}

func (b *boundToolCaller) CallTool(ctx context.Context, tc agent.OpenAIToolCall, leafID, turnID, rootID, cwd string) agent.ToolCallHandle {
	return b.callTool(ctx, tc, leafID, turnID, rootID, cwd)
}

func (b *boundToolCaller) callTool(ctx context.Context, tc agent.OpenAIToolCall, leafID, turnID, rootID, cwd string, runtimeIDs ...string) agent.ToolCallHandle {
	if tc.Function.Name != b.toolName {
		return immediateToolCallHandle(syntheticToolResult(tc.ID, tc.Function.Name, "tool call does not match offered provider binding"))
	}
	b.mu.Lock()
	conn := b.conn
	b.mu.Unlock()
	return b.caller.callToolBound(ctx, tc, leafID, turnID, rootID, cwd, conn, b.cfg, b, runtimeIDs...)
}

func toolConnectionClosed(conn *Connection) bool {
	if conn == nil || conn.apiConn == nil {
		return true
	}
	select {
	case <-conn.apiConn.Closed():
		return true
	default:
		return false
	}
}

func (b *boundToolCaller) sameService(conn *Connection) bool {
	return conn != nil && b.service != nil && conn.launchedServiceName == b.serviceName && reflect.DeepEqual(conn.launchedService, b.service)
}

// Only daemon-launched service identity authorizes recovery. An announcement
// containing the same tool name is not evidence of the same provider.
func (b *boundToolCaller) recover(ctx context.Context, stale *Connection) (*Connection, error) {
	if err := ctx.Err(); err != nil {
		return nil, err
	}
	if owner, _, live := b.caller.captureToolOwner(b.toolName); live && owner != stale && !b.sameService(owner) {
		return nil, fmt.Errorf("offered tool provider replaced by another service: %s", b.toolName)
	}
	recover := b.caller.recoverDirect
	if recover == nil {
		recover = func(ctx context.Context, name string, cfg *config.ServiceConfig, stale *Connection) (*Connection, error) {
			return b.caller.server.pool.RecoverDirectConn(ctx, name, cfg, stale, b.caller.server.serviceSpawnCallbacks())
		}
	}
	conn, err := recover(ctx, b.serviceName, b.service, stale)
	if err != nil {
		return nil, fmt.Errorf("recover configured tool service %s: %w", b.serviceName, err)
	}
	if !b.sameService(conn) {
		return nil, fmt.Errorf("recovered tool provider does not match configured service: %s", b.toolName)
	}
	// Startup claims ownership before metadata arrives. Some configured peers
	// omit announce, so request missing metadata on this exact connection too.
	owner, runtime, live := b.caller.captureToolOwner(b.toolName)
	if !live || owner != conn {
		return nil, fmt.Errorf("offered tool provider no longer owns tool: %s", b.toolName)
	}
	if runtime.Description == "" && runtime.Parameters == nil {
		if err := requestRecoveryToolInfo(ctx, conn, b.toolName); err != nil {
			return nil, err
		}
	}
	if err := ctx.Err(); err != nil {
		return nil, err
	}
	return conn, nil
}

// Startup readiness may already be complete because another tool's metadata
// arrived. Correlate this request separately, on the exact recovered connection.
func requestRecoveryToolInfo(ctx context.Context, conn *Connection, name string) error {
	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()
	requestID := session.NewID("rti_")
	ready := make(chan struct{})
	conn.chMu.Lock()
	if conn.toolInfoWaiters == nil {
		conn.toolInfoWaiters = make(map[string]chan struct{})
	}
	conn.toolInfoWaiters[requestID] = ready
	conn.chMu.Unlock()
	defer func() {
		conn.chMu.Lock()
		delete(conn.toolInfoWaiters, requestID)
		conn.chMu.Unlock()
	}()
	if err := conn.apiConn.SendToolInfoRequest(ctx, []string{name}, requestID); err != nil {
		return fmt.Errorf("request recovered tool metadata: %w", err)
	}
	select {
	case <-ready:
		return nil
	case <-ctx.Done():
		return fmt.Errorf("recovered tool metadata unavailable: %s: %w", name, ctx.Err())
	case <-conn.apiConn.Closed():
		return fmt.Errorf("recovered tool provider disconnected: %s", name)
	}
}

type ToolCallHandle struct {
	caller       *IPCCaller
	key          watchdog.Key
	toolName     string
	conn         *Connection
	providerDone <-chan struct{}
	pending      *PendingCall
	ready        chan struct{}
	initial      ToolCallResult
	initialErr   error
	parallel     bool
	resultCached bool
}

// abortToolCall claims ownership before sending tool_abort, so a racing result
// cannot complete normally once the run context has been cancelled. The
// captured connection remains usable after the claim removes registry ownership.
func (c *IPCCaller) abortToolCall(key watchdog.Key, conn *Connection, pending *PendingCall, err error) {
	c.registry.ClaimPendingCall(key.ID)
	pending.cancelResult(err)
	if c.beforeToolAbort != nil {
		c.beforeToolAbort()
	}
	if conn != nil && conn.apiConn != nil {
		_ = conn.apiConn.SendToolAbort(context.Background(), key.ID)
	}
	c.server.wdMgr.Cancel(key)
}

func syntheticToolResult(callID, toolName, message string) protocol.PendingTurn {
	metadata, _ := json.Marshal(map[string]interface{}{"is_error": true})
	return protocol.PendingTurn{Kind: "tool_result", ContentType: "text", Content: message, ToolCallID: callID, ToolName: toolName, Advanced: &protocol.PendingTurnAdvanced{OtherMeta: string(metadata)}}
}

func immediateToolCallHandle(turn protocol.PendingTurn) *ToolCallHandle {
	ch := make(chan struct{})
	close(ch)
	return &ToolCallHandle{ready: ch, initial: ToolCallResult{Result: protocol.ToolResult{Turn: turn}}, resultCached: true}
}

func (h *ToolCallHandle) Parallel() bool { return h.parallel }

func (h *ToolCallHandle) WaitResult(ctx context.Context) (protocol.PendingTurn, func(*protocol.SteerAccepted, error)) {
	<-h.ready
	var result ToolCallResult
	var err error
	if h.initialErr != nil || h.resultCached {
		result, err = h.initial, h.initialErr
		if h.pending != nil && err == nil && ctx.Err() != nil {
			err = fmt.Errorf("tool aborted: %s", h.toolName)
			if result.OnAdmitted != nil {
				result.OnAdmitted(nil, err)
			}
			h.caller.abortToolCall(h.key, h.conn, h.pending, err)
			result = ToolCallResult{}
		}
	} else {
		result, err = h.caller.roundTrip(ctx, h.pending, h.key, "tool", h.toolName, h.conn, h.providerDone)
	}
	if err != nil {
		return syntheticToolResult(h.key.ID, h.toolName, err.Error()), result.OnAdmitted
	}
	if result.Err != nil {
		return syntheticToolResult(h.key.ID, h.toolName, fmt.Sprintf("tool error: %v", result.Err)), result.OnAdmitted
	}
	if err := validateToolResultBoundary(result.Result); err != nil {
		return syntheticToolResult(h.key.ID, h.toolName, fmt.Sprintf("tool error: %v", err)), result.OnAdmitted
	}
	turn := result.Result.Turn
	if turn.Content == "" && turn.AttachmentBlob == nil {
		return syntheticToolResult(h.key.ID, h.toolName, "tool returned empty result"), result.OnAdmitted
	}
	return turn, result.OnAdmitted
}
func (c *IPCCaller) claimToolConnectionClosed(key watchdog.Key, toolName string) (ToolCallResult, bool) {
	if c.beforeToolCloseClaim != nil {
		c.beforeToolCloseClaim()
	}
	if _, ok := c.registry.ClaimPendingCall(key.ID); !ok {
		return ToolCallResult{}, false
	}
	c.server.wdMgr.Cancel(key)
	return ToolCallResult{Err: fmt.Errorf("tool aborted: connection closed: %s", toolName)}, true
}

func (c *IPCCaller) awaitClaimedToolResult(ctx context.Context, pending *PendingCall, key watchdog.Key, opKind, opName string, conn *Connection) (ToolCallResult, error) {
	select {
	case result := <-pending.ResultCh:
		if ctx.Err() != nil {
			if result.OnAdmitted != nil {
				result.OnAdmitted(nil, fmt.Errorf("%s aborted: %s", opKind, opName))
			}
			c.abortToolCall(key, conn, pending, fmt.Errorf("%s aborted: %s", opKind, opName))
			return ToolCallResult{}, fmt.Errorf("%s aborted: %s", opKind, opName)
		}
		c.server.wdMgr.Cancel(key)
		return result, nil
	case <-ctx.Done():
		c.abortToolCall(key, conn, pending, fmt.Errorf("%s aborted: %s", opKind, opName))
		return ToolCallResult{}, fmt.Errorf("%s aborted: %s", opKind, opName)
	}
}

func (c *IPCCaller) CallTool(ctx context.Context, tc agent.OpenAIToolCall, leafID, turnID, rootID, cwd string) agent.ToolCallHandle {
	toolName := tc.Function.Name

	conn, _, _, _, err := c.resolveConnection("tool", toolName)
	if err != nil {
		return immediateToolCallHandle(syntheticToolResult(tc.ID, toolName, err.Error()))
	}
	return c.callToolBound(ctx, tc, leafID, turnID, rootID, cwd, conn, c.server.configSnapshot(), nil)
}

// callToolInvocation uses the daemon-allocated tc.ID as the runtime ID. The
// caller must first check that the tool is active for the target leaf.
func (c *IPCCaller) callToolInvocation(ctx context.Context, tc agent.OpenAIToolCall, leafID, rootID, cwd string, cfg *config.Config) agent.ToolCallHandle {
	_, bindings := c.ResolveBoundToolsForConfigContext(ctx, []string{tc.Function.Name}, cfg)
	binding, ok := bindings[tc.Function.Name].(*boundToolCaller)
	if !ok {
		return immediateToolCallHandle(syntheticToolResult(tc.ID, tc.Function.Name, fmt.Sprintf("offered tool provider is unavailable: %s", tc.Function.Name)))
	}
	return binding.callTool(ctx, tc, leafID, "", rootID, cwd, tc.ID)
}

func (c *IPCCaller) callToolBound(ctx context.Context, tc agent.OpenAIToolCall, leafID, turnID, rootID, cwd string, conn *Connection, cfg *config.Config, binding *boundToolCaller, runtimeIDs ...string) agent.ToolCallHandle {
	toolName := tc.Function.Name
	if ctx.Err() != nil {
		return immediateToolCallHandle(syntheticToolResult(tc.ID, toolName, fmt.Sprintf("tool aborted: %s", toolName)))
	}
	if conn == nil || conn.apiConn == nil {
		return immediateToolCallHandle(syntheticToolResult(tc.ID, toolName, fmt.Sprintf("offered tool provider is unavailable: %s", toolName)))
	}
	args := make(map[string]interface{})
	if tc.Function.Arguments != "" {
		if err := json.Unmarshal([]byte(tc.Function.Arguments), &args); err != nil {
			return immediateToolCallHandle(syntheticToolResult(tc.ID, toolName, fmt.Sprintf("invalid tool arguments: %v", err)))
		}
	}

	var runtimeID string
	if len(runtimeIDs) > 0 {
		runtimeID = runtimeIDs[0]
	} else {
		runtimeID = session.NewID("tc_")
	}
	toolCallIPC := protocol.ToolCallIPC{Type: "tool_call", ToolCallID: runtimeID, Name: tc.Function.Name, Arguments: args, LeafID: leafID, TurnID: turnID, RootID: rootID, Cwd: cwd}

	resultCh := make(chan ToolCallResult, 1)
	ackCh := make(chan ToolCallAckResult, 1)
	pendingCall := &PendingCall{ToolCallID: runtimeID, ProviderToolCallID: tc.ID, ToolName: tc.Function.Name, LeafID: leafID, SourceTurnID: turnID, GenericInvocation: len(runtimeIDs) > 0, ConnID: conn.ID, ResultCh: resultCh, AckCh: ackCh}
	pendingCall.CommandInterpreter, _ = args["interpreter"].(string)
	if c.beforeToolAdmission != nil {
		c.beforeToolAdmission()
	}
	if ctx.Err() != nil {
		return immediateToolCallHandle(syntheticToolResult(tc.ID, toolName, fmt.Sprintf("tool aborted: %s", toolName)))
	}
	var offered *protocol.ToolInfo
	if binding != nil && binding.service != nil {
		offered = &binding.offered
	}
	info, err := c.reserveBoundToolCall(toolName, conn, cfg, pendingCall, nil)
	if errors.Is(err, errOfferedToolDisconnected) && offered != nil {
		// Admission has not sent anything. Recover once; never retry a failed
		// send or an in-flight call whose execution status is unknown.
		staleID := conn.ID
		conn, err = binding.recover(ctx, conn)
		if err == nil {
			pendingCall.ConnID = conn.ID
			info, err = c.reserveBoundToolCall(toolName, conn, cfg, pendingCall, offered)
			if err == nil {
				binding.mu.Lock()
				binding.conn = conn
				binding.mu.Unlock()
				slog.Info("configured tool provider recovered", "service", binding.serviceName, "tool", toolName, "old_conn_id", staleID, "conn_id", conn.ID)
			}
		}
	}
	if err != nil {
		return immediateToolCallHandle(syntheticToolResult(tc.ID, toolName, err.Error()))
	}
	if info.Parameters != nil {
		if missing := tools.ValidateRequired(info.Parameters, args); len(missing) > 0 {
			c.registry.UnregisterPendingCall(runtimeID)
			return immediateToolCallHandle(syntheticToolResult(tc.ID, toolName, fmt.Sprintf("missing required parameters: %s", strings.Join(missing, ", "))))
		}
	}

	apiConn := conn.apiConn
	providerDone := apiConn.Closed()

	wdTimeout, maxTimeout := parseToolTimeouts(info.Timeout, info.MaxTimeout)
	if c.afterToolTimeouts != nil {
		c.afterToolTimeouts(wdTimeout, maxTimeout)
	}
	key := watchdog.Key{Type: "tool", ID: runtimeID}

	cb := func(k watchdog.Key, reason watchdog.ExpiryReason) {
		if _, ok := c.registry.ClaimPendingCall(k.ID); !ok {
			return
		}
		var err error
		switch reason {
		case watchdog.WatchdogExceeded:
			err = fmt.Errorf("tool timeout (watchdog): %s", toolName)
		case watchdog.MaxExceeded:
			err = fmt.Errorf("tool timeout (max): %s", toolName)
		case watchdog.Cancelled:
			err = fmt.Errorf("tool aborted: %s", toolName)
		}
		select {
		case resultCh <- ToolCallResult{Err: err}:
		default:
		}
	}
	c.server.wdMgr.Register(key, wdTimeout, maxTimeout, cb)

	if ctx.Err() != nil {
		c.server.wdMgr.Cancel(key)
		c.registry.UnregisterPendingCall(runtimeID)
		return immediateToolCallHandle(syntheticToolResult(tc.ID, toolName, fmt.Sprintf("tool aborted: %s", toolName)))
	}
	if err := apiConn.SendToolCall(ctx, toolCallIPC); err != nil {
		c.server.wdMgr.Cancel(watchdog.Key{Type: "tool", ID: runtimeID})
		c.registry.UnregisterPendingCall(runtimeID)
		return immediateToolCallHandle(syntheticToolResult(tc.ID, toolName, fmt.Sprintf("tool call send error: %v", err)))
	}

	h := &ToolCallHandle{caller: c, key: key, toolName: toolName, conn: conn, providerDone: providerDone, pending: pendingCall, ready: make(chan struct{})}
	select {
	case result := <-resultCh:
		if ctx.Err() != nil {
			if result.OnAdmitted != nil {
				result.OnAdmitted(nil, fmt.Errorf("tool aborted: %s", toolName))
			}
			c.abortToolCall(key, conn, pendingCall, fmt.Errorf("tool aborted: %s", toolName))
			h.initialErr = fmt.Errorf("tool aborted: %s", toolName)
			break
		}
		c.server.wdMgr.Cancel(key)
		h.initial = result
		h.resultCached = true
	case ack := <-ackCh:
		if ack.Err != nil {
			h.initialErr = ack.Err
		} else if ack.Ack.Parallel {
			h.parallel = true
		} else {
			result, err := c.roundTrip(ctx, pendingCall, key, "tool", toolName, conn, providerDone)
			h.initial = result
			h.initialErr = err
			h.resultCached = true
		}
	case <-providerDone:
		if ctx.Err() != nil {
			c.abortToolCall(key, conn, pendingCall, fmt.Errorf("tool aborted: %s", toolName))
			h.initialErr = fmt.Errorf("tool aborted: %s", toolName)
			break
		}
		if result, ok := c.claimToolConnectionClosed(key, toolName); ok {
			if ctx.Err() != nil {
				c.abortToolCall(key, conn, pendingCall, fmt.Errorf("tool aborted: %s", toolName))
				h.initialErr = fmt.Errorf("tool aborted: %s", toolName)
			} else {
				h.initial = result
				h.resultCached = true
			}
			break
		}
		result, err := c.awaitClaimedToolResult(ctx, pendingCall, key, "tool", toolName, conn)
		h.initial = result
		h.initialErr = err
		h.resultCached = true
	case <-ctx.Done():
		c.abortToolCall(key, conn, pendingCall, fmt.Errorf("tool aborted: %s", toolName))
		h.initialErr = fmt.Errorf("tool aborted: %s", toolName)
	}
	close(h.ready)
	return h
}

func (c *IPCCaller) AbortPendingCalls(leafID string) {
	c.server.AbortPendingCallsForLeaf(leafID)
}

func directToolConfig(cfg *config.Config, name string) (string, *config.ServiceConfig) {
	if cfg == nil {
		return "", nil
	}
	for connName, dc := range cfg.Services {
		for _, tool := range dc.Tools {
			if tool == name {
				copy := dc
				return connName, &copy
			}
		}
	}
	return "", nil
}

func (c *IPCCaller) ResolveToolsForConfig(toolNames []string, cfg *config.Config) []agent.OpenAITool {
	result, _ := c.ResolveBoundToolsForConfig(toolNames, cfg)
	return result
}

func (c *IPCCaller) ResolveBoundToolsForConfig(toolNames []string, cfg *config.Config) ([]agent.OpenAITool, map[string]agent.ToolCaller) {
	return c.ResolveBoundToolsForConfigContext(context.Background(), toolNames, cfg)
}

func (c *IPCCaller) ResolveBoundToolsForConfigContext(ctx context.Context, toolNames []string, cfg *config.Config) ([]agent.OpenAITool, map[string]agent.ToolCaller) {
	var result []agent.OpenAITool
	bindings := make(map[string]agent.ToolCaller)
	for _, name := range toolNames {
		if ctx.Err() != nil {
			return nil, nil
		}
		conn, runtime, live := c.captureToolOwner(name)
		if !live {
			// Project service declarations only load an absent provider. The
			// registry's first live owner remains authoritative after startup.
			if connName, dc := directToolConfig(cfg, name); dc != nil {
				_, _ = c.ensureDirectConn(connName, dc)
				conn, runtime, live = c.captureToolOwner(name)
			}
		}
		if !live {
			continue
		}

		info := mergeToolInfoForConfig(name, &runtime, cfg)
		if runtime.Description == "" && runtime.Parameters == nil && conn.apiConn != nil {
			if c.requestMetadata(ctx, conn, "tool", []string{name}) != nil {
				return nil, nil
			}
			owner := conn
			conn, runtime, live = c.captureToolOwner(name)
			if !live || conn != owner {
				continue
			}
			info = mergeToolInfoForConfig(name, &runtime, cfg)
		}
		if info.Description == "" {
			continue
		}
		result = append(result, agent.OpenAITool{Type: "function", Function: agent.OpenAIFunct{Name: info.Name, Description: info.Description, Parameters: info.Parameters}})
		binding := &boundToolCaller{caller: c, toolName: name, conn: conn, cfg: cfg, offered: info}
		if cfg != nil && conn.launchedService != nil {
			if service, ok := cfg.Services[conn.launchedServiceName]; ok && service.Direct {
				copy := cloneServiceConfig(service)
				if reflect.DeepEqual(&copy, conn.launchedService) {
					binding.serviceName, binding.service = conn.launchedServiceName, &copy
				}
			}
		}
		bindings[name] = binding
	}
	return result, bindings
}

func (c *IPCCaller) ResolveTools(toolNames []string) []agent.OpenAITool {
	var result []agent.OpenAITool
	for _, name := range toolNames {
		info := c.registry.ResolveMergedToolInfo(name)
		if info != nil && info.Description != "" {
			result = append(result, agent.OpenAITool{
				Type: "function",
				Function: agent.OpenAIFunct{
					Name:        info.Name,
					Description: info.Description,
					Parameters:  info.Parameters,
				},
			})
			continue
		}
		conn, _, _, _, err := c.resolveConnection("tool", name)
		if err != nil || conn == nil {
			continue
		}
		if c.requestMetadata(context.Background(), conn, "tool", []string{name}) != nil {
			continue
		}
		info = c.registry.ResolveMergedToolInfo(name)
		if info != nil && info.Description != "" {
			result = append(result, agent.OpenAITool{
				Type: "function",
				Function: agent.OpenAIFunct{
					Name:        info.Name,
					Description: info.Description,
					Parameters:  info.Parameters,
				},
			})
		}
	}
	return result
}

func (c *IPCCaller) ResolveToolInfo(names []string) []protocol.ToolInfo {
	return c.ResolveToolInfoContext(context.Background(), names)
}

func (c *IPCCaller) ResolveToolInfoContext(ctx context.Context, names []string) []protocol.ToolInfo {
	infos := make([]protocol.ToolInfo, 0, len(names))
	for _, name := range names {
		if ctx.Err() != nil {
			return nil
		}
		info := c.registry.ResolveMergedToolInfo(name)
		if info != nil && (info.Description != "" || info.Parameters != nil || info.ToolHint != "") {
			infos = append(infos, *info)
			continue
		}
		conn, _, _, _, err := c.resolveConnection("tool", name)
		if err == nil && conn != nil {
			if c.requestMetadata(ctx, conn, "tool", []string{name}) == nil {
				info = c.registry.ResolveMergedToolInfo(name)
			}
		}
		if info != nil {
			infos = append(infos, *info)
		}
	}
	return infos
}

func (c *IPCCaller) CallPlugin(ctx context.Context, name, leafID, rootID, cwd, role string, turns []protocol.PendingTurn, configMap map[string]string) ([]protocol.PendingTurn, error) {
	conn, _, _, _, err := c.resolveConnection("plugin", name)
	if err != nil {
		return nil, err
	}

	pluginCallID := session.NewIDBytes("pc_", 8)
	pluginCall := protocol.PluginCallIPC{
		Type:         "plugin_call",
		PluginCallID: pluginCallID,
		Name:         name,
		LeafID:       leafID,
		RootID:       rootID,
		Cwd:          cwd,
		Role:         role,
		PendingTurns: turns,
		Config:       configMap,
	}

	resultCh := make(chan PluginCallResult, 1)
	pending := &PendingPluginCall{
		PluginCallID: pluginCallID,
		LeafID:       leafID,
		ConnID:       conn.ID,
		ResultCh:     resultCh,
	}
	c.registry.RegisterPendingPluginCall(pending)

	apiConn := conn.apiConn
	providerClosed := apiConn.Closed()

	wdTimeout := 5 * time.Second
	maxTimeout := time.Duration(0)
	key := watchdog.Key{Type: "plugin", ID: pluginCallID}

	cb := func(k watchdog.Key, reason watchdog.ExpiryReason) {
		if _, ok := c.registry.ClaimPendingPluginCall(k.ID); !ok {
			return
		}
		var err error
		switch reason {
		case watchdog.WatchdogExceeded:
			err = fmt.Errorf("plugin %s timeout (watchdog)", name)
		case watchdog.MaxExceeded:
			err = fmt.Errorf("plugin %s timeout (max)", name)
		case watchdog.Cancelled:
			err = fmt.Errorf("plugin %s aborted", name)
		}
		select {
		case resultCh <- PluginCallResult{Err: err}:
		default:
		}
	}

	c.server.wdMgr.Register(key, wdTimeout, maxTimeout, cb)

	if err := apiConn.SendPluginCall(ctx, pluginCall); err != nil {
		c.server.wdMgr.Cancel(watchdog.Key{Type: "plugin", ID: pluginCallID})
		c.registry.UnregisterPendingPluginCall(pluginCallID)
		return nil, fmt.Errorf("send plugin_call: %w", err)
	}

	result, err := c.roundTripPlugin(ctx, resultCh, key, name, providerClosed)
	if err != nil {
		return nil, err
	}
	if result.Err != nil {
		return nil, result.Err
	}
	if result.Result.IsError {
		return nil, fmt.Errorf("plugin %s returned error", name)
	}
	return result.Result.PendingTurns, nil
}

func (c *IPCCaller) ResolvePluginInfo(ctx context.Context, plugins []string) []protocol.PluginInfo {
	infos := make([]protocol.PluginInfo, len(plugins))
	for i, name := range plugins {
		if ctx.Err() != nil {
			return nil
		}
		conn, _, pp, _, err := c.resolveConnection("plugin", name)
		if err != nil || conn == nil {
			infos[i] = protocol.PluginInfo{Name: name}
			continue
		}
		if pp != nil && pp.Info.Description != "" {
			infos[i] = pp.Info
			continue
		}
		if c.requestMetadata(ctx, conn, "plugin", []string{name}) != nil {
			return nil
		}
		pp, _, _ = c.registry.FindPlugin(name)
		var waited *protocol.PluginInfo
		if pp != nil && pp.ConnID == conn.ID {
			waited = &pp.Info
		}
		if waited != nil {
			infos[i] = *waited
		} else {
			infos[i] = protocol.PluginInfo{Name: name}
		}
	}
	return infos
}

func (c *IPCCaller) roundTrip(ctx context.Context, pending *PendingCall, key watchdog.Key, opKind, opName string, conn *Connection, providerDone <-chan struct{}) (ToolCallResult, error) {
	select {
	case result := <-pending.ResultCh:
		if ctx.Err() != nil {
			if result.OnAdmitted != nil {
				result.OnAdmitted(nil, fmt.Errorf("%s aborted: %s", opKind, opName))
			}
			c.abortToolCall(key, conn, pending, fmt.Errorf("%s aborted: %s", opKind, opName))
			return ToolCallResult{}, fmt.Errorf("%s aborted: %s", opKind, opName)
		}
		c.server.wdMgr.Cancel(key)
		return result, nil
	case <-providerDone:
		if ctx.Err() != nil {
			c.abortToolCall(key, conn, pending, fmt.Errorf("%s aborted: %s", opKind, opName))
			return ToolCallResult{}, fmt.Errorf("%s aborted: %s", opKind, opName)
		}
		if result, ok := c.claimToolConnectionClosed(key, opName); ok {
			if ctx.Err() != nil {
				c.abortToolCall(key, conn, pending, fmt.Errorf("%s aborted: %s", opKind, opName))
				return ToolCallResult{}, fmt.Errorf("%s aborted: %s", opKind, opName)
			}
			return result, nil
		}
		return c.awaitClaimedToolResult(ctx, pending, key, opKind, opName, conn)
	case <-ctx.Done():
		c.abortToolCall(key, conn, pending, fmt.Errorf("%s aborted: %s", opKind, opName))
		return ToolCallResult{}, fmt.Errorf("%s aborted: %s", opKind, opName)
	}
}

func (c *IPCCaller) roundTripPlugin(ctx context.Context, resultCh chan PluginCallResult, key watchdog.Key, pluginName string, providerClosed <-chan struct{}) (PluginCallResult, error) {
	select {
	case <-providerClosed:
		if _, ok := c.registry.ClaimPendingPluginCall(key.ID); ok {
			c.server.wdMgr.Cancel(key)
			return PluginCallResult{Err: fmt.Errorf("plugin %s aborted: connection closed", pluginName)}, nil
		}
		// A result or timeout already owns delivery. Consume its terminal value.
	case result := <-resultCh:
		c.server.wdMgr.Cancel(key)
		return result, nil
	case <-ctx.Done():
		c.server.wdMgr.Cancel(key)
		c.registry.UnregisterPendingPluginCall(key.ID)
		return PluginCallResult{}, fmt.Errorf("plugin %s aborted", pluginName)
	}
	select {
	case result := <-resultCh:
		c.server.wdMgr.Cancel(key)
		return result, nil
	case <-ctx.Done():
		c.server.wdMgr.Cancel(key)
		c.registry.UnregisterPendingPluginCall(key.ID)
		return PluginCallResult{}, fmt.Errorf("plugin %s aborted", pluginName)
	}
}

func parseToolTimeouts(timeout, maxTimeout string) (watchdog time.Duration, max time.Duration) {
	watchdog = 30 * time.Second
	if timeout != "" && timeout != "-1" {
		if d, err := time.ParseDuration(timeout); err == nil {
			watchdog = d
		}
	}

	if maxTimeout != "" && maxTimeout != "-1" {
		if d, err := time.ParseDuration(maxTimeout); err == nil {
			max = d
		}
	}

	return watchdog, max
}

func macroResultError(name, message string) error {
	if message == "" {
		message = "(no message)"
	}
	return fmt.Errorf("macro %s returned error: %s", name, message)
}

func (c *IPCCaller) resolveMacroConnectionForConfig(name string, cfg *config.Config) (*Connection, *MacroProvider, error) {
	// Runtime-announced macros remain authoritative and preserve stable routing.
	if mp, _, err := c.registry.FindMacro(name); err == nil && mp != nil && mp.ConnID != "" {
		if conn := c.lookupConn(mp.ConnID); conn != nil {
			return conn, mp, nil
		}
	}
	// Config placeholders are generation-specific. Resolve a direct macro from
	// the request's effective snapshot rather than the registry's global layer.
	if cfg != nil {
		for directName, direct := range cfg.Services {
			for _, macroName := range direct.Macros {
				if macroName == name {
					dc := direct
					if _, err := c.ensureDirectConn(directName, &dc); err != nil {
						return nil, nil, fmt.Errorf("ensure direct conn for macro %s: %w", name, err)
					}
					if owner, mp := c.liveMacroProvider(name); owner != nil {
						return owner, mp, nil
					}
					return nil, nil, fmt.Errorf("macro connection not available after service start: %s", name)
				}
			}
		}
	}
	conn, _, _, mp, err := c.resolveConnection("macro", name)
	return conn, mp, err
}

type MacroAdmission struct {
	conn   *Connection
	info   protocol.MacroInfo
	export *agent.ProviderExportRoute
}

func macroInfoForConfig(name string, cfg *config.Config) protocol.MacroInfo {
	// Existing direct capability config carries only the capability name. Its
	// config-only metadata is therefore the established placeholder watchdog;
	// richer metadata can only come from the selected runtime announcement.
	return protocol.MacroInfo{Name: name, Timeout: "5s", MaxTimeout: ""}
}

func (c *IPCCaller) AdmitMacroForConfig(name string, cfg *config.Config) (*MacroAdmission, error) {
	if config.IsReservedProviderExportMacro(name) {
		if c.server.providerExports == nil {
			return nil, agent.ErrProviderExportUnavailable
		}
		route, err := c.server.providerExports.Route(name)
		if err != nil {
			return nil, err
		}
		return &MacroAdmission{export: route, info: protocol.MacroInfo{Name: name, Internal: true}}, nil
	}
	conn, _, err := c.resolveMacroConnectionForConfig(name, cfg)
	if err != nil {
		return nil, err
	}
	info := macroInfoForConfig(name, cfg)
	// Metadata explicitly announced by the selected live runtime wins over
	// config metadata. Other registry/config generations are never consulted.
	if runtime := c.registry.RuntimeMacroInfo(name, conn.ID); runtime != nil {
		info = *runtime
	}
	return &MacroAdmission{conn: conn, info: info}, nil
}
func (c *IPCCaller) CallMacroForConfig(ctx context.Context, name, paramString, leafID, originConnID string, cfg *config.Config) (macroCallID, result string, err error) {
	admission, err := c.AdmitMacroForConfig(name, cfg)
	if err != nil {
		return "", "", err
	}
	return c.callMacroAdmitted(ctx, admission, name, paramString, leafID, originConnID)
}

func (c *IPCCaller) CallMacroAdmitted(ctx context.Context, admission *MacroAdmission, name, paramString, leafID, originConnID string) (macroCallID, result string, err error) {
	return c.callMacroAdmitted(ctx, admission, name, paramString, leafID, originConnID)
}

func (c *IPCCaller) CallMacro(ctx context.Context, name, paramString, leafID, originConnID string) (macroCallID, result string, err error) {
	if config.IsReservedProviderExportMacro(name) {
		return c.CallMacroForConfig(ctx, name, paramString, leafID, originConnID, nil)
	}
	conn, _, _, _, err := c.resolveConnection("macro", name)
	if err != nil {
		return "", "", err
	}
	info := protocol.MacroInfo{Name: name, Timeout: "5s", MaxTimeout: ""}
	if merged := c.registry.ResolveMergedMacroInfo(name); merged != nil {
		info = *merged
	}
	if macroInfoLooksPlaceholder(info) {
		infos := c.ResolveMacroInfoContext(ctx, []string{name})
		if len(infos) > 0 && !macroInfoLooksPlaceholder(infos[0]) {
			info = infos[0]
		}
	}
	return c.callMacroAdmitted(ctx, &MacroAdmission{conn: conn, info: info}, name, paramString, leafID, originConnID)
}

func (c *IPCCaller) callMacroAdmitted(ctx context.Context, admission *MacroAdmission, name, paramString, leafID, originConnID string) (macroCallID, result string, err error) {
	if admission.export != nil {
		conn := c.lookupConn(originConnID)
		if conn == nil || conn.apiConn == nil {
			return "", "", agent.ErrProviderExportUnavailable
		}
		result, err = admission.export.Call(ctx, originConnID, conn.apiConn.Closed(), paramString)
		return session.NewIDBytes("mc_", 8), result, err
	}
	conn, info := admission.conn, admission.info
	apiConn := conn.apiConn
	providerClosed := apiConn.Closed()
	if c.beforeMacroDispatch != nil {
		c.beforeMacroDispatch()
	}

	macroCallID = session.NewIDBytes("mc_", 8)
	macroCall := protocol.MacroCallIPC{
		Type:        "macro_call_ipc",
		MacroCallID: macroCallID,
		MacroName:   name,
		ParamString: paramString,
		LeafID:      leafID,
	}

	resultCh := make(chan MacroCallResult, 1)
	pending := &PendingMacroCall{
		MacroCallID:  macroCallID,
		LeafID:       leafID,
		ConnID:       conn.ID,
		OriginConnID: originConnID,
		ResultCh:     resultCh,
	}
	c.registry.RegisterPendingMacroCall(pending)

	wdTimeout, maxTimeout := parseMacroTimeouts(info.Timeout, info.MaxTimeout)
	key := watchdog.Key{Type: "macro", ID: macroCallID}

	cb := func(k watchdog.Key, reason watchdog.ExpiryReason) {
		if _, ok := c.registry.ClaimPendingMacroCall(k.ID); !ok {
			return
		}
		var cbErr error
		switch reason {
		case watchdog.WatchdogExceeded:
			cbErr = fmt.Errorf("macro %s timeout (watchdog)", name)
		case watchdog.MaxExceeded:
			cbErr = fmt.Errorf("macro %s timeout (max)", name)
		case watchdog.Cancelled:
			cbErr = fmt.Errorf("macro %s aborted", name)
		}
		select {
		case resultCh <- MacroCallResult{Err: cbErr}:
		default:
		}
	}

	c.server.wdMgr.Register(key, wdTimeout, maxTimeout, cb)

	if err := apiConn.SendMacroCallIPC(ctx, macroCall); err != nil {
		c.server.wdMgr.Cancel(watchdog.Key{Type: "macro", ID: macroCallID})
		c.registry.UnregisterPendingMacroCall(macroCallID)
		return macroCallID, "", fmt.Errorf("send macro_call_ipc: %w", err)
	}

	rres, rerr := c.roundTripMacro(ctx, resultCh, key, name, providerClosed)
	if rerr != nil {
		return macroCallID, "", rerr
	}
	if rres.Err != nil {
		return macroCallID, "", rres.Err
	}
	if rres.Result.IsError {
		return macroCallID, "", macroResultError(name, rres.Result.Result)
	}
	return macroCallID, rres.Result.Result, nil
}

func (c *IPCCaller) roundTripMacro(ctx context.Context, resultCh chan MacroCallResult, key watchdog.Key, macroName string, providerClosed <-chan struct{}) (MacroCallResult, error) {
	for {
		select {
		case result := <-resultCh:
			c.server.wdMgr.Cancel(key)
			return result, nil
		case <-providerClosed:
			if c.beforeMacroCloseClaim != nil {
				c.beforeMacroCloseClaim()
			}
			if _, ok := c.registry.ClaimPendingMacroCall(key.ID); ok {
				c.server.wdMgr.Cancel(key)
				return MacroCallResult{Err: fmt.Errorf("macro aborted: connection closed")}, nil
			}
			select {
			case result := <-resultCh:
				c.server.wdMgr.Cancel(key)
				return result, nil
			case <-ctx.Done():
				c.server.wdMgr.Cancel(key)
				return MacroCallResult{}, fmt.Errorf("macro %s aborted", macroName)
			}
		case <-ctx.Done():
			c.server.wdMgr.Cancel(key)
			c.registry.UnregisterPendingMacroCall(key.ID)
			return MacroCallResult{}, fmt.Errorf("macro %s aborted", macroName)
		}
	}
}

func macroInfoLooksPlaceholder(info protocol.MacroInfo) bool {
	return info.Description == "" && info.Priority == 0 && info.Version == "" && len(info.Triggers) == 0 && info.Timeout == "5s" && info.MaxTimeout == ""
}
func parseMacroTimeouts(timeout, maxTimeout string) (watchdog time.Duration, max time.Duration) {
	watchdog = 5 * time.Second
	if timeout != "" && timeout != "-1" {
		if d, err := time.ParseDuration(timeout); err == nil {
			watchdog = d
		}
	}

	if maxTimeout != "" && maxTimeout != "-1" {
		if d, err := time.ParseDuration(maxTimeout); err == nil {
			max = d
		}
	}

	return watchdog, max
}

func (c *IPCCaller) ResolveMacroInfo(names []string) []protocol.MacroInfo {
	return c.ResolveMacroInfoContext(context.Background(), names)
}

func (c *IPCCaller) ResolveMacroInfoContext(ctx context.Context, names []string) []protocol.MacroInfo {
	infos := make([]protocol.MacroInfo, len(names))
	for i, name := range names {
		if ctx.Err() != nil {
			return nil
		}
		if config.IsReservedProviderExportMacro(name) {
			infos[i] = protocol.MacroInfo{Name: name}
			if c.server.providerExports != nil {
				if _, err := c.server.providerExports.Route(name); err == nil {
					infos[i] = *c.registry.ResolveMergedMacroInfo(name)
				}
			}
			continue
		}
		conn, _, _, mp, err := c.resolveConnection("macro", name)
		if err != nil || conn == nil {
			infos[i] = protocol.MacroInfo{Name: name}
			continue
		}
		if mp != nil && (mp.Info.Description != "" || len(mp.Info.Triggers) > 0) {
			infos[i] = mp.Info
			continue
		}
		if c.requestMetadata(ctx, conn, "macro", []string{name}) != nil {
			return nil
		}
		waited := c.registry.RuntimeMacroInfo(name, conn.ID)
		if waited != nil {
			infos[i] = *waited
		} else {
			infos[i] = protocol.MacroInfo{Name: name}
		}
	}
	return infos
}

func (c *IPCCaller) ResolveMergedMacroInfo(name string) *protocol.MacroInfo {
	return c.registry.ResolveMergedMacroInfo(name)
}