pkg/ezagentapi/rpc.go

package ezagentapi

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"sync"
	"time"

	"git.cafe/ezterry/ez-agent/pkg/jsonlpipe"
	"git.cafe/ezterry/ez-agent/pkg/protocol"
	"git.cafe/ezterry/ez-agent/pkg/watchdog"
)

const (
	// RPC inactivity thresholds. Matching heartbeats renew these waits;
	// absolute limits belong to the caller's context.
	ServiceRPCTimeout     = 5 * time.Second
	ServiceRPCLongTimeout = 10 * time.Second
)

var (
	// ErrServiceRPCSend indicates that a service RPC request could not be sent.
	ErrServiceRPCSend = errors.New("ezagentapi service rpc: send failed")
	// ErrServiceRPCTimeout indicates no reply or matching heartbeat within the
	// RPC inactivity threshold.
	ErrServiceRPCTimeout = errors.New("ezagentapi service rpc: timeout")
	// ErrServiceRPCRequestCanceled indicates that the pending request was cancelled.
	ErrServiceRPCRequestCanceled = errors.New("ezagentapi service rpc: request cancelled")
	// ErrServiceRPCConnectionClosed indicates that the connection became terminal
	// before a pending request received a correlated response.
	ErrServiceRPCConnectionClosed = errors.New("ezagentapi service rpc: connection closed")
)

// ServiceError is an error response returned by the service for a correlated RPC.
type ServiceError struct {
	Code      string
	Message   string
	RequestID string
}

func (e *ServiceError) Error() string { return fmt.Sprintf("%s: %s", e.Code, e.Message) }

// RPC provides typed request/response operations from a capability
// process back to the ez-agent service. It owns request IDs, pending waiters,
// response dispatch, and protocol error mapping for these RPCs.
type RPC struct {
	toolInvokePending       *PendingMap[protocol.ToolInvokeResult]
	invocationMu            sync.Mutex
	invocationStarts        int
	invocations             map[string]*ToolInvocation
	invocationEarly         map[string]protocol.ToolInvokeDone
	invocationClosed        bool
	toolMetadataPending     *PendingMap[protocol.ToolInfoResponse]
	pluginMetadataPending   *PendingMap[protocol.PluginInfoResponse]
	macroMetadataPending    *PendingMap[protocol.MacroInfoResponse]
	conn                    *Conn
	watchdogs               *watchdog.Manager
	backgroundAddPending    *PendingMap[protocol.BackgroundTaskAddAck]
	backgroundRemovePending *PendingMap[protocol.BackgroundTaskRemoveAck]

	historyPending            *PendingMap[protocol.HistoryList]
	turnTreePending           *PendingMap[protocol.TurnTreeList]
	statsPending              *PendingMap[protocol.LeafStatsResponse]
	configGetPending          *PendingMap[protocol.LeafConfigValue]
	leafFilesPending          *PendingMap[protocol.LeafFilesResult]
	configListPending         *PendingMap[protocol.LeafConfigList]
	leafCreatedPending        *PendingMap[protocol.LeafCreated]
	promptAcceptedPending     *PendingMap[protocol.PromptAccepted]
	steerAcceptedPending      *PendingMap[protocol.SteerAccepted]
	abortReceivedPending      *PendingMap[protocol.AbortReceived]
	leafRenamedPending        *PendingMap[protocol.LeafRenamed]
	leafMetaUpdatedPending    *PendingMap[protocol.LeafMetaUpdated]
	leafDeletedPending        *PendingMap[protocol.LeafDeleted]
	leafRewoundPending        *PendingMap[protocol.LeafRewound]
	turnContentPending        *PendingMap[protocol.TurnContent]
	attachmentChunkPending    *PendingMap[protocol.AttachmentChunk]
	configSetPending          *PendingMap[protocol.LeafConfigSet]
	configDeletePending       *PendingMap[protocol.LeafConfigDeleted]
	modelListPending          *PendingMap[protocol.ModelList]
	resolvedModelsPending     *PendingMap[protocol.ResolvedModels]
	virtualRootCreatedPending *PendingMap[protocol.VirtualRootCreated]
	modelSetPending           *PendingMap[protocol.ModelSet]
	errorPending              *PendingMap[protocol.Error]
	toolInfoPending           *PendingMap[protocol.ToolInfoValue]
	leafListPending           *PendingMap[protocol.LeafList]
	rootListPending           *PendingMap[protocol.RootList]
	cwdListPending            *PendingMap[protocol.CwdList]
	cwdUpdatedPending         *PendingMap[protocol.CwdUpdated]
	vacuumPending             *PendingMap[protocol.VacuumResult]
	leafSwitchedPending       *PendingMap[protocol.LeafSwitched]
	macroListPending          *PendingMap[protocol.MacroList]
	macroResultPending        *PendingMap[protocol.MacroResult]
	effectiveConfigPending    *PendingMap[protocol.EffectiveConfig]
	toolListPending           *PendingMap[protocol.ToolList]
	pluginListPending         *PendingMap[protocol.PluginList]
	providerListPending       *PendingMap[protocol.ProviderList]
	toolAddedPending          *PendingMap[protocol.ToolAdded]
	toolRemovedPending        *PendingMap[protocol.ToolRemoved]
	thinkingLevelSetPending   *PendingMap[protocol.ThinkingLevelSet]
	supportedFiletypesPending *PendingMap[protocol.SupportedFiletypesResponse]
	connectionListPending     *PendingMap[protocol.ConnectionList]
	queuedListPending         *PendingMap[protocol.QueuedList]
	questionReplyPending      *PendingMap[protocol.QuestionReplyAck]
}

