g1t/crates/contracts/src/billing.rs

886 lines30,255 bytesCodeBlame
1//! The billing service: what agents cost, charged to the workspace they
2//! worked for.
3//!
4//! A workspace buys credit and each agent run deducts what it cost, plus
5//! g1t's margin. With no credit, no agent starts. Money is held in
6//! millionths of a US dollar, so that a run costing a fraction of a cent is
7//! recorded exactly.
8//!
9//! Each `*Args` struct is the argument of the method of the same name,
10//! served at `POST /rpc/<method>`.
11
12use serde::{Deserialize, Serialize};
13
14use crate::repos::RepoPath;
15use crate::{User, Viewer};
16
17/// Millionths of a US dollar in one dollar.
18pub const MICROS_PER_DOLLAR: i64 = 1_000_000;
19
20/// Whether workspaces are charged for agents at all, and with real money.
21/// `status` takes nothing and returns this.
22#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)]
23pub struct Status {
24 /// False when no payment provider is configured: nothing is charged,
25 /// and who may run agents is decided some other way.
26 pub enabled: bool,
27 /// False while the payment provider is in its test mode, where cards
28 /// are not real.
29 pub live: bool,
30 /// True while g1t is being built out: runs are recorded, with what
31 /// they cost, but nothing is charged and no credit is needed. Not a
32 /// promise that it stays free.
33 #[serde(default)]
34 pub free: bool,
35}
36
37/// `trial`: the free allowance on g1t's hosted models for a workspace that
38/// is not otherwise open to them, so people can try g1t's agents without a
39/// key of their own. Each workspace gets a few dollars of model cost, out
40/// of one pool, until an end date. Returns `Trial`.
41#[derive(Debug, Serialize, Deserialize)]
42#[serde(rename_all = "camelCase")]
43pub struct TrialArgs {
44 pub workspace: String,
45 /// Workspaces open to hosted models anyway, whose use is not counted
46 /// against the pool.
47 #[serde(default)]
48 pub exempt: Vec<String>,
49}
50
51#[derive(Clone, Debug, Serialize, Deserialize)]
52#[serde(rename_all = "camelCase")]
53pub struct Trial {
54 /// Whether its agents may use g1t's hosted models on the allowance now.
55 pub open: bool,
56 /// What its runs on g1t's models have cost, in millionths of a dollar.
57 pub used_micros: i64,
58 pub limit_micros: i64,
59 /// RFC 3339; when the allowance ends for everyone.
60 pub ends_at: Option<String>,
61 /// Why it is closed: `off` (no allowance), `ended`, `used` (this
62 /// workspace's is spent) or `pool` (everyone's is).
63 pub reason: Option<String>,
64}
65
66/// A workspace's standing.
67#[derive(Clone, Debug, Serialize, Deserialize)]
68#[serde(rename_all = "camelCase")]
69pub struct Account {
70 pub workspace: String,
71 /// Credit left, in millionths of a dollar. Can dip below zero by the
72 /// cost of the runs that were under way when it ran out.
73 pub balance_micros: i64,
74 pub status: Status,
75 /// What is added to a run's cost, in percent.
76 pub margin_percent: u32,
77 /// What a run on the workspace's own model provider is charged: g1t's
78 /// sandbox and orchestration, with the model paid for elsewhere.
79 pub orchestration_fee_micros: i64,
80 /// The card g1t charges as the workspace nears its limit and when a
81 /// month closes, if one is on file.
82 #[serde(default)]
83 pub card: Option<Card>,
84}
85
86/// A saved card, as far as it is safe to show.
87#[derive(Clone, Debug, Serialize, Deserialize)]
88#[serde(rename_all = "camelCase")]
89pub struct Card {
90 /// `visa`, `mastercard`, ...
91 pub brand: String,
92 pub last4: String,
93 pub exp_month: u32,
94 pub exp_year: u32,
95}
96
97/// `billing_portal`: Stripe's hosted billing page for the workspace, where
98/// an owner adds or replaces the card, sees invoices and receipts, and sets
99/// the billing email and address. g1t never handles card numbers. Owners
100/// only. Returns `Outcome<Checkout>` (its `url`); Stripe sends them back
101/// to `return_url`.
102#[derive(Debug, Serialize, Deserialize)]
103pub struct BillingPortalArgs {
104 pub actor: User,
105 pub workspace: String,
106 pub return_url: String,
107}
108
109/// `admin_billing_link`: for staff to send a customer: their Stripe billing
110/// page. Returns `Outcome<BillingLink>`.
111#[derive(Debug, Serialize, Deserialize)]
112pub struct AdminBillingLinkArgs {
113 pub workspace: String,
114 pub by: String,
115}
116
117#[derive(Clone, Debug, Serialize, Deserialize)]
118#[serde(rename_all = "camelCase")]
119pub struct BillingLink {
120 /// A one-time session on Stripe's billing page, signed in already.
121 pub portal_url: String,
122 /// The billing page's sign-in page, which does not expire: the
123 /// customer signs in with the email Stripe has for them.
124 pub login_url: Option<String>,
125 pub customer_email: Option<String>,
126 pub expires_note: String,
127}
128
129#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
130#[serde(rename_all = "snake_case")]
131pub enum EntryKind {
132 /// Credit bought with a card.
133 TopUp,
134 /// An agent's run, or a paid feature's usage past its allowance.
135 Usage,
136}
137
138/// One line of a workspace's statement.
139#[derive(Clone, Debug, Serialize, Deserialize)]
140#[serde(rename_all = "camelCase")]
141pub struct LedgerEntry {
142 pub id: String,
143 pub kind: EntryKind,
144 /// Positive for credit added, negative for usage.
145 pub amount_micros: i64,
146 pub description: String,
147 /// For usage: the repository and pull request the agent worked on.
148 pub repo: Option<String>,
149 pub number: Option<u32>,
150 /// For usage: `implement`, `review` or `update`.
151 pub task: Option<String>,
152 /// For usage: the model, by its public name.
153 pub model: Option<String>,
154 /// For usage: `g1t` when g1t paid the model provider, `workspace` when
155 /// the workspace's own account did and only orchestration is charged.
156 #[serde(default = "g1t")]
157 pub billed_to: String,
158 /// For a top-up: the username of whoever paid.
159 pub created_by: Option<String>,
160 /// RFC 3339.
161 pub created_at: String,
162 /// The workspace the line belongs to, which tells an enterprise's
163 /// lines apart.
164 #[serde(default, skip_serializing_if = "Option::is_none")]
165 pub workspace: Option<String>,
166}
167
168fn g1t() -> String {
169 "g1t".to_owned()
170}
171
172/// `account` (`Outcome<Account>`) and `ledger` (`Outcome<Vec<LedgerEntry>>`,
173/// newest first). Members of the workspace only.
174#[derive(Debug, Serialize, Deserialize)]
175pub struct AccountArgs {
176 pub workspace: String,
177 pub viewer: Viewer,
178}
179
180/// `checkout`: starts a card payment for credit. Owners of the workspace
181/// only. Returns `Outcome<Checkout>`.
182#[derive(Debug, Serialize, Deserialize)]
183#[serde(rename_all = "camelCase")]
184pub struct CheckoutArgs {
185 pub actor: User,
186 pub workspace: String,
187 /// How much credit to buy, in cents.
188 pub amount_cents: u32,
189 /// Where the payment page sends the person afterwards. The payment's
190 /// id is appended as `session`.
191 pub return_url: String,
192}
193
194#[derive(Debug, Serialize, Deserialize)]
195pub struct Checkout {
196 /// The payment page to send the person to.
197 pub url: String,
198}
199
200/// `confirm`: credits a payment once the provider says it was made. Safe
201/// to call any number of times. Returns `Outcome<Account>`.
202#[derive(Debug, Serialize, Deserialize)]
203pub struct ConfirmArgs {
204 pub workspace: String,
205 pub viewer: Viewer,
206 /// The payment's id, as returned to `return_url`.
207 pub session: String,
208}
209
210/// `can_start`: whether a workspace may start an agent now, asked before
211/// anything is opened for it. Returns `Outcome<bool>`: a failure, with the
212/// reason to show, when it has no credit.
213#[derive(Debug, Serialize, Deserialize)]
214pub struct CanStartArgs {
215 pub workspace: String,
216}
217
218/// `start_run`: asks whether a workspace may start an agent, and opens the
219/// run it will be charged for. Called by the runner service. Returns
220/// `Outcome<Option<RunTicket>>`: no ticket when billing is off, a failure
221/// when the workspace has no credit.
222#[derive(Debug, Serialize, Deserialize)]
223pub struct StartRunArgs {
224 pub workspace: String,
225 pub repo: RepoPath,
226 pub number: u32,
227 /// `implement`, `review` or `update`.
228 pub task: String,
229 /// The model, by its public name.
230 pub model: String,
231 /// `workspace` when the run uses the workspace's own model provider.
232 /// The runner, which is TypeScript, sends it as `billedTo`.
233 #[serde(default = "g1t", alias = "billedTo")]
234 pub billed_to: String,
235 /// The model session's id, when its requests go through g1t's AI
236 /// Gateway: settling charges the run what the gateway priced them at.
237 #[serde(default)]
238 pub session: Option<String>,
239}
240
241#[derive(Clone, Debug, Serialize, Deserialize)]
242#[serde(rename_all = "camelCase")]
243pub struct RunTicket {
244 pub run_id: String,
245 /// Lets the sandbox, and nothing else, report what this run cost.
246 pub token: String,
247}
248
249/// `finish_run`: what a run cost, as its sandbox reports it. Charged once.
250/// Returns `Outcome<bool>`.
251#[derive(Debug, Serialize, Deserialize)]
252#[serde(rename_all = "camelCase")]
253pub struct FinishRunArgs {
254 pub run_id: String,
255 pub token: String,
256 /// What the model provider charged, in US dollars.
257 pub cost_usd: f64,
258 #[serde(default)]
259 pub turns: u32,
260}
261
262
263/// `usage`: what a workspace's agents cost over a period, broken down.
264/// Members only. Returns `Outcome<Usage>`.
265#[derive(Debug, Serialize, Deserialize)]
266pub struct UsageArgs {
267 pub workspace: String,
268 pub viewer: Viewer,
269 /// RFC 3339: the start of the period. The period runs to now.
270 pub since: String,
271}
272
273/// One slice of usage: what it was for, what it cost, how many runs.
274#[derive(Clone, Debug, Serialize, Deserialize)]
275#[serde(rename_all = "camelCase")]
276pub struct UsageSlice {
277 pub key: String,
278 pub micros: i64,
279 pub runs: u32,
280}
281
282/// What a workspace's agents cost over a period.
283#[derive(Clone, Debug, Serialize, Deserialize)]
284#[serde(rename_all = "camelCase")]
285pub struct Usage {
286 pub since: String,
287 /// Charged, including g1t's margin.
288 pub spent_micros: i64,
289 /// What g1t's model provider charged, before the margin.
290 pub cost_micros: i64,
291 /// What runs on the workspace's own provider cost there, as the harness
292 /// estimated it. Not charged by g1t.
293 pub provider_micros: i64,
294 /// What the runs used, at cost: g1t's models and the workspace's own
295 /// provider together, whatever was charged for them.
296 pub used_micros: i64,
297 /// g1t charges nothing for now. The slices then measure usage at cost,
298 /// since every charge is zero.
299 pub free: bool,
300 pub runs: u32,
301 /// Spend per day (`YYYY-MM-DD`) and task, as `day/task` keys.
302 pub by_day: Vec<UsageSlice>,
303 /// Per task: implement, review, revise, update, plan.
304 pub by_task: Vec<UsageSlice>,
305 /// Per repository, `namespace/name`.
306 pub by_repo: Vec<UsageSlice>,
307 /// The pull requests that cost most, as `namespace/name#number`.
308 pub by_pull: Vec<UsageSlice>,
309 /// Per model, by its public name.
310 pub by_model: Vec<UsageSlice>,
311 /// Credit bought in the period.
312 pub added_micros: i64,
313}
314
315/// A paid feature a workspace turns on with a monthly plan, the way
316/// Cloudflare's Workers for Platforms or Vercel's Pro are bought. Never
317/// free: `FREE_WHILE_BUILDING` and the free model allowance do not cover
318/// it.
319#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
320#[serde(rename_all = "snake_case")]
321pub enum Feature {
322 /// Previews per pull request and production on g1t.page.
323 Deployments,
324}
325
326impl Feature {
327 pub const ALL: [Feature; 1] = [Feature::Deployments];
328
329 pub fn as_str(self) -> &'static str {
330 match self {
331 Feature::Deployments => "deployments",
332 }
333 }
334
335 pub fn parse(name: &str) -> Option<Feature> {
336 Feature::ALL.into_iter().find(|feature| feature.as_str() == name)
337 }
338
339 pub fn title(self) -> &'static str {
340 match self {
341 Feature::Deployments => "Deployments",
342 }
343 }
344}
345
346/// What the Deployments plan includes each month; usage past it is charged
347/// at cost plus the margin. The billing service describes the plan with
348/// these and the deployments service meters against them.
349pub mod deployments_allowance {
350 /// Apps deployed at once: production and previews together.
351 pub const APPS: u32 = 10;
352 pub const REQUESTS: u64 = 1_000_000;
353 pub const CPU_MS: u64 = 3_000_000;
354 /// What Cloudflare charges g1t past that, in millionths of a dollar.
355 pub const MICROS_PER_APP_MONTH: i64 = 20_000;
356 pub const MICROS_PER_MILLION_REQUESTS: i64 = 300_000;
357 pub const MICROS_PER_MILLION_CPU_MS: i64 = 20_000;
358 /// What one second of a build's sandbox costs g1t (Cloudflare
359 /// Containers, standard-1: half a vCPU, 4 GiB, 8 GB disk), rounded up.
360 /// Builds are not in the allowance: each is charged at this plus the
361 /// margin.
362 pub const MICROS_PER_BUILD_SECOND: i64 = 21;
363}
364
365/// Sandbox time: every sandbox g1t starts for a workspace (agents,
366/// reviews, checks, the merge queue, workflow jobs) is metered by the
367/// second. Deploy builds are charged by the Deployments plan instead.
368pub mod sandbox_allowance {
369 /// Free each calendar month (UTC): 500 minutes.
370 pub const FREE_SECONDS: i64 = 30_000;
371 /// What one second costs g1t (Cloudflare Containers, standard-1),
372 /// rounded up. Recorded with every entry.
373 pub const COST_MICROS_PER_SECOND: i64 = super::deployments_allowance::MICROS_PER_BUILD_SECOND;
374 /// What one second past the free minutes is charged: $0.003 a minute.
375 pub const MICROS_PER_SECOND: i64 = 50;
376}
377
378/// `record_sandbox`: how long one sandbox ran for a workspace, reported by
379/// the runner when it stops. Recorded once per `reference`, with what it
380/// cost g1t; seconds past the month's free minutes are charged at
381/// `sandbox_allowance::MICROS_PER_SECOND`, unless `FREE_WHILE_BUILDING`.
382/// Returns `Outcome<bool>`: false if that reference was recorded before.
383#[derive(Debug, Serialize, Deserialize)]
384#[serde(rename_all = "camelCase")]
385pub struct RecordSandboxArgs {
386 pub workspace: String,
387 pub seconds: u32,
388 /// What ran, e.g. `Checks on acme/api#12`.
389 pub description: String,
390 /// `namespace/name`.
391 pub repo: Option<String>,
392 /// Unique to the run.
393 pub reference: String,
394}
395
396/// How much a workspace has earned g1t's trust with money, which sets how
397/// far its unpaid usage can go before its work stops.
398#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
399#[serde(rename_all = "snake_case")]
400pub enum Trust {
401 /// No live payment yet: only a little past the free allowances.
402 New,
403 /// Has paid g1t real money: the ceiling grows with what it has paid.
404 Paid,
405 /// A ceiling g1t set by hand, after talking to the workspace.
406 Reviewed,
407 /// g1t's own workspaces: no ceiling.
408 Internal,
409}
410
411#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
412#[serde(rename_all = "snake_case")]
413pub enum LimitState {
414 Ok,
415 /// Past 80% of the ceiling.
416 Warning,
417 /// At or past it: no new sandboxes, builds or app requests.
418 Stopped,
419}
420
421/// How far a workspace's unpaid usage has gone this month, and where its
422/// work stops: like Fly's or Cloudflare's limits for new accounts, so no
423/// one runs up costs g1t cannot collect. Usage counts at what it cost g1t
424/// or what it is charged, whichever is more, so it counts while g1t is
425/// free too.
426#[derive(Clone, Debug, Serialize, Deserialize)]
427#[serde(rename_all = "camelCase")]
428pub struct Limit {
429 pub workspace: String,
430 /// The account that pays, whose usage and payments the limit counts:
431 /// the workspace's own, or its enterprise's.
432 #[serde(default)]
433 pub account: String,
434 #[serde(default)]
435 pub account_name: String,
436 pub trust: Trust,
437 /// Usage this month (UTC) less what was paid this month.
438 pub exposure_micros: i64,
439 /// Where work stops: the lower of g1t's ceiling and the owner's own
440 /// spend limit. None for g1t's own workspaces.
441 pub ceiling_micros: Option<i64>,
442 /// The ceiling g1t sets from `trust`.
443 pub trust_ceiling_micros: Option<i64>,
444 /// The owner's own monthly limit, if they set one.
445 pub spend_limit_micros: Option<i64>,
446 pub state: LimitState,
447 /// What to tell people when work is stopped or close to it.
448 pub message: Option<String>,
449}
450
451/// `limit`: a workspace's limit, for its members. Returns `Outcome<Limit>`.
452#[derive(Debug, Serialize, Deserialize)]
453pub struct LimitArgs {
454 pub workspace: String,
455 pub viewer: Viewer,
456}
457
458/// `check_limit`: the same, for the services that enforce it. Returns
459/// `Outcome<Limit>`.
460#[derive(Debug, Serialize, Deserialize)]
461pub struct CheckLimitArgs {
462 pub workspace: String,
463}
464
465/// `note_pending`: usage this month that will be charged later, such as
466/// app traffic past a plan, so the workspace's limit counts it now. Each
467/// report replaces the last for that workspace, source and month. Called
468/// by the service that meters it. Returns `bool`.
469#[derive(Debug, Serialize, Deserialize)]
470#[serde(rename_all = "camelCase")]
471pub struct NotePendingArgs {
472 pub workspace: String,
473 /// `deployments`.
474 pub source: String,
475 /// What it cost g1t so far this month, before the margin.
476 pub cost_micros: i64,
477}
478
479/// `set_spend_limit`: the owner's own monthly ceiling, under g1t's; None
480/// removes it. Owners only. Returns `Outcome<Limit>`.
481#[derive(Debug, Serialize, Deserialize)]
482#[serde(rename_all = "camelCase")]
483pub struct SetSpendLimitArgs {
484 pub actor: User,
485 pub workspace: String,
486 pub spend_limit_micros: Option<i64>,
487}
488
489/// One metered unit: what it costs g1t, and what it is sold at. The price
490/// is always `cost × (100 + markup) / 100`, so it follows the cost.
491#[derive(Clone, Debug, Serialize, Deserialize)]
492#[serde(rename_all = "camelCase")]
493pub struct Price {
494 /// `sandbox_second`, `build_second`, `app_requests`, `app_cpu`, `app_month`.
495 pub meter: String,
496 pub title: String,
497 pub unit: String,
498 /// Millionths of a dollar per unit; may have a fraction.
499 pub cost_micros: f64,
500 pub markup_percent: u32,
501 pub price_micros: f64,
502 /// `list`: Cloudflare's published price. `cloudflare`: what Cloudflare
503 /// actually billed g1t, measured.
504 pub source: String,
505 /// When it was last checked against Cloudflare's bill.
506 pub checked_at: Option<String>,
507 pub updated_at: String,
508}
509
510impl Price {
511 pub fn price_for(cost_micros: f64, markup_percent: u32) -> f64 {
512 cost_micros * f64::from(100 + markup_percent) / 100.0
513 }
514}
515
516/// A cost that moved.
517#[derive(Clone, Debug, Serialize, Deserialize)]
518#[serde(rename_all = "camelCase")]
519pub struct PriceChange {
520 pub meter: String,
521 pub old_cost_micros: f64,
522 pub new_cost_micros: f64,
523 pub markup_percent: u32,
524 pub reason: String,
525 pub created_at: String,
526}
527
528/// `prices`: every metered price and the recent changes. Public. Returns
529/// `PriceBook`.
530#[derive(Clone, Debug, Serialize, Deserialize)]
531#[serde(rename_all = "camelCase")]
532pub struct PriceBook {
533 pub prices: Vec<Price>,
534 pub changes: Vec<PriceChange>,
535 /// The margin on model usage, which is charged at what AI Gateway
536 /// priced each request at.
537 pub model_margin_percent: u32,
538}
539
540/// Who pays: a billing account. Every workspace has one; by default its
541/// own. An enterprise account pays for several workspaces at once, as
542/// GitHub Enterprise does: one bill, one limit, one set of terms.
543#[derive(Clone, Debug, Serialize, Deserialize)]
544#[serde(rename_all = "camelCase")]
545pub struct BillingAccount {
546 /// `ws_<slug>` for a workspace's own account; `ent_…` for an enterprise.
547 pub id: String,
548 pub kind: AccountKind,
549 pub name: String,
550 pub terms: Terms,
551 /// The workspaces it pays for.
552 pub workspaces: Vec<String>,
553 pub created_at: String,
554}
555
556#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
557#[serde(rename_all = "snake_case")]
558pub enum AccountKind {
559 Workspace,
560 Enterprise,
561}
562
563/// How an account is charged. Standard unless g1t set otherwise in sudo.
564#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
565#[serde(rename_all = "camelCase")]
566pub struct Terms {
567 pub kind: TermsKind,
568 /// Off every usage charge, in percent. Custom terms only.
569 #[serde(default)]
570 pub discount_percent: u32,
571 /// A ceiling on unpaid usage that replaces the one trust would give.
572 #[serde(default)]
573 pub ceiling_micros: Option<i64>,
574 /// Why, for whoever looks next.
575 #[serde(default)]
576 pub note: String,
577 /// When the terms end and the account goes back to standard.
578 #[serde(default)]
579 pub until: Option<String>,
580 #[serde(default)]
581 pub set_by: Option<String>,
582 #[serde(default)]
583 pub set_at: Option<String>,
584}
585
586impl Terms {
587 pub fn standard() -> Self {
588 Terms {
589 kind: TermsKind::Standard,
590 discount_percent: 0,
591 ceiling_micros: None,
592 note: String::new(),
593 until: None,
594 set_by: None,
595 set_at: None,
596 }
597 }
598
599 /// What a charge becomes under these terms.
600 pub fn apply(&self, charge_micros: i64) -> i64 {
601 match self.kind {
602 TermsKind::Comped => 0,
603 TermsKind::Custom => charge_micros * i64::from(100 - self.discount_percent.min(100)) / 100,
604 TermsKind::Standard => charge_micros,
605 }
606 }
607}
608
609#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
610#[serde(rename_all = "snake_case")]
611pub enum TermsKind {
612 /// Prices as published, limits by trust.
613 Standard,
614 /// Nothing charged; usage still recorded with its cost. Paid features
615 /// are on without a plan. For g1t's own workspaces, partners, and the
616 /// like.
617 Comped,
618 /// A discount, a ceiling, or both.
619 Custom,
620}
621
622// --- Staff (sudo.g1t.sh) ------------------------------------------------------
623//
624// Called only by the sudo app, which only g1t staff can reach (behind
625// Cloudflare Access). Each change names who made it, and is kept in the
626// audit log.
627
628/// `admin_accounts`: every billing account, with where each stands this
629/// month. Returns `Vec<AccountSummary>`.
630#[derive(Debug, Default, Serialize, Deserialize)]
631pub struct AdminAccountsArgs {
632 #[serde(default)]
633 pub query: Option<String>,
634}
635
636#[derive(Clone, Debug, Serialize, Deserialize)]
637#[serde(rename_all = "camelCase")]
638pub struct AccountSummary {
639 pub account: BillingAccount,
640 pub limit: Limit,
641 /// Charged this month, after terms.
642 pub charged_micros: i64,
643 /// What this month's usage cost g1t.
644 pub cost_micros: i64,
645 /// Paid, ever.
646 pub paid_micros: i64,
647 /// The same figures for each of the account's workspaces that has
648 /// any, so staff can see what one member of an enterprise used.
649 #[serde(default)]
650 pub by_workspace: Vec<WorkspaceFigures>,
651}
652
653/// One workspace's share of an [`AccountSummary`].
654#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
655#[serde(rename_all = "camelCase")]
656pub struct WorkspaceFigures {
657 pub workspace: String,
658 pub charged_micros: i64,
659 pub cost_micros: i64,
660 pub paid_micros: i64,
661}
662
663/// `admin_account`: one account in full. Returns `Outcome<AccountDetail>`.
664#[derive(Debug, Serialize, Deserialize)]
665pub struct AdminAccountArgs {
666 /// An account id, or a workspace slug.
667 pub id: String,
668}
669
670#[derive(Clone, Debug, Serialize, Deserialize)]
671#[serde(rename_all = "camelCase")]
672pub struct AccountDetail {
673 pub summary: AccountSummary,
674 /// Each workspace's limit, for an enterprise.
675 pub workspaces: Vec<Limit>,
676 pub ledger: Vec<LedgerEntry>,
677 pub audit: Vec<AdminAction>,
678}
679
680/// `admin_set_terms`. Returns `Outcome<BillingAccount>`.
681#[derive(Debug, Serialize, Deserialize)]
682pub struct AdminSetTermsArgs {
683 pub id: String,
684 pub terms: Terms,
685 pub by: String,
686}
687
688/// `admin_create_enterprise`. Returns `Outcome<BillingAccount>`.
689#[derive(Debug, Serialize, Deserialize)]
690pub struct AdminCreateEnterpriseArgs {
691 pub name: String,
692 pub workspaces: Vec<String>,
693 pub by: String,
694}
695
696/// `admin_attach`: moves a workspace onto an enterprise account, or back
697/// onto its own with `account: None`. Returns `Outcome<BillingAccount>`.
698#[derive(Debug, Serialize, Deserialize)]
699pub struct AdminAttachArgs {
700 pub workspace: String,
701 pub account: Option<String>,
702 pub by: String,
703}
704
705/// `admin_credit`: money g1t gives a workspace, such as a refund or a
706/// goodwill credit. Returns `Outcome<LedgerEntry>`.
707#[derive(Debug, Serialize, Deserialize)]
708pub struct AdminCreditArgs {
709 pub workspace: String,
710 pub amount_micros: i64,
711 pub note: String,
712 pub by: String,
713}
714
715/// One change made in sudo.
716#[derive(Clone, Debug, Serialize, Deserialize)]
717#[serde(rename_all = "camelCase")]
718pub struct AdminAction {
719 pub id: String,
720 pub account: String,
721 pub action: String,
722 pub detail: String,
723 pub by: String,
724 pub created_at: String,
725}
726
727/// What a feature's plan costs and includes.
728#[derive(Clone, Debug, Serialize, Deserialize)]
729#[serde(rename_all = "camelCase")]
730pub struct Plan {
731 pub feature: Feature,
732 pub title: String,
733 /// Charged every month while the plan is on, in cents.
734 pub monthly_cents: u32,
735 /// What the monthly price includes, one line each, for people to read.
736 pub includes: Vec<String>,
737 /// How usage past the allowance is charged, for people to read.
738 pub overage: String,
739}
740
741#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
742#[serde(rename_all = "snake_case")]
743pub enum SubscriptionStatus {
744 /// Paid up; the feature works.
745 Active,
746 /// Paid up to the end of the period, and ends then.
747 Canceling,
748 /// The last payment failed; the feature is off until it is paid.
749 PastDue,
750 /// Ended.
751 Canceled,
752}
753
754impl SubscriptionStatus {
755 /// Whether the feature works in this state.
756 pub fn on(self) -> bool {
757 matches!(self, SubscriptionStatus::Active | SubscriptionStatus::Canceling)
758 }
759}
760
761/// A workspace's plan for one feature.
762#[derive(Clone, Debug, Serialize, Deserialize)]
763#[serde(rename_all = "camelCase")]
764pub struct Subscription {
765 pub feature: Feature,
766 pub status: SubscriptionStatus,
767 /// RFC 3339: when the period paid for ends, and the plan renews or
768 /// ends.
769 pub period_end: Option<String>,
770 /// Username of whoever turned it on.
771 pub started_by: String,
772 /// RFC 3339.
773 pub started_at: String,
774}
775
776/// A feature as a workspace sees it: what it costs, and its plan if it has
777/// one.
778#[derive(Clone, Debug, Serialize, Deserialize)]
779#[serde(rename_all = "camelCase")]
780pub struct FeatureState {
781 pub plan: Plan,
782 pub subscription: Option<Subscription>,
783 /// Whether the feature works for the workspace now.
784 pub on: bool,
785}
786
787/// `features`: every paid feature and the workspace's plan for each.
788/// Members only. Returns `Outcome<Vec<FeatureState>>`.
789#[derive(Debug, Serialize, Deserialize)]
790pub struct FeaturesArgs {
791 pub workspace: String,
792 pub viewer: Viewer,
793}
794
795/// `subscribe`: starts the card page for a feature's monthly plan. Owners
796/// only. Returns `Outcome<Checkout>`; the page's id comes back to
797/// `return_url` as `session`, for `confirm_subscription`.
798#[derive(Debug, Serialize, Deserialize)]
799#[serde(rename_all = "camelCase")]
800pub struct SubscribeArgs {
801 pub actor: User,
802 pub workspace: String,
803 pub feature: Feature,
804 pub return_url: String,
805}
806
807/// `confirm_subscription`: turns the feature on once the processor says
808/// the plan was paid for. Safe to call any number of times. Returns
809/// `Outcome<FeatureState>`.
810#[derive(Debug, Serialize, Deserialize)]
811pub struct ConfirmSubscriptionArgs {
812 pub workspace: String,
813 pub viewer: Viewer,
814 pub session: String,
815}
816
817/// `cancel_subscription` (`resume` false) ends a plan at the end of the
818/// period paid for; with `resume` true, takes that back. Owners only.
819/// Returns `Outcome<FeatureState>`.
820#[derive(Debug, Serialize, Deserialize)]
821pub struct CancelSubscriptionArgs {
822 pub actor: User,
823 pub workspace: String,
824 pub feature: Feature,
825 #[serde(default)]
826 pub resume: bool,
827}
828
829/// `has_feature`: whether a feature works for a workspace now, asked by the
830/// service that provides it before doing paid work. Returns
831/// `Outcome<bool>`: a failure, with the reason to show, when it does not.
832/// True everywhere when no card processor is configured.
833#[derive(Debug, Serialize, Deserialize)]
834pub struct HasFeatureArgs {
835 pub workspace: String,
836 pub feature: Feature,
837}
838
839/// `charge_feature`: usage of a feature past its plan's allowance, charged
840/// from the workspace's credit at cost plus the margin, whatever
841/// `FREE_WHILE_BUILDING` says. Called by the service that provides it.
842/// Charged once per `reference`. Returns `Outcome<bool>`: false if that
843/// reference was charged before.
844#[derive(Debug, Serialize, Deserialize)]
845#[serde(rename_all = "camelCase")]
846pub struct ChargeFeatureArgs {
847 pub workspace: String,
848 pub feature: Feature,
849 /// What it cost g1t, in millionths of a dollar, before the margin.
850 pub cost_micros: i64,
851 pub description: String,
852 /// `namespace/name`, when the usage was one repository's.
853 pub repo: Option<String>,
854 /// Unique to this charge, e.g. `deployments/acme/2026-10`.
855 pub reference: String,
856}
857
858#[cfg(test)]
859mod tests {
860 use super::*;
861
862 #[test]
863 fn features_are_named_as_the_site_sends_them() {
864 assert_eq!(
865 serde_json::to_value(Feature::Deployments).unwrap(),
866 serde_json::json!("deployments")
867 );
868 assert_eq!(Feature::parse("deployments"), Some(Feature::Deployments));
869 assert!(SubscriptionStatus::Canceling.on());
870 assert!(!SubscriptionStatus::PastDue.on());
871 }
872
873 #[test]
874 fn who_pays_is_read_as_the_runner_sends_it() {
875 let run: StartRunArgs = serde_json::from_value(serde_json::json!({
876 "workspace": "acme",
877 "repo": { "namespace": "acme", "name": "web" },
878 "number": 7,
879 "task": "implement",
880 "model": "Claude Sonnet 5.5",
881 "billedTo": "workspace",
882 }))
883 .unwrap();
884 assert_eq!(run.billed_to, "workspace");
885 }
886}