-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcodingplan.go
More file actions
288 lines (271 loc) · 8.01 KB
/
Copy pathcodingplan.go
File metadata and controls
288 lines (271 loc) · 8.01 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
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
type codingPlanClaimResponse struct {
Success bool `json:"success"`
Duplicate bool `json:"duplicate"`
Message string `json:"message"`
PlanName string `json:"plan_name"`
PlanType string `json:"plan_type"`
}
type CodingPlanClaimOutcome struct {
Account AccountView
Attempts []CodingPlanClaimAttempt
PlanName string
Message string
}
type CodingPlanClient struct {
config *ConfigManager
store *Store
client *http.Client
oauth *OAuthManager
}
func NewCodingPlanClient(config *ConfigManager, store *Store) *CodingPlanClient {
return &CodingPlanClient{config: config, store: store, client: &http.Client{Timeout: 20 * time.Second}}
}
func (c *CodingPlanClient) SetOAuthManager(oauth *OAuthManager) {
c.oauth = oauth
}
func (c *CodingPlanClient) ClaimAndSync(ctx context.Context, accountID string) (AccountView, error) {
outcome, err := c.ClaimAndSyncDetailed(ctx, accountID)
return outcome.Account, err
}
func (c *CodingPlanClient) ClaimAndSyncDetailed(ctx context.Context, accountID string) (CodingPlanClaimOutcome, error) {
var outcome CodingPlanClaimOutcome
account, token, _, err := c.store.Account(accountID)
if err != nil {
return outcome, err
}
if c.oauth != nil {
token, err = c.oauth.Refresh(ctx, accountID)
if err != nil {
return outcome, err
}
}
claimResponse, attempts, err := c.claim(ctx, token)
outcome.Attempts = attempts
outcome.PlanName = claimResponse.PlanName
outcome.Message = claimResponse.Message
if err != nil {
return outcome, err
}
status, err := c.fetchStatus(ctx, token)
if err != nil {
return outcome, err
}
tier := planTier(status.Plan)
models, err := c.fetchModels(ctx, token, tier)
if err != nil {
return outcome, err
}
usage, usageErr := c.fetchUsage(ctx, token)
now := time.Now().UTC()
outcome.Account, err = c.store.UpdateAccount(account.ID, func(stored *Account) error {
stored.Plan = status
stored.Models = models
stored.ProviderUsage = usage
stored.LastSyncAt = &now
stored.Status = "active"
stored.LastError = ""
if usageErr != nil {
stored.LastError = "usage sync: " + usageErr.Error()
}
return nil
})
if outcome.Account.Plan.Plan != nil {
outcome.PlanName = outcome.Account.Plan.Plan.PlanName
}
return outcome, err
}
func (c *CodingPlanClient) Sync(ctx context.Context, accountID string) (AccountView, error) {
account, token, _, err := c.store.Account(accountID)
if err != nil {
return AccountView{}, err
}
if c.oauth != nil {
token, err = c.oauth.Refresh(ctx, accountID)
if err != nil {
return AccountView{}, err
}
}
status, err := c.fetchStatus(ctx, token)
if err != nil {
return AccountView{}, err
}
models, err := c.fetchModels(ctx, token, planTier(status.Plan))
if err != nil {
return AccountView{}, err
}
usage, usageErr := c.fetchUsage(ctx, token)
now := time.Now().UTC()
return c.store.UpdateAccount(account.ID, func(stored *Account) error {
stored.Plan = status
stored.Models = models
stored.ProviderUsage = usage
stored.LastSyncAt = &now
stored.Status = "active"
stored.LastError = ""
if usageErr != nil {
stored.LastError = "usage sync: " + usageErr.Error()
}
return nil
})
}
func (c *CodingPlanClient) claim(ctx context.Context, token string) (codingPlanClaimResponse, []CodingPlanClaimAttempt, error) {
var last string
attempts := make([]CodingPlanClaimAttempt, 0, 3)
for _, tier := range []string{"Max", "Pro", "Lite"} {
var response codingPlanClaimResponse
httpStatus, rawResponse, err := c.request(ctx, http.MethodPost, "/coding-plan/claim-v2", token, map[string]string{"plan_type": tier}, &response)
if err != nil && len(rawResponse) > 0 {
_ = json.Unmarshal(rawResponse, &response)
}
message := response.Message
if message == "" && err != nil {
message = err.Error()
}
attempts = append(attempts, CodingPlanClaimAttempt{
PlanType: tier, HTTPStatus: httpStatus, Response: string(rawResponse),
Success: err == nil && response.Success, Duplicate: err == nil && response.Duplicate, Message: message,
})
if err != nil {
last = message
continue
}
if response.Success || response.Duplicate {
return response, attempts, nil
}
if response.Message != "" {
last = response.Message
}
}
if last == "" {
last = "no Coding Plan tier is currently available"
}
return codingPlanClaimResponse{}, attempts, errors.New(last)
}
func (c *CodingPlanClient) fetchStatus(ctx context.Context, token string) (CodingPlanStatus, error) {
var status CodingPlanStatus
_, _, err := c.request(ctx, http.MethodGet, "/coding-plan/status-v2", token, nil, &status)
return status, err
}
func (c *CodingPlanClient) fetchModels(ctx context.Context, token, tier string) ([]CodingPlanModel, error) {
var models []CodingPlanModel
path := "/coding-plan/models-v2?plan_type=" + url.QueryEscape(tier)
if _, _, err := c.request(ctx, http.MethodGet, path, token, nil, &models); err != nil {
return nil, err
}
config := c.config.Snapshot()
available := make([]CodingPlanModel, 0, len(models))
for _, model := range models {
if model.DisplayModelName == "" || !model.PlanAvailable {
continue
}
if model.BaseURL == "" {
model.BaseURL = config.GatewayURL
}
if model.ProviderType == "" {
model.ProviderType = "openai"
}
if model.ContextWindow <= 0 {
model.ContextWindow = 64000
}
available = append(available, model)
}
return available, nil
}
func (c *CodingPlanClient) fetchUsage(ctx context.Context, token string) (*ProviderUsage, error) {
var usage ProviderUsage
if _, _, err := c.request(ctx, http.MethodGet, "/coding-plan/usage", token, nil, &usage); err != nil {
return nil, err
}
return &usage, nil
}
func (c *CodingPlanClient) request(ctx context.Context, method, path, token string, body, result any) (int, []byte, error) {
base := strings.TrimRight(c.config.Snapshot().CodingPlanAPIURL, "/")
var encodedBody []byte
if body != nil {
encoded, err := json.Marshal(body)
if err != nil {
return 0, nil, err
}
encodedBody = encoded
}
var response *http.Response
var err error
for attempt := 0; attempt < 3; attempt++ {
var reader io.Reader
if encodedBody != nil {
reader = bytes.NewReader(encodedBody)
}
request, requestErr := http.NewRequestWithContext(ctx, method, base+path, reader)
if requestErr != nil {
return 0, nil, requestErr
}
request.Header.Set("Authorization", "Bearer "+token)
request.Header.Set("Accept", "application/json")
request.Header.Set("User-Agent", c.config.Snapshot().UserAgent)
if body != nil {
request.Header.Set("Content-Type", "application/json")
}
response, err = c.client.Do(request)
if err == nil {
break
}
if attempt < 2 {
time.Sleep(time.Duration(attempt+1) * 150 * time.Millisecond)
}
}
if err != nil {
return 0, nil, fmt.Errorf("Coding Plan request failed: %w", err)
}
defer response.Body.Close()
data, err := io.ReadAll(io.LimitReader(response.Body, 8<<20))
if err != nil {
return response.StatusCode, data, err
}
if response.StatusCode == http.StatusUnauthorized || response.StatusCode == http.StatusForbidden {
return response.StatusCode, data, fmt.Errorf("Coding Plan authentication failed (%d); reconnect the account", response.StatusCode)
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return response.StatusCode, data, fmt.Errorf("Coding Plan returned %d: %s", response.StatusCode, compactError(data))
}
if err := json.Unmarshal(data, result); err != nil {
return response.StatusCode, data, fmt.Errorf("decode Coding Plan response: %w", err)
}
return response.StatusCode, data, nil
}
func planTier(plan *PlanInfo) string {
if plan == nil {
return "Lite"
}
name := strings.ToLower(plan.PlanName)
switch {
case strings.Contains(name, "max"):
return "Max"
case strings.Contains(name, "pro"):
return "Pro"
default:
return "Lite"
}
}
func compactError(data []byte) string {
value := strings.TrimSpace(string(data))
if len(value) > 500 {
value = value[:500] + "..."
}
if value == "" {
return "empty response"
}
return value
}