func newRPC(conn *Conn) *RPC {
	return &RPC{
		toolInvokePending:         NewPendingMap[protocol.ToolInvokeResult](),
		invocations:               make(map[string]*ToolInvocation),
		invocationEarly:           make(map[string]protocol.ToolInvokeDone),
		macroMetadataPending:      NewPendingMap[protocol.MacroInfoResponse](),
		pluginMetadataPending:     NewPendingMap[protocol.PluginInfoResponse](),
		toolMetadataPending:       NewPendingMap[protocol.ToolInfoResponse](),
		watchdogs:                 watchdog.NewManager(),
		backgroundAddPending:      NewPendingMap[protocol.BackgroundTaskAddAck](),
		backgroundRemovePending:   NewPendingMap[protocol.BackgroundTaskRemoveAck](),
		conn:                      conn,
		historyPending:            NewPendingMap[protocol.HistoryList](),
		turnTreePending:           NewPendingMap[protocol.TurnTreeList](),
		statsPending:              NewPendingMap[protocol.LeafStatsResponse](),
		configGetPending:          NewPendingMap[protocol.LeafConfigValue](),
		leafFilesPending:          NewPendingMap[protocol.LeafFilesResult](),
		configListPending:         NewPendingMap[protocol.LeafConfigList](),
		leafCreatedPending:        NewPendingMap[protocol.LeafCreated](),
		promptAcceptedPending:     NewPendingMap[protocol.PromptAccepted](),
		steerAcceptedPending:      NewPendingMap[protocol.SteerAccepted](),
		abortReceivedPending:      NewPendingMap[protocol.AbortReceived](),
		leafRenamedPending:        NewPendingMap[protocol.LeafRenamed](),
		leafMetaUpdatedPending:    NewPendingMap[protocol.LeafMetaUpdated](),
		leafDeletedPending:        NewPendingMap[protocol.LeafDeleted](),
		leafRewoundPending:        NewPendingMap[protocol.LeafRewound](),
		turnContentPending:        NewPendingMap[protocol.TurnContent](),
		attachmentChunkPending:    NewPendingMap[protocol.AttachmentChunk](),
		configSetPending:          NewPendingMap[protocol.LeafConfigSet](),
		configDeletePending:       NewPendingMap[protocol.LeafConfigDeleted](),
		modelListPending:          NewPendingMap[protocol.ModelList](),
		resolvedModelsPending:     NewPendingMap[protocol.ResolvedModels](),
		virtualRootCreatedPending: NewPendingMap[protocol.VirtualRootCreated](),
		modelSetPending:           NewPendingMap[protocol.ModelSet](),
		errorPending:              NewPendingMap[protocol.Error](),
		toolInfoPending:           NewPendingMap[protocol.ToolInfoValue](),
		leafListPending:           NewPendingMap[protocol.LeafList](),
		rootListPending:           NewPendingMap[protocol.RootList](),
		cwdListPending:            NewPendingMap[protocol.CwdList](),
		cwdUpdatedPending:         NewPendingMap[protocol.CwdUpdated](),
		vacuumPending:             NewPendingMap[protocol.VacuumResult](),
		leafSwitchedPending:       NewPendingMap[protocol.LeafSwitched](),
		macroListPending:          NewPendingMap[protocol.MacroList](),
		macroResultPending:        NewPendingMap[protocol.MacroResult](),
		effectiveConfigPending:    NewPendingMap[protocol.EffectiveConfig](),
		toolListPending:           NewPendingMap[protocol.ToolList](),
		pluginListPending:         NewPendingMap[protocol.PluginList](),
		providerListPending:       NewPendingMap[protocol.ProviderList](),
		toolAddedPending:          NewPendingMap[protocol.ToolAdded](),
		toolRemovedPending:        NewPendingMap[protocol.ToolRemoved](),
		thinkingLevelSetPending:   NewPendingMap[protocol.ThinkingLevelSet](),
		supportedFiletypesPending: NewPendingMap[protocol.SupportedFiletypesResponse](),
		connectionListPending:     NewPendingMap[protocol.ConnectionList](),
		queuedListPending:         NewPendingMap[protocol.QueuedList](),
		questionReplyPending:      NewPendingMap[protocol.QuestionReplyAck](),
	}
}

// RPC returns the typed request/response helper for this connection.
func (c *Conn) RPC() *RPC { return c.rpc }

func newRequestID(prefix string) string {
	b := make([]byte, 8)
	_, _ = rand.Read(b)
	return prefix + hex.EncodeToString(b)
}

func serviceCall[T any](ctx context.Context, conn *Conn, pm *PendingMap[T], errorPending *PendingMap[protocol.Error], timeout time.Duration, send func(reqID string) error) (T, error) {
	return serviceCallWithPrefix(ctx, conn, pm, errorPending, timeout, "rpc_", send)
}

