pkg/externalprovider/wire.go

// Package externalprovider defines the dedicated external model provider protocol.
package externalprovider

import (
	"bytes"
	"encoding/json"
	"fmt"
	"strings"
	"time"
	"unicode/utf8"
)

const ProtocolVersion = 1
const MaxFrameBytes = 32 << 20

// Frame is a protocol envelope. Fields not used by a frame type are omitted.
type Frame struct {
	Type            string         `json:"type"`
	ID              string         `json:"id"`
	Protocol        int            `json:"protocol,omitempty"`
	SessionID       string         `json:"session_id,omitempty"`
	Options         map[string]any `json:"options,omitempty"`
	Auth            map[string]any `json:"auth,omitempty"`
	Name            string         `json:"name,omitempty"`
	Version         string         `json:"version,omitempty"`
	Model           string         `json:"model,omitempty"`
	Context         *ContextUpdate `json:"context,omitempty"`
	Tools           []Tool         `json:"tools,omitempty"`
	ThinkingLevel   string         `json:"thinking_level,omitempty"`
	MaxTokens       *int           `json:"max_tokens,omitempty"`
	ContextRevision *int64         `json:"context_revision,omitempty"`
	Event           *Event         `json:"event,omitempty"`
	Code            string         `json:"code,omitempty"`
	Message         string         `json:"message,omitempty"`
	RetryAfterMS    *int64         `json:"retry_after_ms,omitempty"`
}

// MarshalJSON keeps required empty objects and arrays on their respective frames.
func (f Frame) MarshalJSON() ([]byte, error) {
	type plain Frame
	b, err := json.Marshal(plain(f))
	if err != nil {
		return nil, err
	}
	var fields map[string]json.RawMessage
	if err := json.Unmarshal(b, &fields); err != nil {
		return nil, err
	}
	if f.Type == "complete" && f.Tools != nil {
		fields["tools"], err = json.Marshal(f.Tools)
	}
	if err != nil {
		return nil, err
	}
	if f.Type == "hello" && f.Options != nil {
		fields["options"], err = json.Marshal(f.Options)
	}
	if err != nil {
		return nil, err
	}
	return json.Marshal(fields)
}

type ContextUpdate struct {
	Mode         string    `json:"mode"`
	BaseRevision int64     `json:"base_revision"`
	Revision     int64     `json:"revision"`
	Messages     []Message `json:"messages"`
}

type Message struct {
	Role             string     `json:"role"`
	Content          any        `json:"content"`
	ReasoningContent string     `json:"reasoning_content,omitempty"`
	ToolCalls        []ToolCall `json:"tool_calls,omitempty"`
	ToolCallID       string     `json:"tool_call_id,omitempty"`
	IsError          bool       `json:"is_error,omitempty"`
}

// Tool results always carry an explicit status, including successful results.
func (m Message) MarshalJSON() ([]byte, error) {
	type plain Message
	if m.Role != "tool" {
		return json.Marshal(plain(m))
	}
	return json.Marshal(struct {
		plain
		IsError bool `json:"is_error"`
	}{plain: plain(m), IsError: m.IsError})
}

type Tool struct {
	Name        string         `json:"name"`
	Description string         `json:"description,omitempty"`
	Parameters  map[string]any `json:"parameters"`
}

type ToolCall struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
}

type Usage struct {
	Input       int64 `json:"input"`
	Output      int64 `json:"output"`
	CacheRead   int64 `json:"cacheRead"`
	CacheWrite  int64 `json:"cacheWrite"`
	TotalTokens int64 `json:"totalTokens"`
}

// AccessObservation is non-secret, point-in-time evidence about the route.
// Unknown explicitly clears previously observed evidence.
type AccessObservation struct {
	Source       string `json:"source"`
	ObservedAtMS int64  `json:"observed_at_ms"`
	ExpiresAtMS  int64  `json:"expires_at_ms"`
}

type Event struct {
	Type              string             `json:"type"`
	AccessObservation *AccessObservation `json:"access_observation,omitempty"`
	ContextTokens     *int64             `json:"context_tokens,omitempty"`
	Delta             string             `json:"delta,omitempty"`
	Reasoning         string             `json:"reasoning,omitempty"`
	Message           string             `json:"message,omitempty"`
	Usage             *Usage             `json:"usage,omitempty"`
	StopReason        string             `json:"stop_reason,omitempty"`
	ToolCalls         []ToolCall         `json:"tool_calls,omitempty"`
	Model             string             `json:"model,omitempty"`
	ResponseID        string             `json:"response_id,omitempty"`
	// Nil means unchanged; a non-nil empty slice clears the labels.
	ResponseLabels []string `json:"response_labels,omitempty"`
}

