package provider // PLUGIN-SERVED (see AGENTS.md): WorkBuddy ("workbuddy" and "workbuddy-ai") // is a deprecated built-in subscription served by its plugin, // @magpie-community/opencode-workbuddy-auth, once moved onto it // (provider.Moved; the default for a new sign-in). A moved one's sign-ins, // models, requests and usage are all the plugin's, never this code's (only // the move, in migrate*.go, still reads its accounts). A fix here alone // doesn't reach those users; fix the plugin // (github.com/magpie-community/plugins, packages/workbuddy) and raise the // mover's min in internal/provider/migrate_workbuddy.go. // WorkBuddy's daily check-in (签到): while its event runs, a WorkBuddy // (China) account is given a few credits a day for pressing 签到 in the // app, more on a streak. While the setting is on, whichever magpie runs the // gateway presses it for each signed-in account once a Beijing day, as // WorkBuddy does: it asks the event's status, and claims when the event is // on and today's isn't in yet. // // Once a day: what came of it is kept in workbuddy-checkin.json, by site // and account id (no name, no token), so a restart doesn't ask again. An // answer — claimed, already in, not eligible, the event over — holds for // the rest of the day; a request that didn't get one (the network, a // refused token) is tried again after wbCheckinRetry, or, when it never // reached WorkBuddy (a machine just woken, its network not back yet), a // minute later, and twice as long each time it still doesn't. // // Only the Chinese build has the event: WorkBuddy AI ships with it off. import ( "context" "encoding/json" "errors" "io" "log" "net" "net/http" "os" "path/filepath" "slices" "sort" "strings" "sync" "time" "github.com/yetone/magpie/internal/plugin" "github.com/yetone/magpie/internal/settings" ) const ( // wbCheckinEvery is how often the accounts are looked at. wbCheckinEvery = 30 * time.Minute // wbCheckinRetry is how long a check-in that got no answer waits // before it is tried again the same day. wbCheckinRetry = 30 * time.Minute ) // WorkBuddy's check-in answers, the codes its claim refuses with. const ( wbCheckinAlready = 1001 // today's is in already wbCheckinIneligible = 1002 // the account can't take part wbCheckinEnded = 1003 // the event is over ) // What came of a day's check-in, WorkBuddyCheckin.Outcome. const ( CheckinClaimed = "claimed" // claimed by magpie CheckinDone = "done" // in already, pressed in WorkBuddy or before CheckinIneligible = "ineligible" // the account can't take part CheckinInactive = "inactive" // no event running, or it has ended CheckinFailed = "failed" // no answer; tried again later that day // CheckinCaptcha is a plugin's check-in the vendor asked a captcha // of: the user checks in in its own app, magpie never solves one CheckinCaptcha = "captcha" // CheckinOwnApp is a check-in the vendor pays out only to its own // app (Trae CN's 9074 to a device its app didn't register): an // answer for the day, and the user checks in in the vendor's app CheckinOwnApp = "own-app" ) // wbCheckinSoon is how long a check-in that never reached WorkBuddy waits // before it is tried again, doubling each time to wbCheckinRetry. const wbCheckinSoon = time.Minute // beijing is the day the event counts in, UTC+8 all year; fixed, so it // needs no time zone database (Windows has none Go can read without one). var beijing = time.FixedZone("CST", 8*60*60) // CheckinDay is the day (Beijing, "2006-01-02") WorkBuddy's check-in // counts t in: a WorkBuddyCheckin of that Day is today's. func CheckinDay(t time.Time) string { return wbCheckinDay(t) } // wbCheckinDay is the Beijing day ("2006-01-02") t falls on. func wbCheckinDay(t time.Time) string { return t.In(beijing).Format("2006-01-02") } // WorkBuddyCheckin is what came of a WorkBuddy account's check-in on Day // (Beijing): the credits it gave and the streak it made, or why none. type WorkBuddyCheckin struct { User string `json:"user,omitempty"` // as listed now; never kept Day string `json:"day"` At time.Time `json:"at"` Outcome string `json:"outcome"` Credit float64 `json:"credit,omitempty"` Streak int `json:"streak,omitempty"` Msg string `json:"msg,omitempty"` // ValidUntil is a campaign's end, when a successful answer must be // checked again, even if the Beijing day hasn't changed. ValidUntil time.Time `json:"until,omitzero"` // Offline is a failure that never reached WorkBuddy, and Tries how // many before it the same day did the same. Offline bool `json:"offline,omitempty"` Tries int `json:"tries,omitempty"` // By is the vendor whose check-in it is: "" WorkBuddy's, "trae" // Trae CN's; never kept. By string `json:"by,omitempty"` // Vendor is a plugin's provider by name, for a check-in By // "plugin:"; never kept. Vendor string `json:"vendor,omitempty"` // Asked is true of one checked in on this run, not one read back. Asked bool `json:"-"` } // Checked says whether the day's credits are in, claimed now or before. func (r WorkBuddyCheckin) Checked() bool { return r.Outcome == CheckinClaimed || r.Outcome == CheckinDone } // settled says whether r answers for day: it is that day's, and not a // failure due another try (at now; soon, at once). func (r WorkBuddyCheckin) settled(day string, now time.Time, soon bool) bool { if r.Day != day { return false } return r.Outcome != CheckinFailed || !soon && now.Sub(r.At) < r.retryAfter() } // retryAfter is how long a failure waits to be tried again: wbCheckinRetry, // or one that never reached WorkBuddy wbCheckinSoon, doubled for each try // before it that didn't either (#265: a check-in the moment the machine // woke, "no such host", then half an hour of 签到失败). func (r WorkBuddyCheckin) retryAfter() time.Duration { if !r.Offline { return wbCheckinRetry } return min(wbCheckinRetry, wbCheckinSoon< 0 } // wbCheckinAccounts are the WorkBuddy (China) accounts checked in: the // plugin's once WorkBuddy is moved onto it, checked in through it; not // moved, the built-in's, and the plugin's too where it is signed in under // its own id, "workbuddy-plugin" (signed in before the move existed, or // moved back), whose cards had their credits by day but no check-in // (#694, Dazzle-sys on 0.1.774: 没看到). func wbCheckinAccounts() []wbAccount { if Moved(wbCN.id) { pp, ok := PluginOf(wbCN.id) if !ok || pluginChecksIn(pp) { return nil } return wbPluginAccounts(pp) } out := wbLogins(wbCN) if pp, ok := PluginOf(PluginID(wbCN.id)); ok && pp.ID == wbCN.id && !pluginChecksIn(pp) { out = append(out, wbPluginAccounts(pp)...) } return out } // wbPluginAccounts are the WorkBuddy plugin's accounts of pp, each sent // through the plugin's fetch, which signs it, and told by the card its // usage is on. func wbPluginAccounts(pp plugin.Provider) []wbAccount { auths := plugin.Auths(pp.ID) card := PluginID(pp.ID) var out []wbAccount for _, l := range pluginLogins(pp) { key := l.acct.Key out = append(out, wbAccount{Login: l.Login, site: wbCN, card: card, creds: wbCreds{UID: str(auths[key]["uid"])}, via: func(req *http.Request) (*http.Response, error) { h := map[string]string{} for k, vs := range req.Header { h[strings.ToLower(k)] = vs[0] } var body []byte if req.Body != nil { body, _ = io.ReadAll(req.Body) } return plugin.Fetch(req.Context(), plugin.FetchRequest{Provider: pp.ID, Account: key, URL: req.URL.String(), Method: req.Method, Headers: h, Body: body}) }}) } return out } // KeepWorkBuddyCheckedIn checks the WorkBuddy accounts in each day while // settings say to: two minutes after it starts, every wbCheckinEvery after // that, and as the Beijing day turns, until ctx ends. func KeepWorkBuddyCheckedIn(ctx context.Context) { keepCheckedIn(ctx, "workbuddy", newWBCheckiner(), func() bool { return settings.Load().WorkBuddyCheckin }) } // keepCheckedIn runs c while on says to. The clock is looked at every // minute: a machine that slept through the day's turn notices on waking. func keepCheckedIn(ctx context.Context, label string, c checkinRunner, on func() bool) { t := time.NewTimer(2 * time.Minute) defer t.Stop() var l wbCheckinLoop for { select { case <-ctx.Done(): return case <-t.C: } if on() { for _, r := range l.tick(ctx, c) { switch { case !r.Asked: case r.Outcome == CheckinClaimed && r.Streak == 0: log.Printf("%s check-in: %s +%g", label, r.User, r.Credit) case r.Outcome == CheckinClaimed: log.Printf("%s check-in: %s +%g, a %d-day streak", label, r.User, r.Credit, r.Streak) case r.Outcome == CheckinFailed: log.Printf("%s check-in: %s: %s", label, r.User, r.Msg) default: log.Printf("%s check-in: %s: %s", label, r.User, r.Outcome) } } } t.Reset(time.Minute) } } // wbCheckinLoop is when keepCheckedIn last looked at the accounts, and // when a failure is due to be tried again, if before its next look. type wbCheckinLoop struct{ last, again time.Time } // tick looks at the accounts if it is time to: the first tick, // wbCheckinEvery after the last look, as the Beijing day turns, or as a // failure comes due again. It says how they stand, or nil. func (l *wbCheckinLoop) tick(ctx context.Context, c checkinRunner) []WorkBuddyCheckin { // the wall clock, which goes on while the machine sleeps now := c.clock().Round(0) if !l.last.IsZero() && now.Sub(l.last) < wbCheckinEvery && wbCheckinDay(now) == wbCheckinDay(l.last) && (l.again.IsZero() || now.Before(l.again)) { return nil } l.last, l.again = now, time.Time{} cx, cancel := context.WithTimeout(ctx, 2*time.Minute) defer cancel() rs := c.checkinNow(cx, false) for _, r := range rs { if r.Outcome != CheckinFailed { continue } if due := r.At.Add(r.retryAfter()); l.again.IsZero() || due.Before(l.again) { l.again = due } } return rs }