flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/crates/contracts/src/billing.rs

1,244 lines41,853 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 /// Has paid steadily for months, with nothing disputed or declined:
406 /// the ceiling follows its monthly spend, up to $10,000, by itself.
407 Established,
408 /// A ceiling g1t set by hand, after talking to the workspace.
409 Reviewed,
410 /// g1t's own workspaces: no ceiling.
411 Internal,
412}
413
414#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
415#[serde(rename_all = "snake_case")]
416pub enum LimitState {
417 Ok,
418 /// Past 80% of the ceiling.
419 Warning,
420 /// At or past it: no new sandboxes, builds or app requests.
421 Stopped,
422}
423
424/// How far a workspace's unpaid usage has gone this month, and where its
425/// work stops: like Fly's or Cloudflare's limits for new accounts, so no
426/// one runs up costs g1t cannot collect. Usage counts at what it cost g1t
427/// or what it is charged, whichever is more, so it counts while g1t is
428/// free too.
429#[derive(Clone, Debug, Serialize, Deserialize)]
430#[serde(rename_all = "camelCase")]
431pub struct Limit {
432 pub workspace: String,
433 /// The account that pays, whose usage and payments the limit counts:
434 /// the workspace's own, or its enterprise's.
435 #[serde(default)]
436 pub account: String,
437 #[serde(default)]
438 pub account_name: String,
439 pub trust: Trust,
440 /// Usage this month (UTC) less what was paid this month.
441 pub exposure_micros: i64,
442 /// Where work stops: the lower of g1t's ceiling and the owner's own
443 /// spend limit. None for g1t's own workspaces.
444 pub ceiling_micros: Option<i64>,
445 /// The ceiling g1t sets from `trust`.
446 pub trust_ceiling_micros: Option<i64>,
447 /// The owner's own monthly limit, if they set one.
448 pub spend_limit_micros: Option<i64>,
449 pub state: LimitState,
450 /// What to tell people when work is stopped or close to it.
451 pub message: Option<String>,
452 /// Charged this month, which the spend limit is measured against.
453 #[serde(default)]
454 pub spent_micros: i64,
455 /// True while the owners have not chosen a spend limit of their own, so
456 /// the automatic one applies: $200, or twice last month's spend.
457 #[serde(default)]
458 pub default_spend_limit: bool,
459 /// The most the owners may set their own limit to: g1t's ceiling. To
460 /// go past it, they contact g1t.
461 #[serde(default)]
462 pub available_micros: Option<i64>,
463 /// How the ceiling grows from here, in a sentence.
464 #[serde(default)]
465 pub growth: Option<String>,
466}
467
468/// `limit`: a workspace's limit, for its members. Returns `Outcome<Limit>`.
469#[derive(Debug, Serialize, Deserialize)]
470pub struct LimitArgs {
471 pub workspace: String,
472 pub viewer: Viewer,
473}
474
475/// `check_limit`: the same, for the services that enforce it. Returns
476/// `Outcome<Limit>`.
477#[derive(Debug, Serialize, Deserialize)]
478pub struct CheckLimitArgs {
479 pub workspace: String,
480}
481
482/// `note_pending`: usage this month that will be charged later, such as
483/// app traffic past a plan, so the workspace's limit counts it now. Each
484/// report replaces the last for that workspace, source and month. Called
485/// by the service that meters it. Returns `bool`.
486#[derive(Debug, Serialize, Deserialize)]
487#[serde(rename_all = "camelCase")]
488pub struct NotePendingArgs {
489 pub workspace: String,
490 /// `deployments`.
491 pub source: String,
492 /// What it cost g1t so far this month, before the margin.
493 pub cost_micros: i64,
494}
495
496/// `set_spend_limit`: the owner's own monthly ceiling, under g1t's; None
497/// removes it. Owners only. Returns `Outcome<Limit>`.
498#[derive(Debug, Serialize, Deserialize)]
499#[serde(rename_all = "camelCase")]
500pub struct SetSpendLimitArgs {
501 pub actor: User,
502 pub workspace: String,
503 /// A monthly limit, at most what is available; None goes back to the
504 /// default.
505 pub spend_limit_micros: Option<i64>,
506 /// Use everything available, with no limit of their own.
507 #[serde(default)]
508 pub use_full_limit: bool,
509}
510
511/// One metered unit: what it costs g1t, and what it is sold at. The price
512/// is always `cost × (100 + markup) / 100`, so it follows the cost.
513#[derive(Clone, Debug, Serialize, Deserialize)]
514#[serde(rename_all = "camelCase")]
515pub struct Price {
516 /// `sandbox_second`, `build_second`, `app_requests`, `app_cpu`, `app_month`.
517 pub meter: String,
518 pub title: String,
519 pub unit: String,
520 /// Millionths of a dollar per unit; may have a fraction.
521 pub cost_micros: f64,
522 pub markup_percent: u32,
523 pub price_micros: f64,
524 /// `list`: Cloudflare's published price. `cloudflare`: what Cloudflare
525 /// actually billed g1t, measured.
526 pub source: String,
527 /// When it was last checked against Cloudflare's bill.
528 pub checked_at: Option<String>,
529 pub updated_at: String,
530}
531
532impl Price {
533 pub fn price_for(cost_micros: f64, markup_percent: u32) -> f64 {
534 cost_micros * f64::from(100 + markup_percent) / 100.0
535 }
536}
537
538/// A cost that moved.
539#[derive(Clone, Debug, Serialize, Deserialize)]
540#[serde(rename_all = "camelCase")]
541pub struct PriceChange {
542 pub meter: String,
543 pub old_cost_micros: f64,
544 pub new_cost_micros: f64,
545 pub markup_percent: u32,
546 pub reason: String,
547 pub created_at: String,
548}
549
550/// `prices`: every metered price and the recent changes. Public. Returns
551/// `PriceBook`.
552#[derive(Clone, Debug, Serialize, Deserialize)]
553#[serde(rename_all = "camelCase")]
554pub struct PriceBook {
555 pub prices: Vec<Price>,
556 pub changes: Vec<PriceChange>,
557 /// The margin on model usage, which is charged at what AI Gateway
558 /// priced each request at.
559 pub model_margin_percent: u32,
560}
561
562/// Who pays: a billing account. Every workspace has one; by default its
563/// own. An enterprise account pays for several workspaces at once, as
564/// GitHub Enterprise does: one bill, one limit, one set of terms.
565#[derive(Clone, Debug, Serialize, Deserialize)]
566#[serde(rename_all = "camelCase")]
567pub struct BillingAccount {
568 /// `ws_<slug>` for a workspace's own account; `ent_…` for an enterprise.
569 pub id: String,
570 pub kind: AccountKind,
571 pub name: String,
572 pub terms: Terms,
573 /// The workspaces it pays for.
574 pub workspaces: Vec<String>,
575 /// Where an enterprise's invoices go.
576 #[serde(default)]
577 pub billing_email: Option<String>,
578 /// An enterprise's invoices, newest first. Empty for a workspace's own.
579 #[serde(default)]
580 pub invoices: Vec<EnterpriseInvoice>,
581 pub created_at: String,
582}
583
584#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
585#[serde(rename_all = "snake_case")]
586pub enum AccountKind {
587 Workspace,
588 Enterprise,
589}
590
591/// How an account is charged. Standard unless g1t set otherwise in sudo.
592#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
593#[serde(rename_all = "camelCase")]
594pub struct Terms {
595 pub kind: TermsKind,
596 /// Off every usage charge, in percent. Custom terms only.
597 #[serde(default)]
598 pub discount_percent: u32,
599 /// A ceiling on unpaid usage that replaces the one trust would give.
600 #[serde(default)]
601 pub ceiling_micros: Option<i64>,
602 /// Why, for whoever looks next.
603 #[serde(default)]
604 pub note: String,
605 /// When the terms end and the account goes back to standard.
606 #[serde(default)]
607 pub until: Option<String>,
608 #[serde(default)]
609 pub set_by: Option<String>,
610 #[serde(default)]
611 pub set_at: Option<String>,
612}
613
614impl Terms {
615 pub fn standard() -> Self {
616 Terms {
617 kind: TermsKind::Standard,
618 discount_percent: 0,
619 ceiling_micros: None,
620 note: String::new(),
621 until: None,
622 set_by: None,
623 set_at: None,
624 }
625 }
626
627 /// What a charge becomes under these terms.
628 pub fn apply(&self, charge_micros: i64) -> i64 {
629 match self.kind {
630 TermsKind::Comped => 0,
631 TermsKind::Custom => charge_micros * i64::from(100 - self.discount_percent.min(100)) / 100,
632 TermsKind::Standard => charge_micros,
633 }
634 }
635}
636
637#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
638#[serde(rename_all = "snake_case")]
639pub enum TermsKind {
640 /// Prices as published, limits by trust.
641 Standard,
642 /// Nothing charged; usage still recorded with its cost. Paid features
643 /// are on without a plan. For g1t's own workspaces, partners, and the
644 /// like.
645 Comped,
646 /// A discount, a ceiling, or both.
647 Custom,
648}
649
650/// `stripe_webhook`: an event from Stripe, as the API received it: the raw
651/// body and its `Stripe-Signature` header. Billing checks the signature
652/// against the secret of the endpoint it registered, and handles each
653/// event once. Returns `Outcome<bool>`: false for one already handled.
654#[derive(Debug, Serialize, Deserialize)]
655pub struct StripeWebhookArgs {
656 pub payload: String,
657 pub signature: String,
658}
659
660/// `admin_stripe`: where billing stands with Stripe. Staff only. Returns
661/// `StripeStatus`. With `setup: true`, registers (or replaces) the webhook
662/// endpoint for the current mode first.
663#[derive(Debug, Default, Serialize, Deserialize)]
664pub struct AdminStripeArgs {
665 #[serde(default)]
666 pub setup: bool,
667 #[serde(default)]
668 pub by: Option<String>,
669}
670
671#[derive(Clone, Debug, Serialize, Deserialize)]
672#[serde(rename_all = "camelCase")]
673pub struct StripeStatus {
674 /// `test` or `live`, from the key; `off` without one.
675 pub mode: String,
676 pub webhook: Option<StripeWebhook>,
677 /// The latest events handled, newest first.
678 pub recent_events: Vec<StripeEventSummary>,
679 /// What went wrong setting up, if it did.
680 pub error: Option<String>,
681}
682
683#[derive(Clone, Debug, Serialize, Deserialize)]
684#[serde(rename_all = "camelCase")]
685pub struct StripeWebhook {
686 pub url: String,
687 pub endpoint_id: String,
688 pub events: Vec<String>,
689 pub created_by: String,
690 pub created_at: String,
691}
692
693#[derive(Clone, Debug, Serialize, Deserialize)]
694#[serde(rename_all = "camelCase")]
695pub struct StripeEventSummary {
696 pub id: String,
697 pub kind: String,
698 pub outcome: String,
699 pub received_at: String,
700}
701
702/// `admin_enterprise_billing`: where an enterprise's invoices go. Creates
703/// or updates its Stripe customer. Returns `Outcome<BillingAccount>`.
704#[derive(Debug, Serialize, Deserialize)]
705pub struct AdminEnterpriseBillingArgs {
706 pub id: String,
707 pub email: String,
708 pub by: String,
709}
710
711/// `admin_invoice_enterprise`: sends an enterprise its invoice now, for
712/// what its workspaces owe, rather than waiting for the month to close.
713/// Returns `Outcome<EnterpriseInvoice>`.
714#[derive(Debug, Serialize, Deserialize)]
715pub struct AdminInvoiceEnterpriseArgs {
716 pub id: String,
717 pub by: String,
718}
719
720/// An enterprise's invoice: one line per workspace, paid on Stripe.
721#[derive(Clone, Debug, Serialize, Deserialize)]
722#[serde(rename_all = "camelCase")]
723pub struct EnterpriseInvoice {
724 pub invoice_id: String,
725 /// Stripe's page for it, where it is paid.
726 pub hosted_url: Option<String>,
727 pub amount_micros: i64,
728 /// `open`, `paid`, `overdue` or `void`.
729 pub status: String,
730 pub period: String,
731 pub lines: Vec<InvoiceLine>,
732 pub created_at: String,
733}
734
735#[derive(Clone, Debug, Serialize, Deserialize)]
736#[serde(rename_all = "camelCase")]
737pub struct InvoiceLine {
738 pub workspace: String,
739 pub amount_micros: i64,
740}
741
742/// A workspace's invoice from g1t: one per month, and one each time it is
743/// charged near its limit. Itemised, charged to the card on file, and kept
744/// in Stripe's billing page with its PDF.
745#[derive(Clone, Debug, Serialize, Deserialize)]
746#[serde(rename_all = "camelCase")]
747pub struct WorkspaceInvoice {
748 pub invoice_id: String,
749 pub workspace: String,
750 /// `month` (2026-10) or `threshold`.
751 pub reason: String,
752 pub period: String,
753 pub amount_micros: i64,
754 /// `paid`, `open`, `failed` or `void`.
755 pub status: String,
756 pub hosted_url: Option<String>,
757 pub pdf_url: Option<String>,
758 pub lines: Vec<InvoiceItem>,
759 pub created_at: String,
760}
761
762#[derive(Clone, Debug, Serialize, Deserialize)]
763#[serde(rename_all = "camelCase")]
764pub struct InvoiceItem {
765 pub description: String,
766 pub amount_micros: i64,
767}
768
769/// `invoices`: a workspace's invoices from g1t, newest first. Members
770/// only. Returns `Outcome<Vec<WorkspaceInvoice>>`.
771#[derive(Debug, Serialize, Deserialize)]
772pub struct InvoicesArgs {
773 pub workspace: String,
774 pub viewer: Viewer,
775}
776
777/// `admin_workspace_invoices`: the same, for staff. Returns
778/// `Vec<WorkspaceInvoice>`.
779#[derive(Debug, Serialize, Deserialize)]
780pub struct AdminWorkspaceInvoicesArgs {
781 pub workspace: String,
782}
783
784// --- Sales (sudo.g1t.sh) ------------------------------------------------------
785//
786// What staff need to know to reach out: who is growing, who is close to
787// their limit, who was declined, who has become a steady customer. And what
788// was done about it: a stage, an owner on g1t's side, a next step, notes.
789
790/// Why a workspace is worth a look.
791#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
792#[serde(rename_all = "snake_case")]
793pub enum SignalKind {
794 /// At its limit, or its own spend limit: work is stopped.
795 AtLimit,
796 /// Past 80% of what is available to it: about to need more.
797 NearCeiling,
798 /// Its card was declined or a payment disputed.
799 Declined,
800 /// This month is well ahead of last month.
801 Growing,
802 /// Became Established: the ceiling now follows its spend.
803 Established,
804 /// Paid g1t for the first time.
805 FirstPayment,
806 /// Spending enough that custom terms or an enterprise may suit it.
807 HighSpend,
808}
809
810#[derive(Clone, Debug, Serialize, Deserialize)]
811#[serde(rename_all = "camelCase")]
812pub struct Signal {
813 pub workspace: String,
814 pub kind: SignalKind,
815 /// One sentence, with the figures.
816 pub detail: String,
817 /// The figure that matters, such as this month's spend.
818 pub value_micros: i64,
819 /// Its sales stage, if staff gave it one.
820 pub stage: Option<String>,
821 pub owner: Option<String>,
822 #[serde(default)]
823 pub next_step: Option<String>,
824 /// When the next step is due, `YYYY-MM-DD`.
825 #[serde(default)]
826 pub next_at: Option<String>,
827}
828
829/// `admin_invoices`: every invoice g1t has sent, workspaces' and
830/// enterprises', newest first. Returns `Vec<InvoiceSummary>`.
831#[derive(Debug, Default, Serialize, Deserialize)]
832pub struct AdminInvoicesArgs {
833 /// `paid`, `open`, `failed`, `overdue` or `void`.
834 #[serde(default)]
835 pub status: Option<String>,
836 /// YYYY-MM, by when it was sent.
837 #[serde(default)]
838 pub month: Option<String>,
839}
840
841#[derive(Clone, Debug, Serialize, Deserialize)]
842#[serde(rename_all = "camelCase")]
843pub struct InvoiceSummary {
844 pub invoice_id: String,
845 /// `workspace` or `enterprise`.
846 pub kind: String,
847 /// The workspace's slug, or the enterprise's account id.
848 pub account: String,
849 /// What to call it: the workspace, or the enterprise's name.
850 pub name: String,
851 pub reason: String,
852 pub period: String,
853 pub amount_micros: i64,
854 pub status: String,
855 pub hosted_url: Option<String>,
856 pub created_at: String,
857 pub paid_at: Option<String>,
858}
859
860/// `admin_audit`: every change made in sudo, and by Stripe, newest first.
861/// Returns `Vec<AdminAction>`.
862#[derive(Debug, Default, Serialize, Deserialize)]
863pub struct AdminAuditArgs {
864 #[serde(default)]
865 pub by: Option<String>,
866 #[serde(default)]
867 pub action: Option<String>,
868 /// Only those before this time, for paging.
869 #[serde(default)]
870 pub before: Option<String>,
871}
872
873/// `admin_signals`: every workspace worth reaching out to, most urgent
874/// first. Returns `Vec<Signal>`.
875#[derive(Debug, Default, Serialize, Deserialize)]
876pub struct AdminSignalsArgs {}
877
878/// What staff are doing about a workspace.
879#[derive(Clone, Debug, Serialize, Deserialize)]
880#[serde(rename_all = "camelCase")]
881pub struct SalesRecord {
882 pub workspace: String,
883 /// `none`, `lead`, `contacted`, `negotiating`, `won`, `lost` or `churn_risk`.
884 pub stage: String,
885 /// The staff member looking after it.
886 pub owner: Option<String>,
887 pub next_step: Option<String>,
888 /// RFC 3339 date.
889 pub next_at: Option<String>,
890 pub notes: Vec<SalesNote>,
891 pub updated_at: Option<String>,
892}
893
894#[derive(Clone, Debug, Serialize, Deserialize)]
895#[serde(rename_all = "camelCase")]
896pub struct SalesNote {
897 pub id: String,
898 pub text: String,
899 pub by: String,
900 pub created_at: String,
901}
902
903/// `admin_sales`: a workspace's sales record. Returns `SalesRecord`.
904#[derive(Debug, Serialize, Deserialize)]
905pub struct AdminSalesArgs {
906 pub workspace: String,
907}
908
909/// `admin_set_sales`: its stage, owner and next step. Returns `Outcome<SalesRecord>`.
910#[derive(Debug, Serialize, Deserialize)]
911pub struct AdminSetSalesArgs {
912 pub workspace: String,
913 pub stage: String,
914 #[serde(default)]
915 pub owner: Option<String>,
916 #[serde(default)]
917 pub next_step: Option<String>,
918 #[serde(default)]
919 pub next_at: Option<String>,
920 pub by: String,
921}
922
923/// `admin_add_note`. Returns `Outcome<SalesRecord>`.
924#[derive(Debug, Serialize, Deserialize)]
925pub struct AdminAddNoteArgs {
926 pub workspace: String,
927 pub text: String,
928 pub by: String,
929}
930
931/// `admin_overview`: the business at a glance. Returns `Overview`.
932#[derive(Debug, Default, Serialize, Deserialize)]
933pub struct AdminOverviewArgs {}
934
935#[derive(Clone, Debug, Serialize, Deserialize)]
936#[serde(rename_all = "camelCase")]
937pub struct Overview {
938 /// YYYY-MM.
939 pub month: String,
940 /// The last six months, oldest first, all workspaces together.
941 pub months: Vec<MonthFigures>,
942 /// This month by kind of usage: models, sandbox, deployments, plans.
943 pub by_kind: Vec<KindFigures>,
944 pub paying_workspaces: u32,
945 pub stopped: u32,
946 pub near_ceiling: u32,
947 pub declined: u32,
948 /// Sent and not yet paid, workspaces and enterprises.
949 pub open_invoices_micros: i64,
950 /// Follow-ups due today or earlier.
951 pub follow_ups_due: u32,
952}
953
954#[derive(Clone, Debug, Serialize, Deserialize)]
955#[serde(rename_all = "camelCase")]
956pub struct KindFigures {
957 pub kind: String,
958 pub charged_micros: i64,
959 pub cost_micros: i64,
960}
961
962// --- Staff (sudo.g1t.sh) ------------------------------------------------------
963//
964// Called only by the sudo app, which only g1t staff can reach (behind
965// Cloudflare Access). Each change names who made it, and is kept in the
966// audit log.
967
968/// `admin_accounts`: every billing account, with where each stands this
969/// month. Returns `Vec<AccountSummary>`.
970#[derive(Debug, Default, Serialize, Deserialize)]
971pub struct AdminAccountsArgs {
972 #[serde(default)]
973 pub query: Option<String>,
974 /// Exactly these workspaces' accounts, such as one page of sudo's
975 /// list; every account with activity when absent.
976 #[serde(default)]
977 pub workspaces: Option<Vec<String>>,
978}
979
980#[derive(Clone, Debug, Serialize, Deserialize)]
981#[serde(rename_all = "camelCase")]
982pub struct AccountSummary {
983 pub account: BillingAccount,
984 pub limit: Limit,
985 /// Charged this month, after terms.
986 pub charged_micros: i64,
987 /// What this month's usage cost g1t.
988 pub cost_micros: i64,
989 /// Paid, ever.
990 pub paid_micros: i64,
991 /// The same figures for each of the account's workspaces that has
992 /// any, so staff can see what one member of an enterprise used.
993 #[serde(default)]
994 pub by_workspace: Vec<WorkspaceFigures>,
995 /// The last six months, oldest first, for trends.
996 #[serde(default)]
997 pub months: Vec<MonthFigures>,
998}
999
1000/// One month of an account's billing.
1001#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
1002#[serde(rename_all = "camelCase")]
1003pub struct MonthFigures {
1004 /// YYYY-MM.
1005 pub month: String,
1006 pub charged_micros: i64,
1007 pub cost_micros: i64,
1008 pub paid_micros: i64,
1009}
1010
1011/// One workspace's share of an [`AccountSummary`].
1012#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
1013#[serde(rename_all = "camelCase")]
1014pub struct WorkspaceFigures {
1015 pub workspace: String,
1016 pub charged_micros: i64,
1017 pub cost_micros: i64,
1018 pub paid_micros: i64,
1019}
1020
1021/// `admin_account`: one account in full. Returns `Outcome<AccountDetail>`.
1022#[derive(Debug, Serialize, Deserialize)]
1023pub struct AdminAccountArgs {
1024 /// An account id, or a workspace slug.
1025 pub id: String,
1026}
1027
1028#[derive(Clone, Debug, Serialize, Deserialize)]
1029#[serde(rename_all = "camelCase")]
1030pub struct AccountDetail {
1031 pub summary: AccountSummary,
1032 /// Each workspace's limit, for an enterprise.
1033 pub workspaces: Vec<Limit>,
1034 pub ledger: Vec<LedgerEntry>,
1035 pub audit: Vec<AdminAction>,
1036}
1037
1038/// `admin_set_terms`. Returns `Outcome<BillingAccount>`.
1039#[derive(Debug, Serialize, Deserialize)]
1040pub struct AdminSetTermsArgs {
1041 pub id: String,
1042 pub terms: Terms,
1043 pub by: String,
1044}
1045
1046/// `admin_create_enterprise`. Returns `Outcome<BillingAccount>`.
1047#[derive(Debug, Serialize, Deserialize)]
1048pub struct AdminCreateEnterpriseArgs {
1049 pub name: String,
1050 pub workspaces: Vec<String>,
1051 pub by: String,
1052}
1053
1054/// `admin_attach`: moves a workspace onto an enterprise account, or back
1055/// onto its own with `account: None`. Returns `Outcome<BillingAccount>`.
1056#[derive(Debug, Serialize, Deserialize)]
1057pub struct AdminAttachArgs {
1058 pub workspace: String,
1059 pub account: Option<String>,
1060 pub by: String,
1061}
1062
1063/// `admin_credit`: money g1t gives a workspace, such as a refund or a
1064/// goodwill credit. Returns `Outcome<LedgerEntry>`.
1065#[derive(Debug, Serialize, Deserialize)]
1066pub struct AdminCreditArgs {
1067 pub workspace: String,
1068 pub amount_micros: i64,
1069 pub note: String,
1070 pub by: String,
1071}
1072
1073/// One change made in sudo.
1074#[derive(Clone, Debug, Serialize, Deserialize)]
1075#[serde(rename_all = "camelCase")]
1076pub struct AdminAction {
1077 pub id: String,
1078 pub account: String,
1079 pub action: String,
1080 pub detail: String,
1081 pub by: String,
1082 pub created_at: String,
1083}
1084
1085/// What a feature's plan costs and includes.
1086#[derive(Clone, Debug, Serialize, Deserialize)]
1087#[serde(rename_all = "camelCase")]
1088pub struct Plan {
1089 pub feature: Feature,
1090 pub title: String,
1091 /// Charged every month while the plan is on, in cents.
1092 pub monthly_cents: u32,
1093 /// What the monthly price includes, one line each, for people to read.
1094 pub includes: Vec<String>,
1095 /// How usage past the allowance is charged, for people to read.
1096 pub overage: String,
1097}
1098
1099#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1100#[serde(rename_all = "snake_case")]
1101pub enum SubscriptionStatus {
1102 /// Paid up; the feature works.
1103 Active,
1104 /// Paid up to the end of the period, and ends then.
1105 Canceling,
1106 /// The last payment failed; the feature is off until it is paid.
1107 PastDue,
1108 /// Ended.
1109 Canceled,
1110}
1111
1112impl SubscriptionStatus {
1113 /// Whether the feature works in this state.
1114 pub fn on(self) -> bool {
1115 matches!(self, SubscriptionStatus::Active | SubscriptionStatus::Canceling)
1116 }
1117}
1118
1119/// A workspace's plan for one feature.
1120#[derive(Clone, Debug, Serialize, Deserialize)]
1121#[serde(rename_all = "camelCase")]
1122pub struct Subscription {
1123 pub feature: Feature,
1124 pub status: SubscriptionStatus,
1125 /// RFC 3339: when the period paid for ends, and the plan renews or
1126 /// ends.
1127 pub period_end: Option<String>,
1128 /// Username of whoever turned it on.
1129 pub started_by: String,
1130 /// RFC 3339.
1131 pub started_at: String,
1132}
1133
1134/// A feature as a workspace sees it: what it costs, and its plan if it has
1135/// one.
1136#[derive(Clone, Debug, Serialize, Deserialize)]
1137#[serde(rename_all = "camelCase")]
1138pub struct FeatureState {
1139 pub plan: Plan,
1140 pub subscription: Option<Subscription>,
1141 /// Whether the feature works for the workspace now.
1142 pub on: bool,
1143}
1144
1145/// `features`: every paid feature and the workspace's plan for each.
1146/// Members only. Returns `Outcome<Vec<FeatureState>>`.
1147#[derive(Debug, Serialize, Deserialize)]
1148pub struct FeaturesArgs {
1149 pub workspace: String,
1150 pub viewer: Viewer,
1151}
1152
1153/// `subscribe`: starts the card page for a feature's monthly plan. Owners
1154/// only. Returns `Outcome<Checkout>`; the page's id comes back to
1155/// `return_url` as `session`, for `confirm_subscription`.
1156#[derive(Debug, Serialize, Deserialize)]
1157#[serde(rename_all = "camelCase")]
1158pub struct SubscribeArgs {
1159 pub actor: User,
1160 pub workspace: String,
1161 pub feature: Feature,
1162 pub return_url: String,
1163}
1164
1165/// `confirm_subscription`: turns the feature on once the processor says
1166/// the plan was paid for. Safe to call any number of times. Returns
1167/// `Outcome<FeatureState>`.
1168#[derive(Debug, Serialize, Deserialize)]
1169pub struct ConfirmSubscriptionArgs {
1170 pub workspace: String,
1171 pub viewer: Viewer,
1172 pub session: String,
1173}
1174
1175/// `cancel_subscription` (`resume` false) ends a plan at the end of the
1176/// period paid for; with `resume` true, takes that back. Owners only.
1177/// Returns `Outcome<FeatureState>`.
1178#[derive(Debug, Serialize, Deserialize)]
1179pub struct CancelSubscriptionArgs {
1180 pub actor: User,
1181 pub workspace: String,
1182 pub feature: Feature,
1183 #[serde(default)]
1184 pub resume: bool,
1185}
1186
1187/// `has_feature`: whether a feature works for a workspace now, asked by the
1188/// service that provides it before doing paid work. Returns
1189/// `Outcome<bool>`: a failure, with the reason to show, when it does not.
1190/// True everywhere when no card processor is configured.
1191#[derive(Debug, Serialize, Deserialize)]
1192pub struct HasFeatureArgs {
1193 pub workspace: String,
1194 pub feature: Feature,
1195}
1196
1197/// `charge_feature`: usage of a feature past its plan's allowance, charged
1198/// from the workspace's credit at cost plus the margin, whatever
1199/// `FREE_WHILE_BUILDING` says. Called by the service that provides it.
1200/// Charged once per `reference`. Returns `Outcome<bool>`: false if that
1201/// reference was charged before.
1202#[derive(Debug, Serialize, Deserialize)]
1203#[serde(rename_all = "camelCase")]
1204pub struct ChargeFeatureArgs {
1205 pub workspace: String,
1206 pub feature: Feature,
1207 /// What it cost g1t, in millionths of a dollar, before the margin.
1208 pub cost_micros: i64,
1209 pub description: String,
1210 /// `namespace/name`, when the usage was one repository's.
1211 pub repo: Option<String>,
1212 /// Unique to this charge, e.g. `deployments/acme/2026-10`.
1213 pub reference: String,
1214}
1215
1216#[cfg(test)]
1217mod tests {
1218 use super::*;
1219
1220 #[test]
1221 fn features_are_named_as_the_site_sends_them() {
1222 assert_eq!(
1223 serde_json::to_value(Feature::Deployments).unwrap(),
1224 serde_json::json!("deployments")
1225 );
1226 assert_eq!(Feature::parse("deployments"), Some(Feature::Deployments));
1227 assert!(SubscriptionStatus::Canceling.on());
1228 assert!(!SubscriptionStatus::PastDue.on());
1229 }
1230
1231 #[test]
1232 fn who_pays_is_read_as_the_runner_sends_it() {
1233 let run: StartRunArgs = serde_json::from_value(serde_json::json!({
1234 "workspace": "acme",
1235 "repo": { "namespace": "acme", "name": "web" },
1236 "number": 7,
1237 "task": "implement",
1238 "model": "Claude Sonnet 5.5",
1239 "billedTo": "workspace",
1240 }))
1241 .unwrap();
1242 assert_eq!(run.billed_to, "workspace");
1243 }
1244}