// MarshalJSON preserves empty required strings and the distinction between
// omitted and empty labels.
func (e Event) MarshalJSON() ([]byte, error) {
	type plain Event
	data, err := json.Marshal(plain(e))
	if err != nil {
		return nil, err
	}
	var fields map[string]json.RawMessage
	if err := json.Unmarshal(data, &fields); err != nil {
		return nil, err
	}
	var key, value string
	switch e.Type {
	case "content_delta":
		key, value = "delta", e.Delta
	case "reasoning_delta":
		key, value = "reasoning", e.Reasoning
	case "informational":
		key, value = "message", e.Message
	}
	if key != "" {
		fields[key], _ = json.Marshal(value)
	}
	if e.ResponseLabels != nil {
		fields["response_labels"], err = json.Marshal(e.ResponseLabels)
		if err != nil {
			return nil, err
		}
	}
	return json.Marshal(fields)
}

// validateComplete checks the host's request before it is sent.
func (f Frame) validateComplete() error {
	if f.Model == "" || f.Context == nil || f.Tools == nil {
		return fmt.Errorf("invalid complete")
	}
	if f.MaxTokens != nil && *f.MaxTokens <= 0 {
		return fmt.Errorf("max_tokens must be positive")
	}
	if err := f.Context.Validate(); err != nil {
		return err
	}
	names := map[string]bool{}
	for _, t := range f.Tools {
		if t.Name == "" || t.Parameters == nil || names[t.Name] {
			return fmt.Errorf("invalid or duplicate tool %q", t.Name)
		}
		names[t.Name] = true
	}
	return nil
}

// validateProviderFrame checks provider payloads; ownership and ordering are
// checked by the client separately.
func (f Frame) validateProviderFrame() error {
	if f.ID == "" {
		return fmt.Errorf("missing id")
	}
	switch f.Type {
	case "hello":
		if f.Protocol != ProtocolVersion {
			return fmt.Errorf("unsupported protocol %d", f.Protocol)
		}
		if f.Name == "" || f.Version == "" {
			return fmt.Errorf("invalid provider hello")
		}
	case "accepted":
		if f.ContextRevision == nil || *f.ContextRevision < 0 {
			return fmt.Errorf("invalid context_revision")
		}
	case "event":
		if f.Event == nil {
			return fmt.Errorf("missing event")
		}
		return f.Event.Validate(nil)
	case "cancelled":
	case "error":
		switch f.Code {
		case "invalid_request", "unsupported_input", "context_mismatch", "authentication", "rate_limited", "unavailable", "internal":
		default:
			return fmt.Errorf("invalid error code %q", f.Code)
		}
		if f.Message == "" || (f.RetryAfterMS != nil && *f.RetryAfterMS < 0) {
			return fmt.Errorf("invalid error payload")
		}
	default:
		return fmt.Errorf("unknown frame type %q", f.Type)
	}
	return nil
}

func (c ContextUpdate) Validate() error {
	if c.Mode != "replace" && c.Mode != "append" {
		return fmt.Errorf("invalid context mode %q", c.Mode)
	}
	if c.BaseRevision < 0 || c.Revision <= c.BaseRevision || (c.Mode == "replace" && c.BaseRevision != 0) || c.Messages == nil {
		return fmt.Errorf("invalid context revision or messages")
	}
	for _, m := range c.Messages {
		if m.Role == "" {
			return fmt.Errorf("missing message role")
		}
		switch m.Content.(type) {
		case nil, string, []any, []map[string]any:
		default:
			return fmt.Errorf("invalid message content")
		}
		if _, err := json.Marshal(m.Content); err != nil {
			return fmt.Errorf("invalid message content: %w", err)
		}
		if err := ValidateToolCalls(m.ToolCalls, nil); err != nil {
			return err
		}
	}
	return nil
}

// ValidateToolCalls validates call identity and argument JSON. If offered is
// non-nil, every name must occur in that set. Historical calls use nil.
func ValidateToolCalls(calls []ToolCall, offered map[string]bool) error {
	ids := map[string]bool{}
	for _, c := range calls {
		if c.ID == "" || c.Name == "" || ids[c.ID] || (offered != nil && !offered[c.Name]) {
			return fmt.Errorf("invalid tool call %q", c.ID)
		}
		ids[c.ID] = true
		var obj map[string]json.RawMessage
		if err := json.Unmarshal([]byte(c.Arguments), &obj); err != nil || obj == nil {
			return fmt.Errorf("invalid arguments for tool call %q", c.ID)
		}
	}
	return nil
}

