跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

claude_accounts.go

568 行 · 17.7 KB历史下载
1package workbench
2
3import (
4 "context"
5 "crypto/sha256"
6 "encoding/hex"
7 "encoding/json"
8 "errors"
9 "math"
10 "net/mail"
11 "os"
12 "path/filepath"
13 "slices"
14 "strings"
15 "sync"
16 "time"
17 "unicode"
18 "unicode/utf8"
19)
20
21// A profile ID selects a guest CLI configuration directory. Only public status
22// fields enter this registry; the official CLI owns authentication in the VM.
23type claudeAccount struct {
24 ID string `json:"id"`
25 Label string `json:"label"`
26 Source string `json:"source"`
27 ProfileID string `json:"profile_id,omitempty"`
28 Enabled bool `json:"enabled"`
29 Status string `json:"status"`
30 Email string `json:"email,omitempty"`
31 Organization string `json:"organization,omitempty"`
32 Plan string `json:"plan,omitempty"`
33 HandoffGroup string `json:"handoff_group,omitempty"`
34 Quota *claudeQuota `json:"quota,omitempty"`
35 CheckedAt int64 `json:"checked_at,omitempty"`
36 UsageStatus string `json:"usage_status,omitempty"`
37 UsageCheckedAt int64 `json:"usage_checked_at,omitempty"`
38 UsageChecking bool `json:"usage_checking,omitempty"`
39}
40
41type claudeQuota struct {
42 FiveHour *claudeWindow `json:"five_hour,omitempty"`
43 SevenDay *claudeWindow `json:"seven_day,omitempty"`
44 ObservedAt int64 `json:"observed_at"`
45}
46
47type claudeWindow struct {
48 UsedPercentage float64 `json:"used_percentage"`
49 ResetsAt int64 `json:"resets_at"`
50 ObservedAt int64 `json:"observed_at,omitempty"`
51}
52
53type claudeGuestSnapshot struct {
54 UsageStatus string `json:"usage_status,omitempty"`
55 UsageCheckedAt int64 `json:"usage_checked_at,omitempty"`
56 LoggedIn bool `json:"logged_in"`
57 Email string `json:"email"`
58 Organization string `json:"organization"`
59 Plan string `json:"plan"`
60 Quota *claudeQuota `json:"quota"`
61}
62
63type claudeAccountList struct {
64 Accounts []claudeAccount `json:"accounts"`
65 PendingLogin string `json:"pending_login,omitempty"`
66 Scheduling claudeScheduling `json:"scheduling"`
67}
68
69type claudeScheduling struct {
70 Mode string `json:"mode"`
71 SwitchPolicy string `json:"switch_policy"`
72}
73
74func (p claudeScheduling) defaults() claudeScheduling {
75 if p.Mode == "" {
76 p.Mode = "balanced"
77 }
78 if p.SwitchPolicy == "" {
79 p.SwitchPolicy = "ask"
80 }
81 return p
82}
83
84func (p claudeScheduling) valid() bool {
85 return (p.Mode == "balanced" || p.Mode == "sequential") && (p.SwitchPolicy == "ask" || p.SwitchPolicy == "allow" || p.SwitchPolicy == "wait")
86}
87
88type claudeAccountManager struct {
89 usageProbe func(context.Context, string, string) (claudeGuestSnapshot, error)
90 usageActive map[string]*claudeUsageCall
91 panelRunning bool
92 panelUntil time.Time
93 detectedUsage map[string]*claudeAccount
94 defaultGate chan struct{}
95 loginNotice string
96 defaultChecked time.Time
97 defaultReading claudeGuestSnapshot
98 defaultError error
99 probe func(context.Context, string) (claudeGuestSnapshot, error)
100 mu sync.Mutex
101 lastPick string
102 recent map[string]claudeProjectPick
103 refreshing map[string]*claudeRefresh
104 attempted map[string]time.Time
105}
106
107type claudeRefresh struct {
108 done chan struct{}
109 err error
110}
111
112const claudeQuotaFresh = 15 * time.Minute
113
114func validClaudeID(id string) bool {
115 _, err := hex.DecodeString(id)
116 return len(id) == 24 && err == nil && strings.ToLower(id) == id
117}
118
119func (s *Server) loadClaudeAccounts() (claudeAccountList, error) {
120 list := claudeAccountList{Accounts: []claudeAccount{}, Scheduling: (claudeScheduling{}).defaults()}
121 data, err := os.ReadFile(filepath.Join(s.profile, "claude-accounts.json"))
122 if os.IsNotExist(err) {
123 return list, nil
124 }
125 if err != nil || json.Unmarshal(data, &list) != nil || list.Accounts == nil {
126 return list, errors.New("Claude 账号文件无法读取,请检查配置目录或恢复备份")
127 }
128 list.Scheduling = list.Scheduling.defaults()
129 if !list.Scheduling.valid() {
130 return list, errors.New("Claude 调度设置无效,请检查配置文件")
131 }
132 ids := make(map[string]bool)
133 profiles := make(map[string]bool)
134 for i := range list.Accounts {
135 a := &list.Accounts[i]
136 if a.Source == "" {
137 a.Source = "managed"
138 }
139 if !validClaudeID(a.ID) || ids[a.ID] || a.Source != "managed" && a.Source != "default" || a.Source == "default" && (a.Email == "" || a.ProfileID != "") || a.ProfileID != "" && !validClaudeID(a.ProfileID) || len(a.HandoffGroup) > 64 {
140 return list, errors.New("Claude 账号文件含无效或重复的记录,请从备份恢复")
141 }
142 ids[a.ID] = true
143 if a.Source == "managed" {
144 if profiles[a.guestID()] {
145 return list, errors.New("多个账号引用了同一个独立登录目录,请从备份恢复")
146 }
147 profiles[a.guestID()] = true
148 }
149 }
150 if list.PendingLogin != "" && (!validClaudeID(list.PendingLogin) || ids[list.PendingLogin] || profiles[list.PendingLogin]) {
151 return list, errors.New("Claude 登录记录损坏,请恢复备份")
152 }
153 return list, nil
154}
155
156func (s *Server) saveClaudeAccounts(list claudeAccountList) error {
157 if err := writePrivate(filepath.Join(s.profile, "claude-accounts.json"), list); err != nil {
158 return errors.New("Claude 账号设置未保存,请检查配置目录权限和磁盘空间")
159 }
160 return nil
161}
162
163func (a claudeAccount) guestID() string {
164 if a.Source == "default" {
165 return "default"
166 }
167 if a.ProfileID != "" {
168 return a.ProfileID
169 }
170 return a.ID
171}
172
173func (list claudeAccountList) find(id string) *claudeAccount {
174 for i := range list.Accounts {
175 if list.Accounts[i].ID == id {
176 return &list.Accounts[i]
177 }
178 }
179 return nil
180}
181
182func validClaudeLabel(label string) bool {
183 return label != "" && utf8.RuneCountInString(label) <= 64 && strings.IndexFunc(label, unicode.IsControl) < 0
184}
185
186func (list *claudeAccountList) change(input claudeAccountInput) error {
187 label := strings.TrimSpace(input.Label)
188 if input.Action != "update" {
189 return errors.New("未知 Claude 账号操作")
190 }
191 a := list.find(input.ID)
192 if a == nil {
193 return errors.New("未找到 Claude 账号,请刷新面板")
194 }
195 if input.Label != "" {
196 if !validClaudeLabel(label) && (label == "" || label != a.Email) {
197 return errors.New("备注最多 64 个字符,不能含控制字符")
198 }
199 a.Label = label
200 }
201 if input.Enabled != nil {
202 a.Enabled = *input.Enabled
203 }
204 if input.HandoffGroup != nil {
205 group := strings.TrimSpace(*input.HandoffGroup)
206 if len(group) > 64 || strings.IndexFunc(group, unicode.IsControl) >= 0 {
207 return errors.New("接续分组最多 64 字节,不能含控制字符")
208 }
209 a.HandoffGroup = group
210 }
211 return nil
212}
213
214func (r claudeGuestSnapshot) email() string {
215 email := strings.ToLower(strings.TrimSpace(r.Email))
216 mailbox, err := mail.ParseAddress(email)
217 if !r.LoggedIn || err != nil || mailbox.Address != email {
218 return ""
219 }
220 return email
221}
222
223func (r claudeGuestSnapshot) subject() string {
224 if email := r.email(); email != "" {
225 return claudeIdentityHash(email, r.Organization)
226 }
227 return ""
228}
229
230func validClaudeWindow(w *claudeWindow) bool {
231 return w != nil && !math.IsNaN(w.UsedPercentage) && w.UsedPercentage >= 0 && w.UsedPercentage <= 100 && w.ResetsAt >= 0
232}
233
234// A missing reading cannot invalidate an existing reading, or make an old
235// reading fresh. Never attach a previous identity's quota to a new identity.
236func (list claudeAccountList) observe(id string, observed claudeGuestSnapshot, now time.Time) error {
237 a := list.find(id)
238 if a == nil {
239 return errors.New("未找到 Claude 账号")
240 }
241 a.CheckedAt = now.Unix()
242 email := observed.email()
243 if email == "" {
244 a.Status = "signed_out"
245 return nil
246 }
247 organization := strings.TrimSpace(observed.Organization)
248 if a.Email != "" && (!strings.EqualFold(a.Email, email) || a.Organization != organization) {
249 a.Status = "changed"
250 return nil
251 }
252 for _, other := range list.Accounts {
253 if other.ID != id && strings.EqualFold(other.Email, email) && other.Organization == organization {
254 a.Status = "duplicate"
255 return nil
256 }
257 }
258 a.Status, a.Email, a.Organization, a.Plan = "ready", email, organization, observed.Plan
259 a.mergeQuota(observed.Quota, now)
260 return nil
261}
262
263func (a *claudeAccount) mergeQuota(q *claudeQuota, now time.Time) bool {
264 if q == nil || q.ObservedAt <= 0 || q.ObservedAt > now.Unix() {
265 return false
266 }
267 next := claudeQuota{}
268 if a.Quota != nil {
269 next = *a.Quota
270 }
271 merge := func(old, reading *claudeWindow) *claudeWindow {
272 if !validClaudeWindow(reading) {
273 return old
274 }
275 window := *reading
276 if window.ObservedAt == 0 {
277 window.ObservedAt = q.ObservedAt
278 }
279 if window.ObservedAt < 0 || window.ObservedAt > q.ObservedAt || old != nil && old.ObservedAt > window.ObservedAt {
280 return old
281 }
282 if old != nil && window == *old {
283 return old
284 }
285 return &window
286 }
287 next.FiveHour = merge(next.FiveHour, q.FiveHour)
288 next.SevenDay = merge(next.SevenDay, q.SevenDay)
289 if next.FiveHour == nil && next.SevenDay == nil || a.Quota != nil && next == *a.Quota {
290 return false
291 }
292 next.ObservedAt = max(next.ObservedAt, q.ObservedAt)
293 a.Quota = &next
294 return true
295}
296
297func claudeIdentityHash(email, organization string) string {
298 digest := sha256.Sum256([]byte(strings.ToLower(strings.TrimSpace(email)) + "\n" + strings.TrimSpace(organization)))
299 return hex.EncodeToString(digest[:])
300}
301
302// A fully used window still blocks new sessions until its actual reset, even
303// if the snapshot is stale. An expired or unreported window stays unknown.
304func (a claudeAccount) headroom(now time.Time) (float64, bool) {
305 if a.Quota == nil {
306 return -1, true
307 }
308 least := -1.0
309 for _, w := range []*claudeWindow{a.Quota.FiveHour, a.Quota.SevenDay} {
310 if !validClaudeWindow(w) || w.ResetsAt > 0 && w.ResetsAt <= now.Unix() {
311 continue
312 }
313 fresh := now.Sub(time.Unix(w.ObservedAt, 0)) <= claudeQuotaFresh
314 if w.UsedPercentage >= 100 && (w.ResetsAt > now.Unix() || fresh) {
315 return 0, false
316 }
317 if fresh {
318 remaining := 100 - w.UsedPercentage
319 if least < 0 || remaining < least {
320 least = remaining
321 }
322 }
323 }
324 return least, true
325}
326
327// A selection carries the identity verified for this launch. The caller
328// must not replace Subject or GuestID by looking the record up again.
329type claudeSelection struct{ ID, GuestID, Subject string }
330
331func (s *Server) selectClaudeAccount(requestedID string, login bool, workspace string) (claudeSelection, error) {
332 var empty claudeSelection
333 if !login && requestedID != "" && requestedID != "auto" {
334 return empty, errors.New("Claude 终端会自动分配账号")
335 }
336 m := &s.claudeAccounts
337 m.mu.Lock()
338 list, err := s.loadClaudeAccounts()
339 if err == nil && list.PendingLogin != "" && requestedID == "" && !s.claudeLoginActive(list.PendingLogin) {
340 m.mu.Unlock()
341 // Restore a successful login from before a controller restart or lock
342 // before a new login could write into the same guest directory.
343 if epoch, ok := s.account.access(); ok {
344 if probeErr := s.recoverClaudePending(epoch, list.PendingLogin, login); login && probeErr != nil {
345 return empty, probeErr
346 }
347 }
348 m.mu.Lock()
349 list, err = s.loadClaudeAccounts()
350 }
351 if err == nil && login {
352 if requestedID == "" {
353 if list.PendingLogin == "" {
354 list.PendingLogin = randomToken()[:24]
355 m.loginNotice = ""
356 err = s.saveClaudeAccounts(list)
357 }
358 requestedID = list.PendingLogin
359 } else if a := list.find(requestedID); a == nil || a.Source != "managed" {
360 err = errors.New("请在普通终端管理环境的默认登录")
361 }
362 }
363 m.mu.Unlock()
364 if err != nil {
365 return empty, err
366 }
367 if login {
368 guestID := requestedID
369 if a := list.find(requestedID); a != nil {
370 guestID = a.guestID()
371 }
372 return claudeSelection{ID: requestedID, GuestID: guestID}, nil
373 }
374 if len(list.Accounts) == 0 {
375 return empty, nil
376 }
377 return s.allocateClaudeAccount(list, workspace, s.readClaudeGuestQuotas)
378}
379
380type claudeGuestQuota struct {
381 claudeQuota
382 Identity string `json:"identity"`
383}
384
385func (s *Server) readClaudeGuestQuotas(ctx context.Context, ids []string) (map[string]claudeGuestQuota, error) {
386 for _, id := range ids {
387 if !validClaudeID(id) {
388 return nil, errors.New("Claude 账号 ID 无效")
389 }
390 }
391 // s.guest bounds its output to 64 KiB. Even a large pool uses one
392 // server-controlled deadline; keep completed chunks when a later one fails.
393 readings := make(map[string]claudeGuestQuota)
394 for chunk := range slices.Chunk(ids, 96) {
395 if s.windowsGuest != nil {
396 if err := s.windowsCLIRequest(ctx, map[string]any{"action": "account", "mode": "quotas", "ids": chunk}, &readings); err != nil {
397 return readings, err
398 }
399 continue
400 }
401 data, err := s.guest(ctx, "exec /usr/local/bin/cage-claude-account quotas "+strings.Join(chunk, " "))
402 if err != nil {
403 return readings, err
404 }
405 if err := json.Unmarshal(data, &readings); err != nil {
406 return readings, err
407 }
408 }
409 return readings, nil
410}
411
412// The status line may have written a newer reading while the account panel
413// was closed. Fetch only its small local files in one SSH command. The guest
414// does not start the CLI, read tokens, or contact Anthropic for this read.
415func (s *Server) allocateClaudeAccount(previous claudeAccountList, workspace string, read func(context.Context, []string) (map[string]claudeGuestQuota, error)) (claudeSelection, error) {
416 var empty claudeSelection
417 epoch, unlocked := s.account.access()
418 if !unlocked {
419 return empty, errors.New("Cage 已锁定,请先解锁")
420 }
421 var ids []string
422 checkDefault := false
423 for _, a := range previous.Accounts {
424 if a.Source == "default" {
425 checkDefault = checkDefault || a.Enabled
426 } else if a.Enabled && a.Status == "ready" {
427 ids = append(ids, a.guestID())
428 }
429 }
430 var readings map[string]claudeGuestQuota
431 if len(ids) > 0 {
432 ctx, cancel := context.WithTimeout(epoch, 4*time.Second)
433 readings, _ = read(ctx, ids) // Retain the last snapshot when SSH is unavailable.
434 cancel()
435 }
436 defaultSubject := ""
437 if checkDefault {
438 if reading, _, err := s.inspectClaudeDefault(epoch, true); err == nil {
439 defaultSubject = reading.subject()
440 }
441 }
442 m := &s.claudeAccounts
443 m.mu.Lock()
444 defer m.mu.Unlock()
445 if epoch.Err() != nil {
446 return empty, errors.New("Cage 已锁定,请先解锁")
447 }
448 list, err := s.loadClaudeAccounts()
449 if err != nil {
450 return empty, err
451 }
452 now := time.Now()
453 updated := false
454 for i := range list.Accounts {
455 a := &list.Accounts[i]
456 q, ok := readings[a.guestID()]
457 if a.Enabled && a.Status == "ready" && ok && q.Identity == claudeIdentityHash(a.Email, a.Organization) {
458 if a.mergeQuota(&q.claudeQuota, now) {
459 updated = true
460 }
461 }
462 }
463 if updated {
464 if err = s.saveClaudeAccounts(list); err != nil {
465 return empty, err
466 }
467 }
468 active := s.mobileCLI.activeAccounts()
469 logins := make(map[string]bool)
470 for _, session := range s.terminals.snapshot() {
471 if session["closed"] == true {
472 continue
473 }
474 id, _ := session["claude_account_id"].(string)
475 if session["kind"] == "claude-login" {
476 logins[id] = true
477 } else {
478 active[id]++
479 }
480 }
481 recent := m.recent[workspace]
482 preferred := ""
483 if now.Sub(recent.at) < claudeProjectAffinity {
484 preferred = recent.id
485 }
486 // Only a positively verified matching default profile can be admitted.
487 for i := range list.Accounts {
488 a := &list.Accounts[i]
489 if a.Source == "default" && (defaultSubject == "" || defaultSubject != claudeIdentityHash(a.Email, a.Organization)) {
490 a.Enabled = false // local selection view, not the persisted preference
491 }
492 }
493 selected := pickClaudeAccount(list, active, logins, m.lastPick, preferred, now)
494 if selected == "" {
495 return empty, errors.New("暂无可分配的 Claude 账号。请在账号面板检查登录、参与状态和额度重置时间")
496 }
497 a := list.find(selected)
498 return claudeSelection{ID: selected, GuestID: a.guestID(), Subject: claudeIdentityHash(a.Email, a.Organization)}, nil
499}
500
501// Start at the account following the last allocation. Among eligible accounts,
502// prefer fewer live sessions, then the largest known remaining minimum window.
503func pickClaudeAccount(list claudeAccountList, active map[string]int, logins map[string]bool, last, preferred string, now time.Time) string {
504 if list.Scheduling.Mode == "sequential" {
505 for _, a := range list.Accounts {
506 if _, eligible := a.headroom(now); a.Enabled && a.Status == "ready" && !logins[a.ID] && eligible {
507 return a.ID
508 }
509 }
510 return ""
511 }
512 start := slices.IndexFunc(list.Accounts, func(a claudeAccount) bool { return a.ID == last }) + 1
513 best := ""
514 var bestActive int
515 var bestRoom float64
516 for offset := range list.Accounts {
517 a := list.Accounts[(start+offset)%len(list.Accounts)]
518 if !a.Enabled || a.Status != "ready" || logins[a.ID] {
519 continue
520 }
521 room, eligible := a.headroom(now)
522 if eligible && (best == "" || active[a.ID] < bestActive || active[a.ID] == bestActive && room > bestRoom) {
523 best, bestActive, bestRoom = a.ID, active[a.ID], room
524 }
525 }
526 // Keep a recent project's profile only when it has the same load and
527 // comparable headroom (both unknown, or within five percentage points).
528 if a := list.find(preferred); a != nil && a.Enabled && a.Status == "ready" && !logins[a.ID] && active[a.ID] == bestActive {
529 room, ok := a.headroom(now)
530 if ok && (room == bestRoom || room >= 0 && bestRoom-room <= min(5, bestRoom*0.1)) {
531 return a.ID
532 }
533 }
534 return best
535}
536
537type claudeProjectPick struct {
538 id string
539 at time.Time
540}
541
542const claudeProjectAffinity = 5 * time.Minute
543
544func (s *Server) noteClaudeSelection(id, workspace string) {
545 m := &s.claudeAccounts
546 m.mu.Lock()
547 defer m.mu.Unlock()
548 m.lastPick = id
549 if workspace == "" {
550 return
551 }
552 if m.recent == nil {
553 m.recent = make(map[string]claudeProjectPick)
554 }
555 now := time.Now()
556 var oldest string
557 for path, pick := range m.recent {
558 if now.Sub(pick.at) >= claudeProjectAffinity {
559 delete(m.recent, path)
560 } else if oldest == "" || pick.at.Before(m.recent[oldest].at) {
561 oldest = path
562 }
563 }
564 m.recent[workspace] = claudeProjectPick{id: id, at: now}
565 if len(m.recent) > 64 {
566 delete(m.recent, oldest)
567 }
568}