pkg/ezagentapi/dispatch.go

package ezagentapi

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"sync"

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

func (c *Conn) dispatchHandler(handlers Handlers) jsonlpipe.Handler {
	// The preparation lane keeps hooks off the reader. Service connections
	// admit frames in wire order; client admission remains asynchronous.
	// Correlation and built-in discovery remain independent.
	var mu sync.Mutex
	var queue []jsonlpipe.Frame
	running := false
	run := func() {
		defer c.callbacks.Done()
		for {
			mu.Lock()
			if len(queue) == 0 {
				running = false
				mu.Unlock()
				return
			}
			batch := queue
			queue = nil
			mu.Unlock()
			for _, f := range batch {
				var prepare func(context.Context) context.Context
				if handlers.PrepareInbound != nil {
					prepare = handlers.PrepareInbound(f.Type, f.Raw)
				}
				var queuedDone func()
				if handlers.OnRequestQueued != nil {
					if receipt, ok := selectedRequestReceipt(f); ok {
						queuedDone = handlers.OnRequestQueued(receipt)
					}
				}
				go c.dispatchCallbackAsync(handlers, f, queuedDone, prepare)
			}

		}
	}
	return func(f jsonlpipe.Frame) {
		if c.routeExtra(f, handlers) || c.routeHeartbeat(f, handlers) || c.routeRPCResponse(f, handlers) {
			return
		}
		c.admitOperation(f)
		f.Raw = append([]byte(nil), f.Raw...)
		c.callbacks.Add(1)
		mu.Lock()
		queue = append(queue, f)
		if !running {
			running = true
			c.callbacks.Add(1)
			go run()
		}
		mu.Unlock()
	}
}

func (c *Conn) dispatchCallbackAsync(handlers Handlers, f jsonlpipe.Frame, queuedDone func(), prepare func(context.Context) context.Context) {
	defer c.callbacks.Done()
	ctx := c.handlerCtx
	if ctx == nil {
		ctx = context.Background()
	}
	if prepare != nil {
		ctx = prepare(ctx)
		if ctx.Err() != nil {
			return
		}
	}
	if _, rpc := protocol.RPCResponse(f.Type); !handlers.ConcurrentRPCs || !rpc {
		c.handlerMu.Lock()
		defer c.handlerMu.Unlock()
	}
	if queuedDone != nil {
		queuedDone()
	}
	if err := c.dispatchCallback(ctx, handlers, f); err != nil {
		var dec DecodeError
		if errors.As(err, &dec) {
			// Give the existing parse-error responder first refusal. A terminal
			// it sends retires ownership, so the fallback cannot send a duplicate.
			callOnError(ctx, handlers, err)
			c.rejectOperation(f)
			return
		}
		c.rejectOperation(f)
		callOnError(ctx, handlers, err)
	}
}

func (c *Conn) dispatchFrame(ctx context.Context, handlers Handlers, f jsonlpipe.Frame) error {
	if c.routeRPCResponse(f, handlers) {
		return nil
	}
	return c.dispatchCallback(ctx, handlers, f)
}

// routeRPCResponse performs correlation before callback serialization. A
// response-only frame is consumed when matched. A stale response-only frame
// with a non-empty request ID is also discarded instead of becoming an event.
// Lifecycle and explicitly dual-role frames continue to callback dispatch
// after releasing any waiter.
func (c *Conn) routeRPCResponse(f jsonlpipe.Frame, handlers Handlers) bool {
	if c.rpc == nil {
		return false
	}
	if f.Type == "tool_approval_done" {
		var done protocol.ToolApprovalDone
		if json.Unmarshal(f.Raw, &done) != nil {
			// Settle a correlated waiter with an invalid decision instead of
			// leaving it waiting on a push it can never decode.
			var ids struct {
				LeafID     string `json:"leaf_id"`
				ToolCallID string `json:"tool_call_id"`
				ApprovalID string `json:"approval_id"`
			}
			if json.Unmarshal(f.Raw, &ids) != nil {
				return true
			}
			done = protocol.ToolApprovalDone{LeafID: ids.LeafID, ToolCallID: ids.ToolCallID, ApprovalID: ids.ApprovalID}
		}
		c.rpc.deliverApprovalDone(done)
		return true
	}
	if f.Type == "tool_invoke_done" {
		var done protocol.ToolInvokeDone
		if json.Unmarshal(f.Raw, &done) == nil && done.InvocationID != "" {
			matched := c.rpc.deliverInvocationDone(done)
			if matched && handlers.OnToolInvokeDone == nil {
				return true
			}
		}
	}
	responseType, matched := c.rpc.handleResponse(f.Type, f.Raw)
	if !responseType || !rpcResponseOnly(f.Type) {
		return false
	}
	if matched || f.Type == "extra_response" || f.Type == "version_result" || f.Type == "provider_usage_list_result" || f.Type == "provider_usage_result" || f.Type == "provider_usage_set_result" {
		// These extension replies have no request-role ambiguity on service
		// peers. A duplicate or retired reply is never an application event.
		return true
	}
	if !c.clientSide {
		return false
	}
	// switch_leaf historically permits an empty request_id, but its reply is
	// still only an acknowledgement. The authoritative state follows in a
	// separate leaf_updated event.
	return f.Type == "leaf_switched" || responseRequestID(f.Raw) != ""
}

