pkg/ezagentapi/operations.go

package ezagentapi

import (
	"context"
	"encoding/json"

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

// UserTurn constructs a text user turn.
func UserTurn(text string) PendingTurn {
	return TextTurn("user", text)
}

// TextTurn constructs a text turn of kind.
func TextTurn(kind, text string) PendingTurn {
	return PendingTurn{Kind: kind, ContentType: "text", Content: text}
}

// AttachmentSpec constructs an attachment blob and matching metadata.
func AttachmentSpec(files ...FileElement) (*AttachmentBlobSpec, error) {
	meta := make([]FileMeta, len(files))
	for i, file := range files {
		meta[i] = FileMeta{Filename: file.Filename, MimeType: file.MimeType, Size: file.Size}
	}
	return &AttachmentBlobSpec{FileArray: files, MetaFiles: meta}, nil
}

// NewToolResult builds a canonical tool-result envelope.
func NewToolResult(toolCallID, text string, opts ToolResultOptions) (ToolResult, error) {
	metadata, err := json.Marshal(opts.Metadata)
	if err != nil {
		return ToolResult{}, err
	}
	turn := TextTurn("tool_result", text)
	turn.ToolCallID = toolCallID
	turn.ToolName = opts.ToolName
	turn.Advanced = &PendingTurnAdvanced{OtherMeta: string(metadata)}
	if len(opts.Files) > 0 {
		turn.AttachmentBlob, err = AttachmentSpec(opts.Files...)
		if err != nil {
			return ToolResult{}, err
		}
	}
	return ToolResult{Type: "tool_result", ToolCallID: toolCallID, Turn: turn}, nil
}

func (c *Conn) sendTerminalFrame(ctx context.Context, frame any) error {
	if err := c.sendFrame(ctx, frame); err != nil {
		return err
	}
	return c.pipe.Flush()
}

// SendToolResult sends one canonical structured tool result.
func (c *Conn) SendToolResult(ctx context.Context, result ToolResult) error {
	result.Type = "tool_result"
	return c.sendTerminalFrame(ctx, result)
}

// SendToolTextResult is a convenience wrapper for a text-only successful tool
// result. Use SendToolResult directly for attachments or an already-structured
// PendingTurn.
func (c *Conn) SendToolTextResult(ctx context.Context, toolCallID, text, friendlyCall string) error {
	result, err := NewToolResult(toolCallID, text, ToolResultOptions{Metadata: ToolResultMetadata{FriendlyCall: friendlyCall}})
	if err != nil {
		return err
	}
	return c.SendToolResult(ctx, result)
}

// SendToolTextError is a convenience wrapper for a text-only failed tool
// result. Use SendToolResult directly for attachments or an already-structured
// PendingTurn.
func (c *Conn) SendToolTextError(ctx context.Context, toolCallID, text, friendlyCall string) error {
	result, err := NewToolResult(toolCallID, text, ToolResultOptions{Metadata: ToolResultMetadata{IsError: true, FriendlyCall: friendlyCall}})
	if err != nil {
		return err
	}
	return c.SendToolResult(ctx, result)
}

// Announce sends this peer's provided tools, plugins, and macros.
func (c *Conn) Announce(ctx context.Context, caps Capabilities) error {
	return c.sendFrame(ctx, protocol.Announce{
		Type:    "announce",
		Tools:   caps.Tools,
		Plugins: caps.Plugins,
		Macros:  caps.Macros,
	})
}

// SendToolAck sends an early acknowledgement for one tool invocation.
func (c *Conn) SendToolAck(ctx context.Context, toolCallID string, parallel bool) error {
	return c.sendFrame(ctx, protocol.ToolAck{
		Type:       "tool_ack",
		ToolCallID: toolCallID,
		Parallel:   parallel,
	})
}

// SendToolHeartbeat reports that a tool invocation is still active.
func (c *Conn) SendToolHeartbeat(ctx context.Context, toolCallID string) error {
	return c.sendFrame(ctx, protocol.OpHeartbeat{
		Type:   "heartbeat",
		Kind:   "tool",
		CallID: toolCallID,
	})
}

// UpdateProgress creates or replaces one transient, user-facing progress item.
// Success confirms only local transport; daemon validation is asynchronous.
func (c *Conn) UpdateProgress(ctx context.Context, update ProgressUpdate) error {
	report := protocol.ReportProgress{
		Type: "report_progress", LeafID: update.LeafID, TurnID: update.TurnID,
		UpdateID: update.UpdateID, Enabled: true, Title: update.Title, Lines: update.Lines,
		VisualizerMacro: update.VisualizerMacro, VisualizerType: update.VisualizerType,
	}
	if err := protocol.ValidateReportProgress(report); err != nil {
		return err
	}
	return c.sendFrame(ctx, report)
}

// ClearProgress explicitly removes one producer-owned status item when its
// work ends. Items are generic, not inferred tool invocations. Disconnect and
// authoritative sent-turn changes also invalidate retained progress.
func (c *Conn) ClearProgress(ctx context.Context, leafID, turnID, updateID string) error {
	report := protocol.ReportProgress{
		Type: "report_progress", LeafID: leafID, TurnID: turnID,
		UpdateID: updateID, Enabled: false,
	}
	if err := protocol.ValidateReportProgress(report); err != nil {
		return err
	}
	return c.sendFrame(ctx, report)
}

// AckToolAbort acknowledges a service-requested tool abort.
func (c *Conn) AckToolAbort(ctx context.Context, toolCallID string) error {
	return c.sendFrame(ctx, protocol.ToolAbortAck{
		Type:       "tool_abort_ack",
		ToolCallID: toolCallID,
	})
}

// SendPluginResult sends the final result for one plugin invocation.
func (c *Conn) SendPluginResult(ctx context.Context, result PluginResult) error {
	return c.sendTerminalFrame(ctx, protocol.PluginResultIPC{
		Type:         "plugin_result",
		PluginCallID: result.PluginCallID,
		PendingTurns: result.PendingTurns,
		IsError:      result.IsError,
	})
}

// SendPluginError sends an error result for one plugin invocation.
func (c *Conn) SendPluginError(ctx context.Context, pluginCallID string, pendingTurns []PendingTurn) error {
	return c.SendPluginResult(ctx, PluginResult{
		PluginCallID: pluginCallID,
		PendingTurns: pendingTurns,
		IsError:      true,
	})
}

// SendMacroResult sends the final result for one macro invocation.
func (c *Conn) SendMacroResult(ctx context.Context, result MacroResult) error {
	return c.sendTerminalFrame(ctx, protocol.MacroResultIPC{
		Type:        "macro_result_ipc",
		MacroCallID: result.MacroCallID,
		Result:      result.Result,
		IsError:     result.IsError,
	})
}

// SendMacroError sends an error result for one macro invocation.
func (c *Conn) SendMacroError(ctx context.Context, macroCallID string, result string) error {
	return c.SendMacroResult(ctx, MacroResult{
		MacroCallID: macroCallID,
		Result:      result,
		IsError:     true,
	})
}

// SendToolInfoResponse responds to a tool_info_request.
func (c *Conn) SendToolInfoResponse(ctx context.Context, requestID string, tools []protocol.ToolInfo) error {
	return c.sendFrame(ctx, protocol.ToolInfoResponse{
		Type:      "tool_info_response",
		Tools:     tools,
		RequestID: requestID,
	})
}

// SendPluginInfoResponse responds to a plugin_info_request.
func (c *Conn) SendPluginInfoResponse(ctx context.Context, requestID string, plugins []protocol.PluginInfo) error {
	return c.sendFrame(ctx, protocol.PluginInfoResponse{
		Type:      "plugin_info_response",
		Plugins:   plugins,
		RequestID: requestID,
	})
}

// SendMacroInfoResponse responds to a macro_info_request.
func (c *Conn) SendMacroInfoResponse(ctx context.Context, requestID string, macros []protocol.MacroInfo) error {
	return c.sendFrame(ctx, protocol.MacroInfoResponse{
		Type:      "macro_info_response",
		Macros:    macros,
		RequestID: requestID,
	})
}