-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcatalog.go
More file actions
324 lines (294 loc) · 9.05 KB
/
Copy pathcatalog.go
File metadata and controls
324 lines (294 loc) · 9.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package main
import (
_ "embed"
"errors"
"fmt"
"os"
"reflect"
"strings"
)
// Model is one concrete model exposed by a provider.
type Model struct {
ID string `json:"id"`
Tag string `json:"tag"`
Short string `json:"short,omitempty"`
Source string `json:"source,omitempty"`
Latest bool `json:"latest"`
}
// Provider describes protocol endpoints, key metadata, and model aliases.
type Provider struct {
ID string `json:"id"`
Alias string `json:"alias"`
Name string `json:"name"`
Plan string `json:"plan,omitempty"`
ClaudeURL string `json:"claude_url,omitempty"`
OpenAIURL string `json:"openai_url,omitempty"`
ClaudeURLIntl string `json:"claude_url_intl,omitempty"`
OpenAIURLIntl string `json:"openai_url_intl,omitempty"`
KeyEnv string `json:"key_env"`
Key string `json:"-"` // Legacy custom.json only; never accepted in a catalog.
CLI []string `json:"cli"`
WireAPI string `json:"wire_api,omitempty"`
Models []Model `json:"models"`
}
type CatalogFile struct {
Version int `json:"version"`
Revision string `json:"revision"`
RetiredTags map[string]string `json:"retired_tags,omitempty"`
Providers []Provider `json:"providers"`
}
var errCatalogCacheStale = errors.New("catalog cache 旧于内置版本")
// catalog-v2.json is the single source for both the shipped offline seed and
// the separately hosted v2 update artifact. catalog.json remains the frozen
// v1 endpoint for released clients that reject unknown fields.
//
//go:embed catalog-v2.json
var embeddedCatalogJSON []byte
var embeddedCatalog = mustLoadEmbeddedCatalog()
// providers remains the immutable scrub/fallback set. It intentionally does
// not follow remote catalog removals, so retired provider keys stay isolated.
var providers = embeddedCatalog.Providers
func mustLoadEmbeddedCatalog() CatalogFile {
c, err := decodeCatalog(embeddedCatalogJSON)
if err != nil {
panic("embedded catalog is invalid: " + err.Error())
}
return *c
}
func (p *Provider) providerID() string {
if p.ID != "" {
return p.ID
}
return p.Alias
}
func (p *Provider) planID() string {
if p.Plan != "" {
return p.Plan
}
return "standard"
}
func (p *Provider) supports(cli string) bool {
for _, candidate := range p.CLI {
if candidate == cli {
return true
}
}
return false
}
func (p *Provider) hasIntl() bool {
return p.ClaudeURLIntl != "" || p.OpenAIURLIntl != ""
}
func (p *Provider) hasIntlFor(cli string) bool {
switch cli {
case "claude":
return p.ClaudeURLIntl != ""
case "codex":
return p.OpenAIURLIntl != ""
default: // OpenCode prefers an OpenAI-compatible route when present.
if p.OpenAIURL != "" || p.OpenAIURLIntl != "" {
return p.OpenAIURLIntl != ""
}
return p.ClaudeURLIntl != ""
}
}
func (p *Provider) claudeURL(intl bool) string {
if intl && p.ClaudeURLIntl != "" {
return p.ClaudeURLIntl
}
return p.ClaudeURL
}
func (p *Provider) openaiURL(intl bool) string {
if intl && p.OpenAIURLIntl != "" {
return p.OpenAIURLIntl
}
return p.OpenAIURL
}
func (p *Provider) wireAPI() string {
if p.WireAPI == "" {
return "chat"
}
return p.WireAPI
}
// probeTarget selects the protocol and endpoint used by the chosen CLI.
func (p *Provider) probeTarget(cli string, intl bool) (protocol, base string) {
switch cli {
case "claude":
return "anthropic", p.claudeURL(intl)
case "codex":
return "openai", p.openaiURL(intl)
default:
if endpoint := p.openaiURL(intl); endpoint != "" {
return "openai", endpoint
}
return "anthropic", p.claudeURL(intl)
}
}
func (p *Provider) keyEnv(intl bool) string {
if intl && p.hasIntl() {
return p.KeyEnv + "_INTL"
}
return p.KeyEnv
}
func (p *Provider) hostFor(cli string, intl bool) string {
_, endpoint := p.probeTarget(cli, intl)
return hostOf(endpoint)
}
func hostOf(raw string) string {
raw = strings.TrimPrefix(raw, "https://")
raw = strings.TrimPrefix(raw, "http://")
if i := strings.IndexByte(raw, '/'); i >= 0 {
return raw[:i]
}
return raw
}
func loadCachedCatalog() (*CatalogFile, error) {
data, err := readPrivateFile(catalogCacheFile())
if err != nil {
return nil, err
}
catalog, err := decodeCatalog(data)
if err != nil {
return nil, err
}
if err := validateCachedCatalog(catalog); err != nil {
return nil, err
}
return catalog, nil
}
// validateCachedCatalog is shared by runtime activation and doctor so they
// cannot disagree about rollback, revision immutability, or trust evolution.
func validateCachedCatalog(catalog *CatalogFile) error {
if compareCatalogRevision(catalog.Revision, embeddedCatalog.Revision) < 0 {
return fmt.Errorf("%w: %s < %s", errCatalogCacheStale, catalog.Revision, embeddedCatalog.Revision)
}
if catalog.Revision == embeddedCatalog.Revision && !reflect.DeepEqual(catalog, &embeddedCatalog) {
return fmt.Errorf("catalog cache 与同 revision 的内置 catalog 内容不一致")
}
if err := validateCatalogEvolution(&embeddedCatalog, catalog); err != nil {
return fmt.Errorf("catalog cache 不满足内置信任约束: %w", err)
}
return nil
}
func activeCatalogRevision() string {
if c, err := loadCachedCatalog(); err == nil {
return c.Revision
}
return embeddedCatalog.Revision
}
// catalogProviders prefers a valid, non-rollback cache and otherwise uses the
// embedded seed. A broken update never makes the CLI unusable.
func catalogProviders() []Provider {
c, err := loadCachedCatalog()
if err == nil {
return c.Providers
}
if !os.IsNotExist(err) && !errors.Is(err, errCatalogCacheStale) {
fmt.Fprintln(os.Stderr, tr("⚠ 本地 catalog 无效,已回退到内置版本", "⚠ Local catalog is invalid; using the embedded catalog"))
}
return providers
}
type Resolved struct {
Prov *Provider
Model *Model
}
// buildIndex resolves provider aliases to latest models, version tags to
// pinned models, and official model short names to their direct provider.
// Catalog entries win over colliding local custom aliases.
func buildIndex() map[string]Resolved {
idx := make(map[string]Resolved)
retiredTags := retiredCatalogTags()
add := func(ps []Provider, custom bool) {
for i := range ps {
provider := &ps[i]
if custom && retiredTags[provider.Alias] {
fmt.Fprintf(os.Stderr, tr("⚠ 自定义别名 %q 与已退役 catalog 别名冲突,已忽略自定义项\n", "⚠ Custom alias %q conflicts with a retired catalog alias and was ignored\n"), provider.Alias)
continue
}
if _, exists := idx[provider.Alias]; custom && exists {
fmt.Fprintf(os.Stderr, tr("⚠ 自定义别名 %q 与 catalog 冲突,已忽略自定义项\n", "⚠ Custom alias %q conflicts with the catalog and was ignored\n"), provider.Alias)
continue
}
var latest *Model
for j := range provider.Models {
model := &provider.Models[j]
if model.Tag != "" {
if custom && retiredTags[model.Tag] {
continue
}
if _, exists := idx[model.Tag]; !custom || !exists {
idx[model.Tag] = Resolved{provider, model}
}
}
if !custom && model.Source == "official" && model.Short != "" {
idx[model.Short] = Resolved{provider, model}
}
if model.Latest {
latest = model
}
}
if latest != nil {
idx[provider.Alias] = Resolved{provider, latest}
}
}
}
add(catalogProviders(), false)
add(loadCustomProfiles(), true)
return idx
}
// resolveProviderModel resolves a model only inside the selected provider.
// Scoped short names may be shared by many providers; immutable legacy tags and
// exact model ids are also accepted for convenience.
func resolveProviderModel(provider *Provider, selector string) (Resolved, bool) {
if provider == nil || selector == "" {
return Resolved{}, false
}
for i := range provider.Models {
model := &provider.Models[i]
if selector == model.Short || selector == model.Tag || selector == model.ID {
return Resolved{Prov: provider, Model: model}, true
}
}
return Resolved{}, false
}
// knownModelSelector reports whether a token is a published short name or
// version tag anywhere in the active catalog. It is used to distinguish
// "provider does not offer this model" from an ordinary prompt argument.
func knownModelSelector(selector string) bool {
if selector == "" {
return false
}
all := append([]Provider{}, catalogProviders()...)
all = append(all, loadCustomProfiles()...)
for i := range all {
for j := range all[i].Models {
model := &all[i].Models[j]
if selector == model.Short || selector == model.Tag {
return true
}
}
}
return false
}
func retiredCatalogTags() map[string]bool {
state := loadCatalogUpdateState()
activeCatalog := &embeddedCatalog
if cached, err := loadCachedCatalog(); err == nil {
activeCatalog = cached
}
retired := make(map[string]bool, len(state.RetiredTags)+len(activeCatalog.RetiredTags))
for tag := range activeCatalog.RetiredTags {
retired[tag] = true
}
for tag, value := range state.RetiredTags {
if value {
retired[tag] = true
}
}
active := catalogTagTrustIndex(activeCatalog)
for tag := range state.TagTargets {
if _, exists := active[tag]; !exists {
retired[tag] = true
}
}
return retired
}