main.go

  1// Package main implements a tool to fetch GitHub Copilot models and generate a Catwalk provider configuration.
  2package main
  3
  4import (
  5	"context"
  6	"encoding/json"
  7	"fmt"
  8	"net/http"
  9	"os"
 10	"path/filepath"
 11	"regexp"
 12	"runtime"
 13	"slices"
 14	"strings"
 15	"time"
 16
 17	"github.com/charmbracelet/catwalk/pkg/catwalk"
 18)
 19
 20type Response struct {
 21	Object string  `json:"object"`
 22	Data   []Model `json:"data"`
 23}
 24
 25type Model struct {
 26	ID                 string     `json:"id"`
 27	Name               string     `json:"name"`
 28	Version            string     `json:"version"`
 29	Vendor             string     `json:"vendor"`
 30	Preview            bool       `json:"preview"`
 31	ModelPickerEnabled bool       `json:"model_picker_enabled"`
 32	Capabilities       Capability `json:"capabilities"`
 33	Policy             *Policy    `json:"policy,omitempty"`
 34}
 35
 36type Capability struct {
 37	Family    string   `json:"family"`
 38	Type      string   `json:"type"`
 39	Tokenizer string   `json:"tokenizer"`
 40	Limits    Limits   `json:"limits"`
 41	Supports  Supports `json:"supports"`
 42}
 43
 44type Limits struct {
 45	MaxContextWindowTokens int `json:"max_context_window_tokens,omitempty"`
 46	MaxOutputTokens        int `json:"max_output_tokens,omitempty"`
 47	MaxPromptTokens        int `json:"max_prompt_tokens,omitempty"`
 48}
 49
 50type Supports struct {
 51	ToolCalls         bool `json:"tool_calls,omitempty"`
 52	ParallelToolCalls bool `json:"parallel_tool_calls,omitempty"`
 53	MaxThinkingBudget int  `json:"max_thinking_budget,omitempty"`
 54	MinThinkingBudget int  `json:"min_thinking_budget,omitempty"`
 55}
 56
 57type Policy struct {
 58	State string `json:"state"`
 59	Terms string `json:"terms"`
 60}
 61
 62var versionedModelRegexp = regexp.MustCompile(`-\d{4}-\d{2}-\d{2}$`)
 63
 64func main() {
 65	if err := run(); err != nil {
 66		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
 67		os.Exit(1)
 68	}
 69}
 70
 71func run() error {
 72	copilotModels, err := fetchCopilotModels()
 73	if err != nil {
 74		return err
 75	}
 76
 77	// NOTE(@andreynering): Exclude versioned models and keep only the main version of each.
 78	copilotModels = slices.DeleteFunc(copilotModels, func(m Model) bool {
 79		return m.ID != m.Version || versionedModelRegexp.MatchString(m.ID) || strings.Contains(m.ID, "embedding")
 80	})
 81
 82	catwalkModels := modelsToCatwalk(copilotModels)
 83	slices.SortStableFunc(catwalkModels, func(a, b catwalk.Model) int {
 84		return strings.Compare(a.ID, b.ID)
 85	})
 86
 87	provider := catwalk.Provider{
 88		ID:                  catwalk.InferenceProviderCopilot,
 89		Name:                "GitHub Copilot",
 90		Models:              catwalkModels,
 91		APIEndpoint:         "https://api.githubcopilot.com",
 92		Type:                catwalk.TypeOpenAICompat,
 93		DefaultLargeModelID: "claude-sonnet-4.5",
 94		DefaultSmallModelID: "claude-haiku-4.5",
 95	}
 96	data, err := json.MarshalIndent(provider, "", "  ")
 97	if err != nil {
 98		return fmt.Errorf("unable to marshal json: %w", err)
 99	}
100	if err := os.WriteFile("internal/providers/configs/copilot.json", data, 0o600); err != nil {
101		return fmt.Errorf("unable to write copilog.json: %w", err)
102	}
103	return nil
104}
105
106func fetchCopilotModels() ([]Model, error) {
107	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
108	defer cancel()
109
110	req, err := http.NewRequestWithContext(
111		ctx,
112		"GET",
113		"https://api.githubcopilot.com/models",
114		nil,
115	)
116	if err != nil {
117		return nil, fmt.Errorf("unable to create request: %w", err)
118	}
119	req.Header.Set("Accept", "application/json")
120	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", copilotToken()))
121
122	client := &http.Client{}
123	resp, err := client.Do(req)
124	if err != nil {
125		return nil, fmt.Errorf("unable to make http request: %w", err)
126	}
127	defer resp.Body.Close() //nolint:errcheck
128
129	if resp.StatusCode != http.StatusOK {
130		return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
131	}
132
133	var data Response
134	if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
135		return nil, fmt.Errorf("unable to unmarshal json: %w", err)
136	}
137	return data.Data, nil
138}
139
140func modelsToCatwalk(m []Model) []catwalk.Model {
141	models := make([]catwalk.Model, 0, len(m))
142	for _, model := range m {
143		models = append(models, modelToCatwalk(model))
144	}
145	return models
146}
147
148func modelToCatwalk(m Model) catwalk.Model {
149	canReason, reasoningLevels, defaultReasoning := detectReasoningCapabilities(m)
150
151	return catwalk.Model{
152		ID:                     m.ID,
153		Name:                   m.Name,
154		DefaultMaxTokens:       int64(m.Capabilities.Limits.MaxOutputTokens),
155		ContextWindow:          int64(m.Capabilities.Limits.MaxContextWindowTokens),
156		CanReason:              canReason,
157		ReasoningLevels:        reasoningLevels,
158		DefaultReasoningEffort: defaultReasoning,
159	}
160}
161
162func detectReasoningCapabilities(m Model) (canReason bool, levels []string, defaultLevel string) {
163	// Models with thinking budget (Claude, Gemini) support extended thinking without levels
164	if m.Capabilities.Supports.MaxThinkingBudget > 0 {
165		return true, nil, ""
166	}
167
168	// OpenAI o-series and GPT-5+ models support reasoning with effort levels
169	if strings.HasPrefix(m.ID, "o1") ||
170		strings.HasPrefix(m.ID, "o3") ||
171		strings.HasPrefix(m.ID, "o4") ||
172		strings.HasPrefix(m.ID, "gpt-5") {
173		return true, []string{"low", "medium", "high"}, "medium"
174	}
175
176	return false, nil, ""
177}
178
179func copilotToken() string {
180	if token := os.Getenv("COPILOT_TOKEN"); token != "" {
181		return token
182	}
183	return tokenFromDisk()
184}
185
186func tokenFromDisk() string {
187	data, err := os.ReadFile(tokenFilePath())
188	if err != nil {
189		return ""
190	}
191	var content map[string]struct {
192		User        string `json:"user"`
193		OAuthToken  string `json:"oauth_token"`
194		GitHubAppID string `json:"githubAppId"`
195	}
196	if err := json.Unmarshal(data, &content); err != nil {
197		return ""
198	}
199	if app, ok := content["github.com:Iv1.b507a08c87ecfe98"]; ok {
200		return app.OAuthToken
201	}
202	return ""
203}
204
205func tokenFilePath() string {
206	switch runtime.GOOS {
207	case "windows":
208		return filepath.Join(os.Getenv("LOCALAPPDATA"), "github-copilot/apps.json")
209	default:
210		return filepath.Join(os.Getenv("HOME"), ".config/github-copilot/apps.json")
211	}
212}