func serviceCallWithPrefix[T any](ctx context.Context, conn *Conn, pm *PendingMap[T], errorPending *PendingMap[protocol.Error], timeout time.Duration, prefix string, send func(reqID string) error) (T, error) {
	var zero T
	if ctx == nil {
		ctx = context.Background()
	}
	if err := ctx.Err(); err != nil {
		return zero, err
	}

	var closed <-chan struct{}
	if conn != nil && conn.pipe != nil {
		closed = conn.Closed()
		if conn.Err() != nil {
			return zero, serviceRPCConnectionError(conn)
		}
		select {
		case <-closed:
			return zero, serviceRPCConnectionError(conn)
		default:
		}
	}

	reqID := newRequestID(prefix)
	type result struct {
		v  T
		ok bool
	}
	ch := make(chan result, 1)
	errCh := make(chan protocol.Error, 1)
	pm.Register(reqID, func(v T) { ch <- result{v: v, ok: true} }, func() { ch <- result{} })
	errorPending.Register(reqID, func(e protocol.Error) { errCh <- e }, func() {})
	defer pm.Cancel(reqID)
	defer errorPending.Cancel(reqID)

	manager := watchdog.NewManager()
	if conn != nil && conn.rpc != nil {
		manager = conn.rpc.watchdogs
	}
	key := watchdog.Key{Type: "rpc", ID: reqID}
	expired := make(chan struct{}, 1)
	manager.Register(key, timeout, 0, func(watchdog.Key, watchdog.ExpiryReason) { expired <- struct{}{} })
	defer manager.Cancel(key)
	if err := send(reqID); err != nil {
		if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
			return zero, err
		}
		if conn != nil && conn.Err() != nil {
			return zero, serviceRPCConnectionError(conn)
		}
		if closed != nil {
			select {
			case <-closed:
				return zero, serviceRPCConnectionError(conn)
			default:
			}
		}
		return zero, fmt.Errorf("%w: %w", ErrServiceRPCSend, err)
	}

	select {
	case r := <-ch:
		if !r.ok {
			return zero, ErrServiceRPCRequestCanceled
		}
		return r.v, nil
	case e := <-errCh:
		return zero, &ServiceError{Code: e.Code, Message: e.Message, RequestID: e.RequestID}
	case <-closed:
		// Prefer a response that was already correlated before the terminal
		// signal. This avoids turning an acknowledged operation into an
		// ambiguous connection failure merely because both became ready.
		select {
		case r := <-ch:
			if !r.ok {
				return zero, ErrServiceRPCRequestCanceled
			}
			return r.v, nil
		case e := <-errCh:
			return zero, &ServiceError{Code: e.Code, Message: e.Message, RequestID: e.RequestID}
		default:
			return zero, serviceRPCConnectionError(conn)
		}
	case <-expired:
		return zero, ErrServiceRPCTimeout
	case <-ctx.Done():
		if conn != nil && conn.pipe != nil {
			select {
			case <-conn.pipe.Closed():
				// Connection-owned handler cancellation can precede correlation
				// drain. Preserve replies decoded before terminal EOF here too.
				<-closed
				select {
				case r := <-ch:
					if !r.ok {
						return zero, ErrServiceRPCRequestCanceled
					}
					return r.v, nil
				case e := <-errCh:
					return zero, &ServiceError{Code: e.Code, Message: e.Message, RequestID: e.RequestID}
				default:
				}
				return zero, serviceRPCConnectionError(conn)
			default:
			}
		}
		return zero, ctx.Err()
	}
}

func serviceRPCConnectionError(conn *Conn) error {
	cause := error(jsonlpipe.ErrClosed)
	if conn != nil {
		if err := conn.Err(); err != nil {
			cause = err
		}
	}
	return fmt.Errorf("%w: %w", ErrServiceRPCConnectionClosed, cause)
}