func responseRequestID(raw json.RawMessage) string {
	var envelope struct {
		RequestID string `json:"request_id"`
	}
	if json.Unmarshal(raw, &envelope) != nil {
		return ""
	}
	return envelope.RequestID
}

func (c *Conn) dispatchCallback(ctx context.Context, handlers Handlers, f jsonlpipe.Frame) error {
	switch f.Type {
	case "background_task_add":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnBackgroundTaskAdd)
	case "background_task_remove":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnBackgroundTaskRemove)
	case "background_task_kill":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnBackgroundTaskKill)
	case "announce":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnAnnounce)
	case "version":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnVersion)
	case "prompt":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnPrompt)
	case "steer":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnSteer)
	case "abort":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnAbort)
	case "create_leaf":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnCreateLeaf)
	case "delete_leaf":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnDeleteLeaf)
	case "rewind_leaf":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnRewindLeaf)
	case "rename_leaf":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnRenameLeaf)
	case "update_leaf_meta":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnUpdateLeafMeta)
	case "notify_leaf":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnNotifyLeaf)
	case "switch_leaf":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnSwitchLeaf)
	case "drop_feed":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnDropFeed)
	case "list_leaves":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnListLeaves)
	case "list_roots":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnListRoots)
	case "list_cwd":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnListCwd)
	case "update_cwd":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnUpdateCwd)
	case "list_history":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnListHistory)
	case "list_turn_tree":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnListTurnTree)
	case "list_queued":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnListQueued)
	case "list_connections":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnListConnections)
	case "get_turn":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnGetTurn)
	case "get_attachment_chunk":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnGetAttachmentChunk)
	case "leaf_stats":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnLeafStats)
	case "create_virtual_root":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnCreateVirtualRoot)
	case "vacuum":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnVacuum)
	case "get_leaf_config":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnGetLeafConfig)
	case "leaf_files":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnLeafFiles)
	case "set_leaf_config":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnSetLeafConfig)
	case "list_leaf_config":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnListLeafConfig)
	case "delete_leaf_config":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnDeleteLeafConfig)
	case "effective_config":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnGetEffectiveConfig)
	case "get_supported_filetypes":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnGetSupportedFiletypes)
	case "add_tool":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnAddTool)
	case "remove_tool":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnRemoveTool)
	case "list_tools":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnListTools)
	case "get_tool_info":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnGetToolInfo)
	case "list_plugins":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnListPlugins)
	case "list_macros":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnListMacros)
	case "macro_call":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnMacroCallRequest)
	case "list_models":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnListModels)
	case "list_providers":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnListProviders)
	case "provider_usage_list":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnProviderUsageList)
	case "provider_usage":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnProviderUsage)
	case "provider_usage_set":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnProviderUsageSet)
	case "resolve_models":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnResolveModels)
	case "set_model":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnSetModel)
	case "set_thinking_level":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnSetThinkingLevel)
	case "report_progress":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnReportProgress)
	case "question_reply":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnQuestionReply)
	case "tool_invoke":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnToolInvoke)
	case "tool_approval_request":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnToolApprovalRequest)
	case "tool_call":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnToolCall)
	case "tool_abort":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnToolAbort)
	case "tool_info_request":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnToolInfoRequest)
	case "tool_result":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnToolResult)
	case "tool_invoke_done":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnToolInvokeDone)
	case "tool_ack":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnToolAck)
	case "tool_info_response":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnToolInfoResponse)
	case "heartbeat":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnHeartbeat)
	case "tool_abort_ack":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnToolAbortAck)
	case "plugin_call":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnPluginCall)
	case "plugin_info_request":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnPluginInfoRequest)
	case "plugin_result":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnPluginResult)
	case "plugin_info_response":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnPluginInfoResponse)
	case "macro_call_ipc":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnMacroCall)
	case "macro_info_request":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnMacroInfoRequest)
	case "macro_result_ipc":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnMacroResultIPC)
	case "macro_info_response":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnMacroInfoResponse)
	case "shutdown":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnShutdown)
	case "prompt_completed":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnPromptCompleted)
	case "prompt_accepted":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnPromptAccepted)
	case "steer_accepted":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnSteerAccepted)
	case "agent_start":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnAgentStart)
	case "agent_end":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnAgentEnd)
	case "turn_start":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnTurnStart)
	case "turn_end":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnTurnEnd)
	case "message_start":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnMessageStart)
	case "message_update":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnMessageUpdate)
	case "message_end":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnMessageEnd)
	case "turns_sent":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnTurnsSent)
	case "turn_content":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnTurnContent)
	case "leaf_created":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnLeafCreated)
	case "leaf_updated":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnLeafUpdated)
	case "leaf_deleted":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnLeafDeleted)
	case "leaf_rewound":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnLeafRewound)
	case "leaf_switched":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnLeafSwitched)
	case "feed_dropped":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnFeedDropped)
	case "abort_received":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnAbortReceived)
	case "informational":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnInformational)
	case "error":
		return decodeAndCallOrUnsupported(ctx, handlers, f, handlers.OnProtocolError)
	default:
		if handlers.OnUnsupportedMessage != nil {
			return handlers.OnUnsupportedMessage(ctx, UnsupportedMessage{Type: f.Type, Raw: f.Raw})
		}
	}
	return nil
}

