cmd/ez-agent-configurator/probe.go

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
	"time"

	"git.cafe/ezterry/ez-agent/pkg/externalprovider"
	"git.cafe/ezterry/ez-agent/pkg/oauth"
	"git.cafe/ezterry/ez-agent/pkg/service/config"
	"gopkg.in/yaml.v3"
)

type DiscoveredModel struct {
	ID             string
	DisplayName    string
	Size           int64
	MaxContext     int
	ContextLimit   *int
	MaxTokens      int
	ZDRSupported   bool
	ThinkingLevels []string
	Responses      *config.ResponsesCapabilities // typed runtime-known capability metadata
	ResponsesNode  *yaml.Node                    // full opaque map, including future catalog keys
}

var discoverExternalCatalog = externalprovider.Discover

func probeExternalModels(ctx context.Context, opts externalprovider.ProcessOptions) ([]DiscoveredModel, string, error) {
	catalog, err := discoverExternalCatalog(ctx, opts)
	if err != nil {
		return nil, "", err
	}
	models := make([]DiscoveredModel, 0, len(catalog.Models))
	for _, model := range catalog.Models {
		m := DiscoveredModel{ID: model.Name, DisplayName: model.DisplayName, ContextLimit: model.ContextLimit, ThinkingLevels: model.ThinkingLevels}
		if model.MaxContext != nil {
			m.MaxContext = *model.MaxContext
		}
		if model.MaxTokens != nil {
			m.MaxTokens = *model.MaxTokens
		}
		models = append(models, m)
	}
	return models, catalog.Source, nil
}

func cloneResponsesCapabilities(in *config.ResponsesCapabilities) *config.ResponsesCapabilities {
	if in == nil {
		return nil
	}
	out := *in
	if in.ParallelToolCalls != nil {
		value := *in.ParallelToolCalls
		out.ParallelToolCalls = &value
	}
	if in.ReasoningSummary != nil {
		value := *in.ReasoningSummary
		out.ReasoningSummary = &value
	}
	if in.PromptCacheKey != nil {
		value := *in.PromptCacheKey
		out.PromptCacheKey = &value
	}
	if in.WebSocket != nil {
		value := *in.WebSocket
		out.WebSocket = &value
	}
	if in.SendMaxOutputTokens != nil {
		value := *in.SendMaxOutputTokens
		out.SendMaxOutputTokens = &value
	}
	return &out
}

func mergeDiscoveredModels(primary, secondary []DiscoveredModel) []DiscoveredModel {
	seen := make(map[string]bool, len(primary)+len(secondary))
	out := make([]DiscoveredModel, 0, len(primary)+len(secondary))
	for _, m := range primary {
		if seen[m.ID] {
			continue
		}
		seen[m.ID] = true
		out = append(out, m)
	}
	for _, m := range secondary {
		if seen[m.ID] {
			continue
		}
		seen[m.ID] = true
		out = append(out, m)
	}
	return out
}

func ProbeOpenAI(baseURL, apiKey string) ([]DiscoveredModel, error) {
	return probeProvider(context.Background(), "openai", baseURL, apiKey)
}

func ProbeOllama(baseURL string) ([]DiscoveredModel, error) {
	return probeProvider(context.Background(), "ollama", baseURL, "")
}

func ProbeWafer(baseURL, apiKey string) ([]DiscoveredModel, error) {
	return probeProvider(context.Background(), "wafer", baseURL, apiKey)
}

var modelDiscoveryTimeout = 30 * time.Second

func probeEndpoint(ctx context.Context, url, apiKey string, parser func([]byte) ([]DiscoveredModel, error)) ([]DiscoveredModel, error) {
	ctx, cancel := context.WithTimeout(ctx, modelDiscoveryTimeout)
	defer cancel()

	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return nil, fmt.Errorf("creating request: %w", err)
	}
	if apiKey != "" {
		req.Header.Set("Authorization", "Bearer "+apiKey)
	}

	client := *http.DefaultClient
	client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
	resp, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("request failed: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(body))
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("reading response: %w", err)
	}

	return parser(body)
}

func parseOpenAIModels(data []byte) ([]DiscoveredModel, error) {
	var resp struct {
		Data []struct {
			ID string `json:"id"`
		} `json:"data"`
	}
	if err := json.Unmarshal(data, &resp); err != nil {
		return nil, fmt.Errorf("parsing response: %w", err)
	}
	models := make([]DiscoveredModel, 0, len(resp.Data))
	for _, m := range resp.Data {
		models = append(models, DiscoveredModel{ID: m.ID})
	}
	return models, nil
}

func parseOllamaModels(data []byte) ([]DiscoveredModel, error) {
	var resp struct {
		Models []struct {
			Name string `json:"name"`
			Size int64  `json:"size"`
		} `json:"models"`
	}
	if err := json.Unmarshal(data, &resp); err != nil {
		return nil, fmt.Errorf("parsing response: %w", err)
	}
	models := make([]DiscoveredModel, 0, len(resp.Models))
	for _, m := range resp.Models {
		models = append(models, DiscoveredModel{ID: m.Name, Size: m.Size})
	}
	return models, nil
}

func parseWaferModels(data []byte) ([]DiscoveredModel, error) {
	var resp struct {
		Data []struct {
			ID     string `json:"id"`
			MaxLen int    `json:"max_model_len"`
			ZDR    *bool  `json:"zdr_supported"`
			Cap    struct {
				Reasoning bool `json:"reasoning"`
			} `json:"wafer.capabilities"`
		} `json:"data"`
	}
	if err := json.Unmarshal(data, &resp); err != nil {
		return nil, fmt.Errorf("parsing response: %w", err)
	}
	models := make([]DiscoveredModel, 0, len(resp.Data))
	for _, m := range resp.Data {
		dm := DiscoveredModel{ID: m.ID, MaxContext: m.MaxLen}
		if m.ZDR != nil {
			dm.ZDRSupported = *m.ZDR
		}
		if m.Cap.Reasoning {
			dm.ThinkingLevels = []string{"on", "low", "medium", "high", "max", "off"}
		}
		models = append(models, dm)
	}
	return models, nil
}

func ProbeProvider(profileID, baseURL, apiKey string) ([]DiscoveredModel, error) {
	return probeProvider(context.Background(), profileID, baseURL, apiKey)
}

func probeProvider(ctx context.Context, profileID, baseURL, apiKey string) ([]DiscoveredModel, error) {
	url := strings.TrimRight(baseURL, "/") + "/models"
	parser := parseOpenAIModels
	switch profileID {
	case "ollama":
		url = strings.TrimSuffix(strings.TrimRight(baseURL, "/"), "/v1") + "/api/tags"
		apiKey, parser = "", parseOllamaModels
	case "wafer":
		parser = parseWaferModels
	case "openai-oauth":
		return nil, oauth.ErrReconnect
	}
	return probeEndpoint(ctx, url, apiKey, parser)
}