// handleResponse reports whether msgType is an RPC response type and whether
// this frame matched a pending request. Keeping those results separate lets
// routing reject stale correlated responses without mistaking them for events.
func (s *RPC) handleResponse(msgType string, raw json.RawMessage) (responseType, matched bool) {
	switch msgType {
	case "tool_invoke_result":
		return true, deliver(raw, s.toolInvokePending)
	case "macro_info_response":
		return true, deliver(raw, s.macroMetadataPending)
	case "plugin_info_response":
		return true, deliver(raw, s.pluginMetadataPending)
	case "tool_info_response":
		return true, deliver(raw, s.toolMetadataPending)
	case "background_task_add_ack":
		return true, deliver(raw, s.backgroundAddPending)
	case "background_task_remove_ack":
		return true, deliver(raw, s.backgroundRemovePending)
	case "history_list":
		return true, deliver(raw, s.historyPending)
	case "turn_tree_list":
		return true, deliver(raw, s.turnTreePending)
	case "leaf_stats_response":
		return true, deliver(raw, s.statsPending)
	case "leaf_config_value":
		return true, deliver(raw, s.configGetPending)
	case "leaf_files_result":
		return true, deliver(raw, s.leafFilesPending)
	case "leaf_config_list":
		return true, deliver(raw, s.configListPending)
	case "leaf_created":
		return true, deliver(raw, s.leafCreatedPending)
	case "prompt_accepted":
		return true, deliver(raw, s.promptAcceptedPending)
	case "steer_accepted":
		return true, deliver(raw, s.steerAcceptedPending)
	case "abort_received":
		return true, deliver(raw, s.abortReceivedPending)
	case "leaf_renamed":
		return true, deliver(raw, s.leafRenamedPending)
	case "leaf_meta_updated":
		return true, deliver(raw, s.leafMetaUpdatedPending)
	case "leaf_deleted":
		return true, deliver(raw, s.leafDeletedPending)
	case "leaf_rewound":
		return true, deliver(raw, s.leafRewoundPending)
	case "turn_content":
		return true, deliver(raw, s.turnContentPending)
	case "attachment_chunk":
		return true, deliver(raw, s.attachmentChunkPending)
	case "leaf_config_set":
		return true, deliver(raw, s.configSetPending)
	case "leaf_config_deleted":
		return true, deliver(raw, s.configDeletePending)
	case "model_list":
		return true, deliver(raw, s.modelListPending)
	case "resolved_models":
		return true, deliver(raw, s.resolvedModelsPending)
	case "virtual_root_created":
		return true, deliver(raw, s.virtualRootCreatedPending)
	case "model_set":
		return true, deliver(raw, s.modelSetPending)
	case "tool_info":
		return true, deliver(raw, s.toolInfoPending)
	case "leaf_list":
		return true, deliver(raw, s.leafListPending)
	case "root_list":
		return true, deliver(raw, s.rootListPending)
	case "cwd_list":
		return true, deliver(raw, s.cwdListPending)
	case "cwd_updated":
		return true, deliver(raw, s.cwdUpdatedPending)
	case "vacuum_result":
		return true, deliver(raw, s.vacuumPending)
	case "leaf_switched":
		return true, deliver(raw, s.leafSwitchedPending)
	case "feed_dropped":
		// The wire type is an acknowledgement even though RPC does not expose a
		// DropFeed convenience method. Do not reinterpret a late acknowledgement
		// as a frontend event.
		return true, false
	case "macro_list":
		return true, deliver(raw, s.macroListPending)
	case "macro_result":
		return true, deliver(raw, s.macroResultPending)
	case "effective_config":
		return true, deliver(raw, s.effectiveConfigPending)
	case "tool_list":
		return true, deliver(raw, s.toolListPending)
	case "plugin_list":
		return true, deliver(raw, s.pluginListPending)
	case "provider_list":
		return true, deliver(raw, s.providerListPending)
	case "tool_added":
		return true, deliver(raw, s.toolAddedPending)
	case "tool_removed":
		return true, deliver(raw, s.toolRemovedPending)
	case "thinking_level_set":
		return true, deliver(raw, s.thinkingLevelSetPending)
	case "supported_filetypes_response":
		return true, deliver(raw, s.supportedFiletypesPending)
	case "connection_list":
		return true, deliver(raw, s.connectionListPending)
	case "queued_list":
		return true, deliver(raw, s.queuedListPending)
	case "question_reply_ack":
		return true, deliver(raw, s.questionReplyPending)
	case "error":
		var e protocol.Error
		if json.Unmarshal(raw, &e) != nil || e.RequestID == "" {
			return true, false
		}
		return true, s.errorPending.Deliver(e.RequestID, e)
	default:
		return false, false
	}
}

func deliver[T any](raw json.RawMessage, pm *PendingMap[T]) bool {
	var v T
	if json.Unmarshal(raw, &v) == nil {
		if id := requestIDOf(v); id != "" {
			return pm.Deliver(id, v)
		}
	}
	return false
}

func requestIDOf(v any) string {
	switch x := v.(type) {
	case protocol.ToolInvokeResult:
		return x.RequestID
	case protocol.ToolInfoResponse:
		return x.RequestID
	case protocol.PluginInfoResponse:
		return x.RequestID
	case protocol.MacroInfoResponse:
		return x.RequestID
	case protocol.BackgroundTaskAddAck:
		return x.RequestID
	case protocol.BackgroundTaskRemoveAck:
		return x.RequestID
	case protocol.HistoryList:
		return x.RequestID
	case protocol.TurnTreeList:
		return x.RequestID
	case protocol.LeafStatsResponse:
		return x.RequestID
	case protocol.LeafConfigValue:
		return x.RequestID
	case protocol.LeafFilesResult:
		return x.RequestID
	case protocol.LeafConfigList:
		return x.RequestID
	case protocol.LeafCreated:
		return x.RequestID
	case protocol.PromptAccepted:
		return x.RequestID
	case protocol.SteerAccepted:
		return x.RequestID
	case protocol.AbortReceived:
		return x.RequestID
	case protocol.LeafRenamed:
		return x.RequestID
	case protocol.LeafMetaUpdated:
		return x.RequestID
	case protocol.LeafDeleted:
		return x.RequestID
	case protocol.LeafRewound:
		return x.RequestID
	case protocol.TurnContent:
		return x.RequestID
	case protocol.AttachmentChunk:
		return x.RequestID
	case protocol.LeafConfigSet:
		return x.RequestID
	case protocol.LeafConfigDeleted:
		return x.RequestID
	case protocol.ModelList:
		return x.RequestID
	case protocol.ResolvedModels:
		return x.RequestID
	case protocol.VirtualRootCreated:
		return x.RequestID
	case protocol.ModelSet:
		return x.RequestID
	case protocol.ToolInfoValue:
		return x.RequestID
	case protocol.LeafList:
		return x.RequestID
	case protocol.RootList:
		return x.RequestID
	case protocol.CwdList:
		return x.RequestID
	case protocol.CwdUpdated:
		return x.RequestID
	case protocol.VacuumResult:
		return x.RequestID
	case protocol.LeafSwitched:
		return x.RequestID
	case protocol.MacroList:
		return x.RequestID
	case protocol.MacroResult:
		return x.RequestID
	case protocol.EffectiveConfig:
		return x.RequestID
	case protocol.ToolList:
		return x.RequestID
	case protocol.PluginList:
		return x.RequestID
	case protocol.ProviderList:
		return x.RequestID
	case protocol.ToolAdded:
		return x.RequestID
	case protocol.ToolRemoved:
		return x.RequestID
	case protocol.ThinkingLevelSet:
		return x.RequestID
	case protocol.SupportedFiletypesResponse:
		return x.RequestID
	case protocol.ConnectionList:
		return x.RequestID
	case protocol.QueuedList:
		return x.RequestID
	case protocol.QuestionReplyAck:
		return x.RequestID
	default:
		return ""
	}
}