// Validate validates an event and, if offered is non-nil, checks tool names.
func (e Event) Validate(offered map[string]bool) error {
	if o := e.AccessObservation; o != nil {
		switch o.Source {
		case "unknown":
			if o.ObservedAtMS != 0 || o.ExpiresAtMS != 0 {
				return fmt.Errorf("invalid unknown access observation")
			}
		case "muse_subscription":
			if o.ObservedAtMS <= 0 || o.ExpiresAtMS <= o.ObservedAtMS || o.ExpiresAtMS-o.ObservedAtMS > int64((31*24*time.Hour)/time.Millisecond) {
				return fmt.Errorf("invalid access observation")
			}
		default:
			return fmt.Errorf("invalid access observation source")
		}
	}
	if e.ContextTokens != nil && *e.ContextTokens < 0 {
		return fmt.Errorf("negative context tokens")
	}
	if e.Usage != nil && (e.Usage.Input < 0 || e.Usage.Output < 0 || e.Usage.CacheRead < 0 || e.Usage.CacheWrite < 0 || e.Usage.TotalTokens < 0) {
		return fmt.Errorf("negative usage")
	}
	switch e.Type {
	case "content_delta", "reasoning_delta", "reasoning_reset", "informational", "usage_only", "assistant_boundary":
		if len(e.ToolCalls) != 0 || e.StopReason != "" {
			return fmt.Errorf("unexpected terminal payload")
		}
		if e.Type == "usage_only" && e.Usage == nil {
			return fmt.Errorf("missing usage")
		}
	case "done":
		switch e.StopReason {
		case "stop":
			if len(e.ToolCalls) != 0 {
				return fmt.Errorf("stop with tool calls")
			}
		case "tool_calls":
			if len(e.ToolCalls) == 0 {
				return fmt.Errorf("missing tool calls")
			}
		default:
			return fmt.Errorf("invalid stop reason %q", e.StopReason)
		}
		return ValidateToolCalls(e.ToolCalls, offered)
	default:
		return fmt.Errorf("unknown event type %q", e.Type)
	}
	return nil
}

// decodeFrame validates provider-originated frames. Unknown optional fields are ignored.
func decodeFrame(data []byte) (Frame, error) {
	var f Frame
	if !utf8.Valid(data) {
		return f, fmt.Errorf("invalid UTF-8 frame")
	}
	if len(data) > MaxFrameBytes {
		return f, fmt.Errorf("frame exceeds size limit")
	}
	var raw map[string]json.RawMessage
	if err := json.Unmarshal(data, &raw); err != nil || raw == nil {
		return f, fmt.Errorf("invalid frame JSON")
	}
	required := func(m map[string]json.RawMessage, keys ...string) error {
		for _, k := range keys {
			v, ok := m[k]
			if !ok || bytes.Equal(bytes.TrimSpace(v), []byte("null")) {
				return fmt.Errorf("missing or null %s", k)
			}
		}
		return nil
	}
	if err := required(raw, "type", "id"); err != nil {
		return f, err
	}
	if err := json.Unmarshal(data, &f); err != nil {
		return f, err
	}
	switch f.Type {
	case "hello":
		if err := required(raw, "protocol", "name", "version"); err != nil {
			return f, err
		}
	case "accepted":
		if err := required(raw, "context_revision"); err != nil {
			return f, err
		}
	case "error":
		if err := required(raw, "code", "message"); err != nil {
			return f, err
		}
	case "event":
		if err := required(raw, "event"); err != nil {
			return f, err
		}
		var event map[string]json.RawMessage
		if err := json.Unmarshal(raw["event"], &event); err != nil {
			return f, err
		}
		if err := required(event, "type"); err != nil {
			return f, err
		}
		for field, v := range event {
			switch {
			case strings.EqualFold(field, "access_observation"):
				var observation map[string]json.RawMessage
				if json.Unmarshal(v, &observation) != nil || observation == nil {
					return f, fmt.Errorf("invalid access observation")
				}
				for _, key := range []string{"source", "observed_at_ms", "expires_at_ms"} {
					if value, ok := observation[key]; !ok || bytes.Equal(bytes.TrimSpace(value), []byte("null")) {
						return f, fmt.Errorf("invalid access observation")
					}
				}
			case strings.EqualFold(field, "context_tokens"):
				var n int64
				if bytes.Equal(bytes.TrimSpace(v), []byte("null")) || json.Unmarshal(v, &n) != nil || n < 0 {
					return f, fmt.Errorf("invalid context tokens")
				}
			case strings.EqualFold(field, "response_labels"):
				var labels []json.RawMessage
				if err := json.Unmarshal(v, &labels); err != nil || labels == nil {
					return f, fmt.Errorf("invalid response_labels")
				}
				for _, label := range labels {
					label = bytes.TrimSpace(label)
					if len(label) == 0 || label[0] != '"' {
						return f, fmt.Errorf("invalid response label")
					}
				}
			case strings.EqualFold(field, "usage"):
				var counters map[string]json.RawMessage
				if err := json.Unmarshal(v, &counters); err != nil || counters == nil {
					return f, fmt.Errorf("invalid usage")
				}
				for name, value := range counters {
					for _, known := range []string{"input", "output", "cacheRead", "cacheWrite", "totalTokens"} {
						if !strings.EqualFold(name, known) {
							continue
						}
						var n int64
						if bytes.Equal(bytes.TrimSpace(value), []byte("null")) || json.Unmarshal(value, &n) != nil || n < 0 {
							return f, fmt.Errorf("invalid usage counter %s", name)
						}
						break
					}
				}
			}
		}
		var key string
		switch f.Event.Type {
		case "content_delta":
			key = "delta"
		case "reasoning_delta":
			key = "reasoning"
		case "informational":
			key = "message"
		case "usage_only":
			key = "usage"
		case "done":
			key = "stop_reason"
		}
		if key != "" {
			if err := required(event, key); err != nil {
				return f, err
			}
		}
	}
	return f, f.validateProviderFrame()
}