-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
255 lines (245 loc) · 6.8 KB
/
Copy pathmain.go
File metadata and controls
255 lines (245 loc) · 6.8 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
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"sort"
"strings"
"syscall"
"time"
)
func main() {
cfg, err := parseAppConfig(os.Args[1:], os.LookupEnv, os.Stderr)
if errors.Is(err, flag.ErrHelp) {
return
}
if err != nil {
os.Exit(2)
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
debugf := func(format string, args ...any) {
if cfg.verbose {
log.Printf(format, args...)
}
}
always := func(format string, args ...any) { log.Printf(format, args...) }
if err := run(ctx, cfg, defaultAppDeps(), os.Stdout, debugf, always); err != nil {
log.Fatal(err)
}
}
func homeDir() string {
h, err := os.UserHomeDir()
if err != nil {
return "~"
}
return h
}
func (r *modelResolver) keys() []string {
out := make([]string, 0, len(r.byKey))
for k := range r.byKey {
out = append(out, k)
}
sort.Strings(out)
return out
}
func catalogReadErrorDetail(err error) string {
var pathErr *os.PathError
if errors.As(err, &pathErr) && pathErr != nil {
return fmt.Sprintf("%s: %v", pathErr.Op, pathErr.Err)
}
return fmt.Sprintf("%T", err)
}
func catalogDecryptErrorDetail(err error) string {
if err == nil {
return "unknown"
}
if errors.Is(err, context.Canceled) {
return context.Canceled.Error()
}
if errors.Is(err, context.DeadlineExceeded) {
return context.DeadlineExceeded.Error()
}
if protocolErr := protocolErrorFrom(err); protocolErr != nil {
return fmt.Sprintf("kind=%s: %v", protocolErr.kind, protocolInternalError(err))
}
return fmt.Sprintf("%T", err)
}
// loadCatalog builds the model catalog: built-in defaults, optionally overridden
// by a plaintext catalog file or the CLI's encrypted model cache.
func loadCatalog(ctx context.Context, decryptor modelCacheDecryptor, authFile, uid, catalogPath string, logf func(string, ...any)) []*modelConfig {
catalog := builtinCatalog()
if logf == nil {
logf = func(string, ...any) {}
}
var raw []byte
if catalogPath != "" {
var err error
raw, err = os.ReadFile(catalogPath)
if err != nil {
logf("catalog read %s: %v", catalogPath, err)
}
} else {
cachePath := filepath.Clean(filepath.Join(filepath.Dir(authFile), "..", ".models", uid, "catalog-v6"))
blob, err := os.ReadFile(cachePath)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
logf("catalog cache read failed: %s", catalogReadErrorDetail(err))
}
} else if decryptor == nil {
logf("catalog decrypt failed: decryptor unavailable")
} else {
raw, err = decryptor.Decrypt(ctx, strings.TrimSpace(string(blob)), uid)
if err != nil {
logf("catalog decrypt failed: %s", catalogDecryptErrorDetail(err))
raw = nil
}
}
}
if len(raw) > 0 {
var cat struct {
Chat []*modelConfig `json:"chat"`
}
if json.Unmarshal(raw, &cat) == nil && len(cat.Chat) > 0 {
merged := map[string]*modelConfig{}
for _, mc := range catalog {
merged[mc.Key] = mc
}
for _, mc := range cat.Chat {
if mc.Format == "" {
mc.Format = "openai"
}
if mc.Source == "" {
mc.Source = "system"
}
mc.Enable = true
for _, tier := range mc.ContextConfig {
if tier.TokenCount > mc.MaxInputTokens {
mc.MaxInputTokens = tier.TokenCount
}
}
merged[mc.Key] = mc
}
catalog = catalog[:0]
for _, mc := range merged {
catalog = append(catalog, mc)
}
logf("catalog merged: %d models", len(catalog))
}
}
return catalog
}
func builtinCatalog() []*modelConfig {
type spec struct {
key, name string
reasoning bool
maxIn int
}
specs := []spec{
{"auto", "Auto", false, 180000},
{"ultimate", "Ultimate", true, 1000000},
{"performance", "Performance", false, 1000000},
{"efficient", "Efficient", false, 180000},
{"lite", "Lite", false, 180000},
{"cmodel", "Cantus", true, 1000000},
{"qmodel_38max", "Qwen3.8-Max", true, 1000000},
{"qmodel_latest", "Qwen3.7-Max", false, 1000000},
{"qmodel", "Qwen3.7-Plus", false, 1000000},
{"kmodel_latest", "Kimi-K3", false, 1000000},
{"kmodel", "Kimi-K2.7-Code", false, 256000},
{"gmodel", "GLM-5.3", true, 1000000},
{"gm51model", "GLM-5.2", true, 1000000},
{"dmodel", "DeepSeek-V4-Pro", true, 1000000},
{"dfmodel", "DeepSeek-V4-Flash", true, 1000000},
{"mmodel", "MiniMax-M3", false, 1000000},
}
out := make([]*modelConfig, 0, len(specs))
for _, sp := range specs {
out = append(out, &modelConfig{
Key: sp.key, Format: "openai", Source: "system", Enable: true,
DisplayName: sp.name, IsVL: true, IsReasoning: sp.reasoning,
PriceFactor: 1.0, MaxInputTokens: sp.maxIn,
})
}
return out
}
// patLogin exchanges a personal access token for a device token.
func patLogin(ctx context.Context, am *authManager, pat string) error {
if err := am.closedStateError(); err != nil {
return err
}
body, _ := json.Marshal(map[string]string{"personal_token": pat})
req, err := http.NewRequestWithContext(ctx, "POST", am.openapiBase+"/api/v1/jobToken/exchange", strings.NewReader(string(body)))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", qoderUserAgent())
resp, err := am.httpc.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
raw, _ := io.ReadAll(resp.Body)
if resp.StatusCode != 200 {
return fmt.Errorf("jobToken/exchange status %d: %s", resp.StatusCode, truncate(string(raw), 200))
}
var r struct {
Token string `json:"token"`
DeviceToken string `json:"device_token"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
ExpiresAt string `json:"expires_at"`
ExpiresIn int64 `json:"expires_in"`
RefreshExpAt string `json:"refresh_token_expires_at"`
RefreshExpIn int64 `json:"refresh_token_expires_in"`
}
if err := json.Unmarshal(raw, &r); err != nil {
return err
}
tok := r.Token
if tok == "" {
tok = r.DeviceToken
}
if tok == "" {
tok = r.AccessToken
}
if tok == "" {
return fmt.Errorf("exchange response missing token")
}
candidate := &userInfo{
SecurityOAuthToken: tok, AccessToken: tok,
RefreshToken: r.RefreshToken, ExpireTime: parseExpiry(r.ExpiresAt, r.ExpiresIn),
RefreshTokenExpireTime: parseExpiry(r.RefreshExpAt, r.RefreshExpIn),
PersonalAccessToken: pat,
LoginMethod: "token", LoginTimestamp: time.Now().Unix(),
}
profile, err := am.requestUserInfo(ctx, tok)
if err != nil {
return fmt.Errorf("could not fetch user info after exchange")
}
applyAuthUserInfoProfile(candidate, profile)
if candidate.UID == "" {
return fmt.Errorf("could not fetch user info after exchange")
}
am.mu.Lock()
if err := am.closedStateError(); err != nil {
am.mu.Unlock()
return err
}
if err := am.commitLoginCandidateLocked(ctx, candidate); err != nil {
am.mu.Unlock()
return err
}
am.mu.Unlock()
return nil
}