// QuestionReply resolves the exact revision of one daemon-owned leaf question.
func (s *RPC) QuestionReply(ctx context.Context, leafID, kind, revision, reply string) (QuestionReplyAck, error) {
	ack, err := serviceCall(ctx, s.conn, s.questionReplyPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		request := protocol.QuestionReply{
			Type: "question_reply", LeafID: leafID, Kind: kind,
			Revision: revision, Reply: reply, RequestID: reqID,
		}
		if err := request.Validate(); err != nil {
			return err
		}
		return s.conn.sendFrame(ctx, request)
	})
	if err != nil {
		return QuestionReplyAck{}, err
	}
	if err := ack.Validate(); err != nil {
		return QuestionReplyAck{}, fmt.Errorf("ezagentapi: malformed question_reply_ack: %w", err)
	}
	if ack.LeafID != leafID || ack.Kind != kind || ack.Revision != revision || ack.Reply != reply {
		return QuestionReplyAck{}, errors.New("ezagentapi: question_reply_ack does not match request")
	}
	return ack, nil
}

// ListHistorySnapshot returns the complete correlated history response. Its
// TipTurnID is the canonical history cut and may identify a draft omitted from
// Turns.
func (s *RPC) ListHistorySnapshot(ctx context.Context, leafID string) (HistorySnapshot, error) {
	return serviceCall(ctx, s.conn, s.historyPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.ListHistory{Type: "list_history", LeafID: leafID, RequestID: reqID})
	})
}

// ListHistory returns the typed summaries from one history snapshot. Use
// ListHistorySnapshot when the canonical tip or response metadata is needed.
func (s *RPC) ListHistory(ctx context.Context, leafID string) ([]TurnSummary, error) {
	hl, err := s.ListHistorySnapshot(ctx, leafID)
	if err != nil {
		return nil, err
	}
	return hl.Turns, nil
}

func (s *RPC) ListTurnTree(ctx context.Context, rootID string) ([]protocol.TurnTreeNode, error) {
	list, err := serviceCall(ctx, s.conn, s.turnTreePending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.ListTurnTree{Type: "list_turn_tree", RootID: rootID, RequestID: reqID})
	})
	if err != nil {
		return nil, err
	}
	return list.Turns, nil
}

func (s *RPC) LeafStats(ctx context.Context, leafID string) (protocol.LeafStatsResponse, error) {
	return serviceCall(ctx, s.conn, s.statsPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.LeafStats{Type: "leaf_stats", LeafID: leafID, RequestID: reqID})
	})
}

func (s *RPC) GetLeafConfig(ctx context.Context, leafID, key string) (string, bool, error) {
	v, err := serviceCall(ctx, s.conn, s.configGetPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.GetLeafConfig{Type: "get_leaf_config", LeafID: leafID, Key: key, RequestID: reqID})
	})
	if err != nil {
		return "", false, err
	}
	return v.Value, true, nil
}

func (s *RPC) ListLeafConfig(ctx context.Context, leafID string) ([]protocol.LeafConfigListEntry, error) {
	v, err := serviceCall(ctx, s.conn, s.configListPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.ListLeafConfig{Type: "list_leaf_config", LeafID: leafID, RequestID: reqID})
	})
	if err != nil {
		return nil, err
	}
	return v.Configs, nil
}

func (s *RPC) GetToolInfo(ctx context.Context, leafID string, names []string) ([]protocol.ToolInfo, error) {
	v, err := serviceCall(ctx, s.conn, s.toolInfoPending, s.errorPending, ServiceRPCLongTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.GetToolInfo{Type: "get_tool_info", LeafID: leafID, Names: names, RequestID: reqID})
	})
	if err != nil {
		return nil, err
	}
	return v.Tools, nil
}

func (s *RPC) SetLeafConfig(ctx context.Context, leafID, key, value string) error {
	_, err := serviceCall(ctx, s.conn, s.configSetPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.SetLeafConfig{Type: "set_leaf_config", LeafID: leafID, Key: key, Value: value, RequestID: reqID})
	})
	return err
}

func (s *RPC) DeleteLeafConfig(ctx context.Context, leafID, key string) error {
	_, err := serviceCall(ctx, s.conn, s.configDeletePending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.DeleteLeafConfig{Type: "delete_leaf_config", LeafID: leafID, Key: key, RequestID: reqID})
	})
	return err
}

