| 1 | package equipo |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "math" |
| 8 | "net/http" |
| 9 | "strconv" |
| 10 | "strings" |
| 11 | "time" |
| 12 | |
| 13 | "amadan.net/oficina/equipo/internal/equipo/chat" |
| 14 | "amadan.net/oficina/equipo/internal/wire" |
| 15 | "github.com/go-chi/chi/v5" |
| 16 | ) |
| 17 | |
| 18 | // Metered connections on the Connections page (connectors spec S1, S5): |
| 19 | // the TensorX and OpenCode Go options with their confirmation and |
| 20 | // budget, the key and model cards, and each metered row's spend line, |
| 21 | // pause and budget form. |
| 22 | |
| 23 | // meteredAdd is the chooser's form for one API-key provider. |
| 24 | type meteredAdd struct { |
| 25 | Provider, Name, Desc, How, Docs, DocsText, CannotSee, Confirm string |
| 26 | Day, Month string |
| 27 | Refused string |
| 28 | } |
| 29 | |
| 30 | // meteredAdds are the API-key providers the chooser offers, with the |
| 31 | // pre-filled budget (spec §0 decision 4). |
| 32 | func meteredAdds(refused string) []meteredAdd { |
| 33 | var out []meteredAdd |
| 34 | for _, name := range []string{wire.ProviderTensorX, wire.ProviderOpenCodeGo} { |
| 35 | kp := wire.APIKeyProviders[name] |
| 36 | docs := "chat.connections.metered.limit_docs" |
| 37 | if name != wire.ProviderTensorX { |
| 38 | docs += "." + name |
| 39 | } |
| 40 | add := meteredAdd{Provider: name, Name: copyText("chat.connections." + name), Desc: copyText("chat.connections." + name + "_desc"), How: copyText("chat.connections.metered.limit_how." + name), Docs: providerDocs[name], DocsText: copyText(docs), CannotSee: fmt.Sprintf(copyText("chat.connections.metered.cannot_see"), kp.Name), Confirm: fmt.Sprintf(copyText("chat.connections.metered.limit_confirm"), kp.Name), Day: moneyField(wire.DefaultBudgetDay), Month: moneyField(wire.DefaultBudgetMonth)} |
| 41 | switch refused { |
| 42 | case "confirm": |
| 43 | add.Refused = copyText("chat.connections.metered.confirm_first") |
| 44 | case "old": |
| 45 | add.Refused = copyText("chat.connections.metered.too_old") |
| 46 | } |
| 47 | out = append(out, add) |
| 48 | } |
| 49 | return out |
| 50 | } |
| 51 | |
| 52 | // providerDocs is where each provider says how its limit works (spec |
| 53 | // §2.1's sources). |
| 54 | var providerDocs = map[string]string{wire.ProviderTensorX: "https://docs.tensorx.ai/billing", wire.ProviderOpenCodeGo: "https://opencode.ai/docs/console/go/"} |
| 55 | |
| 56 | // money is an amount of micro-units in words: $1, $0.84, $6.20 (advice |
| 57 | // says amounts the same way). |
| 58 | func money(micros int64, currency string) string { return chat.Money(micros, currency) } |
| 59 | |
| 60 | // moneyField is an amount as a form field's value: 1, 0.5, 10.25. |
| 61 | func moneyField(micros int64) string { |
| 62 | return strings.TrimSuffix(strings.TrimRight(strconv.FormatFloat(float64(micros)/1e6, 'f', 2, 64), "0"), ".") |
| 63 | } |
| 64 | |
| 65 | // parseMoney reads a form's amount (1, 1.50, $2) as micro-units. |
| 66 | func parseMoney(s string) (int64, bool) { |
| 67 | s = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(s), "$")) |
| 68 | v, err := strconv.ParseFloat(s, 64) |
| 69 | if err != nil || math.IsNaN(v) || math.IsInf(v, 0) || v <= 0 || v > 1e6 { |
| 70 | return 0, false |
| 71 | } |
| 72 | return int64(math.Round(v * 1e6)), true |
| 73 | } |
| 74 | |
| 75 | // harnessName is how a harness is named to a person. |
| 76 | func harnessName(h string) string { |
| 77 | switch h { |
| 78 | case wire.HarnessPi: |
| 79 | return "Pi" |
| 80 | case wire.HarnessOpenCode: |
| 81 | return "OpenCode" |
| 82 | } |
| 83 | return h |
| 84 | } |
| 85 | |
| 86 | // meteredFacts are a metered row's spend line, its pause and its budget |
| 87 | // form (spec §2.3): "$0.84 today of $1 · $6.20 this month of $10", |
| 88 | // reported by the harness, can go over by one step. |
| 89 | func meteredFacts(row *connRow, c wire.Connection, runner string, now time.Time) { |
| 90 | row.Metered, row.Model = true, c.Model |
| 91 | row.CheckAgain = c.LocalID != "" && row.State != wire.ConnSignedOut |
| 92 | modelFacts(row, c, runner) |
| 93 | if c.Budget == nil { |
| 94 | return |
| 95 | } |
| 96 | row.BudgetDay, row.BudgetMonth, row.BudgetRevision = moneyField(c.Budget.Day), moneyField(c.Budget.Month), c.Budget.Revision |
| 97 | if c.BudgetPending { |
| 98 | row.Pending = fmt.Sprintf(copyText("chat.connections.metered.pending"), runner) |
| 99 | } |
| 100 | if c.Spend == nil { |
| 101 | return |
| 102 | } |
| 103 | s := c.Spend |
| 104 | row.Spend = fmt.Sprintf(copyText("chat.connections.metered.spend"), money(s.Day, s.Currency), money(c.Budget.Day, c.Budget.Currency), money(s.Month, s.Currency), money(c.Budget.Month, c.Budget.Currency)) |
| 105 | row.SpendTail = fmt.Sprintf(copyText("chat.connections.metered.reported_by"), harnessName(c.Harness)) |
| 106 | switch { |
| 107 | case s.Unknown: |
| 108 | row.Unknown, row.PauseRevision = fmt.Sprintf(copyText("chat.connections.metered.unknown"), providerName(c.Provider)), s.PauseRevision |
| 109 | case s.Month >= c.Budget.Month: |
| 110 | next := time.Date(now.UTC().Year(), now.UTC().Month()+1, 1, 0, 0, 0, 0, time.UTC) |
| 111 | row.Paused = fmt.Sprintf(copyText("chat.connections.metered.paused_month"), next.Format("2 Jan")) |
| 112 | case s.Day >= c.Budget.Day: |
| 113 | row.Paused = copyText("chat.connections.metered.paused_day") |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | // modelFacts are a metered row's allowed set (§16.1): "Models: 9 of |
| 118 | // 10" over the models that can be allowed, the list it opens, and the |
| 119 | // set pending until the runner applies it, or, on a runner too old to |
| 120 | // change the set, why it cannot. |
| 121 | func modelFacts(row *connRow, c wire.Connection, runner string) { |
| 122 | if c.ModelsTooOld { |
| 123 | // Its one model, exactly as before, and why it cannot change. |
| 124 | row.ModelsTooOld = copyText("chat.connections.metered.models_too_old") |
| 125 | return |
| 126 | } |
| 127 | if len(c.Models) == 0 { |
| 128 | return |
| 129 | } |
| 130 | allowed, eligible := 0, 0 |
| 131 | for _, m := range c.Models { |
| 132 | cm := connModel{ID: m.ID, Allowed: m.Allowed, Eligible: m.Eligible} |
| 133 | if m.Tier != "" { |
| 134 | cm.Tier = copyText("chat.connections.metered.tier." + m.Tier) |
| 135 | } |
| 136 | switch { |
| 137 | case !cm.Eligible: |
| 138 | cm.Note = copyText("chat.connections.metered.no_price") |
| 139 | case m.Allowed && m.Applied && m.State == wire.ModelUnhealthy: |
| 140 | cm.Note = copyText("chat.connections.metered.model_unhealthy") |
| 141 | } |
| 142 | if cm.Allowed && cm.Eligible { |
| 143 | allowed++ |
| 144 | } |
| 145 | if cm.Eligible { |
| 146 | eligible++ |
| 147 | } |
| 148 | row.Models = append(row.Models, cm) |
| 149 | } |
| 150 | row.Model = "" |
| 151 | row.ModelsLine = fmt.Sprintf(copyText("chat.connections.metered.models_count"), allowed, eligible) |
| 152 | row.ModelsRevision = c.ModelsRevision |
| 153 | if c.ModelsPending { |
| 154 | row.ModelsPending = fmt.Sprintf(copyText("chat.connections.metered.pending"), runner) |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | // connectionsModels is the models card's answer while a connection |
| 159 | // connects (revision 0), and a metered row's change of its set: the |
| 160 | // ticked models against the revision the page showed. |
| 161 | func (a *application) connectionsModels(w http.ResponseWriter, r *http.Request) { |
| 162 | back := "/conversation/settings/connections" |
| 163 | if r.PostFormValue("from") == "add" { |
| 164 | back += "/add" |
| 165 | } |
| 166 | a.chatActionTo(w, r, back, func(ctx context.Context, address string) error { |
| 167 | revision, err := strconv.ParseInt(r.PostFormValue("revision"), 10, 64) |
| 168 | if err != nil { |
| 169 | return chat.ErrInvalid |
| 170 | } |
| 171 | _, err = a.store.Chat().SetModels(ctx, address, chi.URLParam(r, "id"), wire.SetModels{Allowed: r.PostForm["model"], Revision: revision}) |
| 172 | return err |
| 173 | }) |
| 174 | } |
| 175 | |
| 176 | // connectionsStartMetered starts an API-key connection from the |
| 177 | // chooser's form: refused without the confirmation or a budget in |
| 178 | // bounds (the page says so), or on a runner too old for it. |
| 179 | func (a *application) connectionsStartMetered(w http.ResponseWriter, r *http.Request, ctx context.Context, address, provider string) { |
| 180 | day, okDay := parseMoney(r.PostFormValue("budget_day")) |
| 181 | month, okMonth := parseMoney(r.PostFormValue("budget_month")) |
| 182 | in := wire.Connect{Provider: provider, Kind: wire.KindAPIKey, LimitConfirmed: r.PostFormValue("limit_confirmed") == "1"} |
| 183 | if okDay && okMonth { |
| 184 | in.Budget = &wire.Budget{Day: day, Month: month} |
| 185 | } |
| 186 | _, err := a.store.Chat().StartConnection(ctx, address, in) |
| 187 | back := "/conversation/settings/connections/add" |
| 188 | switch { |
| 189 | case err == nil, errors.Is(err, chat.ErrRunnerOffline): |
| 190 | case errors.Is(err, chat.ErrConfirmation), errors.Is(err, chat.ErrInvalid): |
| 191 | back += "?refused=confirm" |
| 192 | case errors.Is(err, chat.ErrRunnerTooOld): |
| 193 | back += "?refused=old" |
| 194 | default: |
| 195 | a.failure(w, r, chatError(err)) |
| 196 | return |
| 197 | } |
| 198 | http.Redirect(w, r, back, http.StatusSeeOther) |
| 199 | } |
| 200 | |
| 201 | // connectionsModel is the model card's pick. |
| 202 | func (a *application) connectionsModel(w http.ResponseWriter, r *http.Request) { |
| 203 | a.chatActionTo(w, r, "/conversation/settings/connections/add", func(ctx context.Context, address string) error { |
| 204 | _, err := a.store.Chat().ChooseModel(ctx, address, chi.URLParam(r, "id"), wire.ChooseModel{Model: r.PostFormValue("model")}) |
| 205 | return err |
| 206 | }) |
| 207 | } |
| 208 | |
| 209 | // connectionsBudget is a metered row's Change budget. |
| 210 | func (a *application) connectionsBudget(w http.ResponseWriter, r *http.Request) { |
| 211 | a.chatActionTo(w, r, "/conversation/settings/connections", func(ctx context.Context, address string) error { |
| 212 | day, okDay := parseMoney(r.PostFormValue("budget_day")) |
| 213 | month, okMonth := parseMoney(r.PostFormValue("budget_month")) |
| 214 | revision, err := strconv.ParseInt(r.PostFormValue("revision"), 10, 64) |
| 215 | if !okDay || !okMonth || err != nil { |
| 216 | return chat.ErrInvalid |
| 217 | } |
| 218 | _, err = a.store.Chat().SetBudget(ctx, address, chi.URLParam(r, "id"), wire.SetBudget{Day: day, Month: month, Revision: revision}) |
| 219 | return err |
| 220 | }) |
| 221 | } |
| 222 | |
| 223 | // connectionsResume is a row's Resume when its spend is unknown, bound |
| 224 | // to the pause the page showed. |
| 225 | func (a *application) connectionsResume(w http.ResponseWriter, r *http.Request) { |
| 226 | a.chatActionTo(w, r, "/conversation/settings/connections", func(ctx context.Context, address string) error { |
| 227 | pause, err := strconv.ParseInt(r.PostFormValue("pause_revision"), 10, 64) |
| 228 | if err != nil { |
| 229 | return chat.ErrInvalid |
| 230 | } |
| 231 | return a.store.Chat().ResumeSpend(ctx, address, chi.URLParam(r, "id"), wire.ResumeSpend{PauseRevision: pause}) |
| 232 | }) |
| 233 | } |
| 234 | |