// rpcResponseOnly reports whether a response must not also be delivered as a
// frontend event. Most frontend response types are lifecycle acknowledgements
// that intentionally reach both paths. A turn_content with request_id is the
// result of get_turn; unsolicited turn_content has no request_id and continues
// through OnTurnContent. leaf_switched is an acknowledgement, not an event.
func rpcResponseOnly(msgType string) bool {
	if msgType == "extra_response" || msgType == "version_result" {
		return true
	}
	return msgType != "tool_info_response" && msgType != "plugin_info_response" && msgType != "macro_info_response" && !hasFrontendHandler(msgType) || msgType == "error" || msgType == "turn_content"
}

var frontendEventTypes = map[string]struct{}{
	"prompt_completed": {},
	"prompt_accepted":  {},
	"steer_accepted":   {},
	"abort_received":   {},
	"agent_start":      {},
	"agent_end":        {},
	"turn_start":       {},
	"turn_end":         {},
	"message_start":    {},
	"message_update":   {},
	"message_end":      {},
	"turns_sent":       {},
	"turn_content":     {},
	"leaf_created":     {},
	"leaf_updated":     {},
	"leaf_deleted":     {},
	"informational":    {},
	"error":            {},
}

func hasFrontendHandler(msgType string) bool {
	_, ok := frontendEventTypes[msgType]
	return ok
}

type DecodeError struct {
	Type string
	Raw  json.RawMessage
	Err  error
}

func (e DecodeError) Error() string { return fmt.Sprintf("ezagentapi: decode %s: %v", e.Type, e.Err) }
func (e DecodeError) Unwrap() error { return e.Err }

func decodeAndCallOrUnsupported[T any](ctx context.Context, handlers Handlers, f jsonlpipe.Frame, handler func(context.Context, T) error) error {
	var v T
	if err := json.Unmarshal(f.Raw, &v); err != nil {
		return DecodeError{Type: f.Type, Raw: f.Raw, Err: err}
	}
	if handler != nil {
		return handler(ctx, v)
	}
	if !hasFrontendHandler(f.Type) && handlers.OnUnsupportedMessage != nil {
		if err := handlers.OnUnsupportedMessage(ctx, UnsupportedMessage{Type: f.Type, Raw: f.Raw}); err != nil {
			return err
		}
	}
	if _, _, _, ok := protocol.OperationResponse(f.Type); ok {
		// An observer returning nil does not take responsibility for a reply.
		// Only a registered typed handler may retain asynchronous ownership.
		return fmt.Errorf("unsupported request: %s", f.Type)
	}
	return nil
}

func callOnError(ctx context.Context, handlers Handlers, err error) {
	if handlers.OnError != nil {
		handlers.OnError(ctx, err)
	}
}