func (s *RPC) CreateLeaf(ctx context.Context, cmd protocol.CreateLeaf) (protocol.LeafCreated, error) {
	return serviceCall(ctx, s.conn, s.leafCreatedPending, s.errorPending, ServiceRPCLongTimeout, func(reqID string) error {
		cmd.Type = "create_leaf"
		cmd.RequestID = reqID
		return s.conn.sendFrame(ctx, cmd)
	})
}

func (s *RPC) PromptTurn(ctx context.Context, leafID string, parentTurnID *string, turn PendingTurn) (protocol.PromptAccepted, error) {
	return serviceCall(ctx, s.conn, s.promptAcceptedPending, s.errorPending, ServiceRPCLongTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.Prompt{Type: "prompt", LeafID: leafID, ParentTurnID: parentTurnID, Turn: turn, RequestID: reqID})
	})
}

// RewindLeaf atomically moves a leaf to a retained proper ancestor. Pass an
// empty newTipTurnID to select the root boundary before the first turn. When
// replay is true, the acknowledgement means generation was admitted; terminal
// success or failure arrives through the normal lifecycle events.
func (s *RPC) RewindLeaf(ctx context.Context, leafID, currentTipTurnID, newTipTurnID string, replay bool) (protocol.LeafRewound, error) {
	return serviceCall(ctx, s.conn, s.leafRewoundPending, s.errorPending, ServiceRPCLongTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.RewindLeaf{
			Type: "rewind_leaf", LeafID: leafID, CurrentTipTurnID: currentTipTurnID,
			NewTipTurnID: newTipTurnID, Replay: replay, RequestID: reqID,
		})
	})
}

// PromptText is a convenience wrapper for simple text-only user prompts.
// It constructs a user PendingTurn and delegates to PromptTurn. Callers that
// already have structured content, attachments, or other turn fields should
// use PromptTurn directly.
func (s *RPC) PromptText(ctx context.Context, leafID, text string, parentTurnID *string) (protocol.PromptAccepted, error) {
	return s.PromptTurn(ctx, leafID, parentTurnID, UserTurn(text))
}

func (s *RPC) RenameLeaf(ctx context.Context, leafID, name string) (protocol.LeafRenamed, error) {
	return serviceCall(ctx, s.conn, s.leafRenamedPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.RenameLeaf{Type: "rename_leaf", LeafID: leafID, Name: name, RequestID: reqID})
	})
}

func (s *RPC) UpdateLeafMeta(ctx context.Context, leafID string, name *string, setConfig map[string]string, deleteConfig []string) (protocol.LeafMetaUpdated, error) {
	return serviceCall(ctx, s.conn, s.leafMetaUpdatedPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.UpdateLeafMeta{Type: "update_leaf_meta", LeafID: leafID, Name: name, SetConfig: setConfig, DeleteConfig: deleteConfig, RequestID: reqID})
	})
}

func (s *RPC) DeleteLeaf(ctx context.Context, leafID string) (protocol.LeafDeleted, error) {
	return serviceCall(ctx, s.conn, s.leafDeletedPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.DeleteLeaf{Type: "delete_leaf", LeafID: leafID, RequestID: reqID})
	})
}

func (s *RPC) GetTurn(ctx context.Context, turnID string) (protocol.TurnContent, error) {
	return serviceCall(ctx, s.conn, s.turnContentPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.GetTurn{Type: "get_turn", TurnID: turnID, RequestID: reqID})
	})
}

// GetAttachmentChunk reads at most MaxAttachmentChunkBytes decoded bytes from
// an attachment indexed by the turn's meta_files list. Clients should keep up to
// two calls in flight, replenishing the window as each response arrives. Replies
// may arrive out of order; each call owns its correlated response.
func (s *RPC) GetAttachmentChunk(ctx context.Context, turnID string, attachmentIndex int, offset, length int64) (protocol.AttachmentChunk, error) {
	return serviceCall(ctx, s.conn, s.attachmentChunkPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.GetAttachmentChunk{
			Type: "get_attachment_chunk", TurnID: turnID, RequestID: reqID,
			AttachmentIndex: &attachmentIndex, Offset: &offset, Length: &length,
		})
	})
}

func (s *RPC) NotifyLeaf(ctx context.Context, leafID, level, title, message string) error {
	if err := s.conn.sendFrame(ctx, protocol.NotifyLeaf{Type: "notify_leaf", LeafID: leafID, Level: level, Title: title, Message: message}); err != nil {
		return err
	}
	// notify_leaf is fire-and-forget at the protocol level. Give the service a
	// brief chance to fan out the informational event before callers send a
	// subsequent completion frame on the same module connection.
	t := time.NewTimer(10 * time.Millisecond)
	defer t.Stop()
	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-t.C:
		return nil
	}
}

func (s *RPC) ListModels(ctx context.Context) ([]protocol.ModelEntry, error) {
	return s.ListModelsForLeaf(ctx, "")
}

// ListModelsForLeaf returns models from the effective configuration for leafID.
// An empty leaf ID retains the connection-scoped ListModels behavior.
func (s *RPC) ListModelsForLeaf(ctx context.Context, leafID string) ([]protocol.ModelEntry, error) {
	v, err := serviceCall(ctx, s.conn, s.modelListPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.ListModels{Type: "list_models", LeafID: leafID, RequestID: reqID})
	})
	if err != nil {
		return nil, err
	}
	return v.Models, nil
}

func (s *RPC) ResolveModels(ctx context.Context, leafID string) (protocol.ResolvedModels, error) {
	return serviceCall(ctx, s.conn, s.resolvedModelsPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.ResolveModels{Type: "resolve_models", LeafID: leafID, RequestID: reqID})
	})
}

func (s *RPC) CreateVirtualRoot(ctx context.Context, leafID, reason string, turns []protocol.PendingTurn, metadata map[string]any) (protocol.VirtualRootCreated, error) {
	return serviceCall(ctx, s.conn, s.virtualRootCreatedPending, s.errorPending, ServiceRPCLongTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.CreateVirtualRoot{Type: "create_virtual_root", LeafID: leafID, Reason: reason, PendingTurns: turns, Metadata: metadata, RequestID: reqID})
	})
}

func (s *RPC) SetModel(ctx context.Context, leafID, model string) (protocol.ModelSet, error) {
	return serviceCall(ctx, s.conn, s.modelSetPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.SetModel{Type: "set_model", LeafID: leafID, Model: model, RequestID: reqID})
	})
}

func (s *RPC) ListLeaves(ctx context.Context, rootID, cwd string) ([]protocol.LeafInfo, error) {
	return s.ListLeavesWithMetadata(ctx, rootID, cwd, nil)
}

func (s *RPC) ListLeavesWithMetadata(ctx context.Context, rootID, cwd string, metadataKeys []string) ([]protocol.LeafInfo, error) {
	return s.ListLeavesFiltered(ctx, rootID, cwd, metadataKeys, false)
}

// ListLeavesFiltered optionally restricts results to running or aborting leaves.
func (s *RPC) ListLeavesFiltered(ctx context.Context, rootID, cwd string, metadataKeys []string, isActive bool) ([]protocol.LeafInfo, error) {
	v, err := serviceCall(ctx, s.conn, s.leafListPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.ListLeaves{Type: "list_leaves", RootID: rootID, Cwd: cwd, MetadataKeys: metadataKeys, IsActive: isActive, RequestID: reqID})
	})
	if err != nil {
		return nil, err
	}
	return v.Leaves, nil
}
func (s *RPC) UpdateCwd(ctx context.Context, cwd, leafID string) (protocol.CwdUpdated, error) {
	return serviceCall(ctx, s.conn, s.cwdUpdatedPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.UpdateCwd{Type: "update_cwd", NewCwd: cwd, LeafID: leafID, RequestID: reqID})
	})
}

// ListCwdDetails returns the complete response, including optional cwd_infos.
func (s *RPC) ListCwdDetails(ctx context.Context) (protocol.CwdList, error) {
	return serviceCall(ctx, s.conn, s.cwdListPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.ListCwd{Type: "list_cwd", RequestID: reqID})
	})
}

func (s *RPC) ListCwd(ctx context.Context) ([]string, error) {
	v, err := s.ListCwdDetails(ctx)
	if err != nil {
		return nil, err
	}
	return v.Cwds, nil
}

func (s *RPC) ListRoots(ctx context.Context) ([]protocol.RootInfo, error) {
	v, err := serviceCall(ctx, s.conn, s.rootListPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.ListRoots{Type: "list_roots", RequestID: reqID})
	})
	if err != nil {
		return nil, err
	}
	return v.Roots, nil
}

// VacuumOptions controls a vacuum request. Deep is reserved for deep branch
// pruning; false preserves the existing orphan-root-only behavior.
type VacuumOptions struct {
	OlderThan int64
	DryRun    bool
	Deep      bool
}

// Vacuum sends a backward-compatible shallow vacuum request.
func (s *RPC) Vacuum(ctx context.Context, olderThan int64, dryRun bool) (protocol.VacuumResult, error) {
	return s.VacuumWithOptions(ctx, VacuumOptions{OlderThan: olderThan, DryRun: dryRun})
}

// VacuumWithOptions sends a vacuum request with explicit options.
func (s *RPC) VacuumWithOptions(ctx context.Context, opts VacuumOptions) (protocol.VacuumResult, error) {
	return serviceCall(ctx, s.conn, s.vacuumPending, s.errorPending, ServiceRPCLongTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.Vacuum{Type: "vacuum", OlderThan: opts.OlderThan, DryRun: opts.DryRun, Deep: opts.Deep, RequestID: reqID})
	})
}
func (s *RPC) SwitchLeaf(ctx context.Context, leafID string) (protocol.LeafSwitched, error) {
	return serviceCall(ctx, s.conn, s.leafSwitchedPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.SwitchLeaf{Type: "switch_leaf", LeafID: leafID, RequestID: reqID})
	})
}
func (s *RPC) ListMacros(ctx context.Context, leafID, filter string) ([]protocol.MacroInfo, error) {
	v, err := serviceCall(ctx, s.conn, s.macroListPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.ListMacros{Type: "list_macros", LeafID: leafID, Filter: filter, RequestID: reqID})
	})
	if err != nil {
		return nil, err
	}
	return v.Macros, nil
}
func (s *RPC) MacroCall(ctx context.Context, leafID, macroName, paramString string) (protocol.MacroResult, error) {
	return serviceCall(ctx, s.conn, s.macroResultPending, s.errorPending, ServiceRPCLongTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.MacroCall{Type: "macro_call", LeafID: leafID, MacroName: macroName, ParamString: paramString, RequestID: reqID})
	})
}
func (s *RPC) GetEffectiveConfig(ctx context.Context, leafID string) (protocol.EffectiveConfig, error) {
	return serviceCall(ctx, s.conn, s.effectiveConfigPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.GetEffectiveConfig{Type: "effective_config", LeafID: leafID, RequestID: reqID})
	})
}
func (s *RPC) ListTools(ctx context.Context, leafID string) ([]string, error) {
	v, err := serviceCall(ctx, s.conn, s.toolListPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.ListTools{Type: "list_tools", LeafID: leafID, RequestID: reqID})
	})
	if err != nil {
		return nil, err
	}
	return v.Tools, nil
}
func (s *RPC) ListPlugins(ctx context.Context, leafID string) ([]string, error) {
	v, err := serviceCall(ctx, s.conn, s.pluginListPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.ListPlugins{Type: "list_plugins", LeafID: leafID, RequestID: reqID})
	})
	if err != nil {
		return nil, err
	}
	return v.Plugins, nil
}
func (s *RPC) ListProviders(ctx context.Context, leafID string) ([]protocol.ProviderListEntry, error) {
	v, err := serviceCall(ctx, s.conn, s.providerListPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.ListProviders{Type: "list_providers", LeafID: leafID, RequestID: reqID})
	})
	if err != nil {
		return nil, err
	}
	return v.Providers, nil
}
func (s *RPC) AddTool(ctx context.Context, leafID, toolName string) (protocol.ToolAdded, error) {
	return serviceCall(ctx, s.conn, s.toolAddedPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.AddTool{Type: "add_tool", LeafID: leafID, ToolName: toolName, RequestID: reqID})
	})
}
func (s *RPC) RemoveTool(ctx context.Context, leafID, toolName string) (protocol.ToolRemoved, error) {
	return serviceCall(ctx, s.conn, s.toolRemovedPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.RemoveTool{Type: "remove_tool", LeafID: leafID, ToolName: toolName, RequestID: reqID})
	})
}
func (s *RPC) SetThinkingLevel(ctx context.Context, leafID, level string) (protocol.ThinkingLevelSet, error) {
	return serviceCall(ctx, s.conn, s.thinkingLevelSetPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.SetThinkingLevel{Type: "set_thinking_level", LeafID: leafID, Level: level, RequestID: reqID})
	})
}
func (s *RPC) GetSupportedFiletypes(ctx context.Context) ([]string, error) {
	v, err := serviceCall(ctx, s.conn, s.supportedFiletypesPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.GetSupportedFiletypes{Type: "get_supported_filetypes", RequestID: reqID})
	})
	if err != nil {
		return nil, err
	}
	return v.Filetypes, nil
}
func (s *RPC) SteerTurn(ctx context.Context, leafID string, parentTurnID *string, turn PendingTurn) (protocol.SteerAccepted, error) {
	return serviceCall(ctx, s.conn, s.steerAcceptedPending, s.errorPending, ServiceRPCLongTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.Steer{Type: "steer", LeafID: leafID, ParentTurnID: parentTurnID, Turn: turn, RequestID: reqID})
	})
}

// SteerText is a convenience wrapper for simple text-only user steers.
// It constructs a user PendingTurn and delegates to SteerTurn. Callers that
// already have structured content, attachments, or other turn fields should
// use SteerTurn directly.
func (s *RPC) SteerText(ctx context.Context, leafID, text string, parentTurnID *string) (protocol.SteerAccepted, error) {
	return s.SteerTurn(ctx, leafID, parentTurnID, UserTurn(text))
}
func (s *RPC) Abort(ctx context.Context, leafID string) error {
	_, err := serviceCallWithPrefix(ctx, s.conn, s.abortReceivedPending, s.errorPending, ServiceRPCTimeout, "abort_", func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.Abort{Type: "abort", LeafID: leafID, RequestID: reqID})
	})
	return err
}

func (s *RPC) ListConnections(ctx context.Context, leafID string) ([]protocol.ConnectionListEntry, error) {
	v, err := serviceCall(ctx, s.conn, s.connectionListPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.ListConnections{Type: "list_connections", LeafID: leafID, RequestID: reqID})
	})
	if err != nil {
		return nil, err
	}
	return v.Connections, nil
}

func (s *RPC) ListQueued(ctx context.Context, leafID string) ([]protocol.QueuedMessage, error) {
	v, err := serviceCall(ctx, s.conn, s.queuedListPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.ListQueued{Type: "list_queued", LeafID: leafID, RequestID: reqID})
	})
	if err != nil {
		return nil, err
	}
	return v.Messages, nil
}

// AttachLeafFile registers a stable key for a leaf without creating its payload.
func (s *RPC) AttachLeafFile(ctx context.Context, leafID, key string) (protocol.LeafFileDescriptor, error) {
	v, err := serviceCall(ctx, s.conn, s.leafFilesPending, s.errorPending, ServiceRPCTimeout, func(reqID string) error {
		return s.conn.sendFrame(ctx, protocol.LeafFiles{Type: "leaf_files", Operation: "attach", LeafID: leafID, Key: key, RequestID: reqID})
	})
	if err != nil {
		return protocol.LeafFileDescriptor{}, err
	}
	if v.Operation != "attach" || v.LeafID != leafID || v.File.FileID == "" || v.File.Key != key || v.File.Path == "" {
		return protocol.LeafFileDescriptor{}, fmt.Errorf("invalid leaf_files_result")
	}
	return v.File, nil
}