pr_01m47d15m3e54sn21z27rpy5n9/crates/contracts/src/billing.rs

1,195 lines40,311 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Agents as a team: lifecycle, merge queue, billing and a new shell1//! 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,
Free while g1t is being built out; agents can check out their own forks30 /// 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,
Agents as a team: lifecycle, merge queue, billing and a new shell35}
36
A free allowance on g1t's models, so anyone can try its agents37/// `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
Agents as a team: lifecycle, merge queue, billing and a new shell66/// 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,
Integrations: your own model provider, alerts that open issues, tickets agents read77 /// 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,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace80 /// 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>,
Agents as a team: lifecycle, merge queue, billing and a new shell84}
85
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace86/// 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
Agents as a team: lifecycle, merge queue, billing and a new shell129#[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,
Paid features: a workspace turns on Deployments with a monthly plan134 /// An agent's run, or a paid feature's usage past its allowance.
Agents as a team: lifecycle, merge queue, billing and a new shell135 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>,
Integrations: your own model provider, alerts that open issues, tickets agents read154 /// 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,
Agents as a team: lifecycle, merge queue, billing and a new shell158 /// For a top-up: the username of whoever paid.
159 pub created_by: Option<String>,
160 /// RFC 3339.
161 pub created_at: String,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace162 /// 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>,
Agents as a team: lifecycle, merge queue, billing and a new shell166}
167
Integrations: your own model provider, alerts that open issues, tickets agents read168fn g1t() -> String {
169 "g1t".to_owned()
170}
171
Agents as a team: lifecycle, merge queue, billing and a new shell172/// `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,
Integrations: your own model provider, alerts that open issues, tickets agents read231 /// `workspace` when the run uses the workspace's own model provider.
Models per workspace: several providers, routed by kind of work232 /// The runner, which is TypeScript, sends it as `billedTo`.
233 #[serde(default = "g1t", alias = "billedTo")]
Integrations: your own model provider, alerts that open issues, tickets agents read234 pub billed_to: String,
Prices keep themselves current with what g1t pays235 /// 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>,
Agents as a team: lifecycle, merge queue, billing and a new shell239}
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}
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request261
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,
Integrations: your own model provider, alerts that open issues, tickets agents read289 /// What g1t's model provider charged, before the margin.
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request290 pub cost_micros: i64,
Integrations: your own model provider, alerts that open issues, tickets agents read291 /// 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,
Usage while free is shown at cost; agents get rustfmt and clippy294 /// 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,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request300 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}
Models per workspace: several providers, routed by kind of work314
Paid features: a workspace turns on Deployments with a monthly plan315/// 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;
Deployments: a preview for every pull request, production on g1t.page358 /// 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;
Paid features: a workspace turns on Deployments with a monthly plan363}
364
Every sandbox is metered by the second365/// 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
Usage limits: unpaid usage can only go so far396/// 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,
Two limits, real invoices, trust that grows by itself, sales signals405 /// 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,
Usage limits: unpaid usage can only go so far408 /// 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,
Billing accounts, terms and enterprises; g1t is no longer free433 /// 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,
Usage limits: unpaid usage can only go so far439 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>,
Two limits, real invoices, trust that grows by itself, sales signals452 /// 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>,
Usage limits: unpaid usage can only go so far466}
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
Prices keep themselves current with what g1t pays482/// `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
Usage limits: unpaid usage can only go so far496/// `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,
Two limits, real invoices, trust that grows by itself, sales signals503 /// A monthly limit, at most what is available; None goes back to the
504 /// default.
Usage limits: unpaid usage can only go so far505 pub spend_limit_micros: Option<i64>,
Two limits, real invoices, trust that grows by itself, sales signals506 /// Use everything available, with no limit of their own.
507 #[serde(default)]
508 pub use_full_limit: bool,
Usage limits: unpaid usage can only go so far509}
510
Prices keep themselves current with what g1t pays511/// 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
Billing accounts, terms and enterprises; g1t is no longer free562/// 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>,
Stripe webhooks, enterprise invoices, and sudo for both575 /// 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>,
Billing accounts, terms and enterprises; g1t is no longer free581 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
Stripe webhooks, enterprise invoices, and sudo for both650/// `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
Two limits, real invoices, trust that grows by itself, sales signals742/// 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}
823
824/// `admin_signals`: every workspace worth reaching out to, most urgent
825/// first. Returns `Vec<Signal>`.
826#[derive(Debug, Default, Serialize, Deserialize)]
827pub struct AdminSignalsArgs {}
828
829/// What staff are doing about a workspace.
830#[derive(Clone, Debug, Serialize, Deserialize)]
831#[serde(rename_all = "camelCase")]
832pub struct SalesRecord {
833 pub workspace: String,
834 /// `none`, `lead`, `contacted`, `negotiating`, `won`, `lost` or `churn_risk`.
835 pub stage: String,
836 /// The staff member looking after it.
837 pub owner: Option<String>,
838 pub next_step: Option<String>,
839 /// RFC 3339 date.
840 pub next_at: Option<String>,
841 pub notes: Vec<SalesNote>,
842 pub updated_at: Option<String>,
843}
844
845#[derive(Clone, Debug, Serialize, Deserialize)]
846#[serde(rename_all = "camelCase")]
847pub struct SalesNote {
848 pub id: String,
849 pub text: String,
850 pub by: String,
851 pub created_at: String,
852}
853
854/// `admin_sales`: a workspace's sales record. Returns `SalesRecord`.
855#[derive(Debug, Serialize, Deserialize)]
856pub struct AdminSalesArgs {
857 pub workspace: String,
858}
859
860/// `admin_set_sales`: its stage, owner and next step. Returns `Outcome<SalesRecord>`.
861#[derive(Debug, Serialize, Deserialize)]
862pub struct AdminSetSalesArgs {
863 pub workspace: String,
864 pub stage: String,
865 #[serde(default)]
866 pub owner: Option<String>,
867 #[serde(default)]
868 pub next_step: Option<String>,
869 #[serde(default)]
870 pub next_at: Option<String>,
871 pub by: String,
872}
873
874/// `admin_add_note`. Returns `Outcome<SalesRecord>`.
875#[derive(Debug, Serialize, Deserialize)]
876pub struct AdminAddNoteArgs {
877 pub workspace: String,
878 pub text: String,
879 pub by: String,
880}
881
882/// `admin_overview`: the business at a glance. Returns `Overview`.
883#[derive(Debug, Default, Serialize, Deserialize)]
884pub struct AdminOverviewArgs {}
885
886#[derive(Clone, Debug, Serialize, Deserialize)]
887#[serde(rename_all = "camelCase")]
888pub struct Overview {
889 /// YYYY-MM.
890 pub month: String,
891 /// The last six months, oldest first, all workspaces together.
892 pub months: Vec<MonthFigures>,
893 /// This month by kind of usage: models, sandbox, deployments, plans.
894 pub by_kind: Vec<KindFigures>,
895 pub paying_workspaces: u32,
896 pub stopped: u32,
897 pub near_ceiling: u32,
898 pub declined: u32,
899 /// Sent and not yet paid, workspaces and enterprises.
900 pub open_invoices_micros: i64,
901 /// Follow-ups due today or earlier.
902 pub follow_ups_due: u32,
903}
904
905#[derive(Clone, Debug, Serialize, Deserialize)]
906#[serde(rename_all = "camelCase")]
907pub struct KindFigures {
908 pub kind: String,
909 pub charged_micros: i64,
910 pub cost_micros: i64,
911}
912
Billing accounts, terms and enterprises; g1t is no longer free913// --- Staff (sudo.g1t.sh) ------------------------------------------------------
914//
915// Called only by the sudo app, which only g1t staff can reach (behind
916// Cloudflare Access). Each change names who made it, and is kept in the
917// audit log.
918
919/// `admin_accounts`: every billing account, with where each stands this
920/// month. Returns `Vec<AccountSummary>`.
921#[derive(Debug, Default, Serialize, Deserialize)]
922pub struct AdminAccountsArgs {
923 #[serde(default)]
924 pub query: Option<String>,
Stripe webhooks, enterprise invoices, and sudo for both925 /// Exactly these workspaces' accounts, such as one page of sudo's
926 /// list; every account with activity when absent.
927 #[serde(default)]
928 pub workspaces: Option<Vec<String>>,
Billing accounts, terms and enterprises; g1t is no longer free929}
930
931#[derive(Clone, Debug, Serialize, Deserialize)]
932#[serde(rename_all = "camelCase")]
933pub struct AccountSummary {
934 pub account: BillingAccount,
935 pub limit: Limit,
936 /// Charged this month, after terms.
937 pub charged_micros: i64,
938 /// What this month's usage cost g1t.
939 pub cost_micros: i64,
940 /// Paid, ever.
941 pub paid_micros: i64,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace942 /// The same figures for each of the account's workspaces that has
943 /// any, so staff can see what one member of an enterprise used.
944 #[serde(default)]
945 pub by_workspace: Vec<WorkspaceFigures>,
Two limits, real invoices, trust that grows by itself, sales signals946 /// The last six months, oldest first, for trends.
947 #[serde(default)]
948 pub months: Vec<MonthFigures>,
949}
950
951/// One month of an account's billing.
952#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
953#[serde(rename_all = "camelCase")]
954pub struct MonthFigures {
955 /// YYYY-MM.
956 pub month: String,
957 pub charged_micros: i64,
958 pub cost_micros: i64,
959 pub paid_micros: i64,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace960}
961
962/// One workspace's share of an [`AccountSummary`].
963#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
964#[serde(rename_all = "camelCase")]
965pub struct WorkspaceFigures {
966 pub workspace: String,
967 pub charged_micros: i64,
968 pub cost_micros: i64,
969 pub paid_micros: i64,
Billing accounts, terms and enterprises; g1t is no longer free970}
971
972/// `admin_account`: one account in full. Returns `Outcome<AccountDetail>`.
973#[derive(Debug, Serialize, Deserialize)]
974pub struct AdminAccountArgs {
975 /// An account id, or a workspace slug.
976 pub id: String,
977}
978
979#[derive(Clone, Debug, Serialize, Deserialize)]
980#[serde(rename_all = "camelCase")]
981pub struct AccountDetail {
982 pub summary: AccountSummary,
983 /// Each workspace's limit, for an enterprise.
984 pub workspaces: Vec<Limit>,
985 pub ledger: Vec<LedgerEntry>,
986 pub audit: Vec<AdminAction>,
987}
988
989/// `admin_set_terms`. Returns `Outcome<BillingAccount>`.
990#[derive(Debug, Serialize, Deserialize)]
991pub struct AdminSetTermsArgs {
992 pub id: String,
993 pub terms: Terms,
994 pub by: String,
995}
996
997/// `admin_create_enterprise`. Returns `Outcome<BillingAccount>`.
998#[derive(Debug, Serialize, Deserialize)]
999pub struct AdminCreateEnterpriseArgs {
1000 pub name: String,
1001 pub workspaces: Vec<String>,
1002 pub by: String,
1003}
1004
1005/// `admin_attach`: moves a workspace onto an enterprise account, or back
1006/// onto its own with `account: None`. Returns `Outcome<BillingAccount>`.
1007#[derive(Debug, Serialize, Deserialize)]
1008pub struct AdminAttachArgs {
1009 pub workspace: String,
1010 pub account: Option<String>,
1011 pub by: String,
1012}
1013
1014/// `admin_credit`: money g1t gives a workspace, such as a refund or a
1015/// goodwill credit. Returns `Outcome<LedgerEntry>`.
1016#[derive(Debug, Serialize, Deserialize)]
1017pub struct AdminCreditArgs {
1018 pub workspace: String,
1019 pub amount_micros: i64,
1020 pub note: String,
1021 pub by: String,
1022}
1023
1024/// One change made in sudo.
1025#[derive(Clone, Debug, Serialize, Deserialize)]
1026#[serde(rename_all = "camelCase")]
1027pub struct AdminAction {
1028 pub id: String,
1029 pub account: String,
1030 pub action: String,
1031 pub detail: String,
1032 pub by: String,
1033 pub created_at: String,
1034}
1035
Paid features: a workspace turns on Deployments with a monthly plan1036/// What a feature's plan costs and includes.
1037#[derive(Clone, Debug, Serialize, Deserialize)]
1038#[serde(rename_all = "camelCase")]
1039pub struct Plan {
1040 pub feature: Feature,
1041 pub title: String,
1042 /// Charged every month while the plan is on, in cents.
1043 pub monthly_cents: u32,
1044 /// What the monthly price includes, one line each, for people to read.
1045 pub includes: Vec<String>,
1046 /// How usage past the allowance is charged, for people to read.
1047 pub overage: String,
1048}
1049
1050#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1051#[serde(rename_all = "snake_case")]
1052pub enum SubscriptionStatus {
1053 /// Paid up; the feature works.
1054 Active,
1055 /// Paid up to the end of the period, and ends then.
1056 Canceling,
1057 /// The last payment failed; the feature is off until it is paid.
1058 PastDue,
1059 /// Ended.
1060 Canceled,
1061}
1062
1063impl SubscriptionStatus {
1064 /// Whether the feature works in this state.
1065 pub fn on(self) -> bool {
1066 matches!(self, SubscriptionStatus::Active | SubscriptionStatus::Canceling)
1067 }
1068}
1069
1070/// A workspace's plan for one feature.
1071#[derive(Clone, Debug, Serialize, Deserialize)]
1072#[serde(rename_all = "camelCase")]
1073pub struct Subscription {
1074 pub feature: Feature,
1075 pub status: SubscriptionStatus,
1076 /// RFC 3339: when the period paid for ends, and the plan renews or
1077 /// ends.
1078 pub period_end: Option<String>,
1079 /// Username of whoever turned it on.
1080 pub started_by: String,
1081 /// RFC 3339.
1082 pub started_at: String,
1083}
1084
1085/// A feature as a workspace sees it: what it costs, and its plan if it has
1086/// one.
1087#[derive(Clone, Debug, Serialize, Deserialize)]
1088#[serde(rename_all = "camelCase")]
1089pub struct FeatureState {
1090 pub plan: Plan,
1091 pub subscription: Option<Subscription>,
1092 /// Whether the feature works for the workspace now.
1093 pub on: bool,
1094}
1095
1096/// `features`: every paid feature and the workspace's plan for each.
1097/// Members only. Returns `Outcome<Vec<FeatureState>>`.
1098#[derive(Debug, Serialize, Deserialize)]
1099pub struct FeaturesArgs {
1100 pub workspace: String,
1101 pub viewer: Viewer,
1102}
1103
1104/// `subscribe`: starts the card page for a feature's monthly plan. Owners
1105/// only. Returns `Outcome<Checkout>`; the page's id comes back to
1106/// `return_url` as `session`, for `confirm_subscription`.
1107#[derive(Debug, Serialize, Deserialize)]
1108#[serde(rename_all = "camelCase")]
1109pub struct SubscribeArgs {
1110 pub actor: User,
1111 pub workspace: String,
1112 pub feature: Feature,
1113 pub return_url: String,
1114}
1115
1116/// `confirm_subscription`: turns the feature on once the processor says
1117/// the plan was paid for. Safe to call any number of times. Returns
1118/// `Outcome<FeatureState>`.
1119#[derive(Debug, Serialize, Deserialize)]
1120pub struct ConfirmSubscriptionArgs {
1121 pub workspace: String,
1122 pub viewer: Viewer,
1123 pub session: String,
1124}
1125
1126/// `cancel_subscription` (`resume` false) ends a plan at the end of the
1127/// period paid for; with `resume` true, takes that back. Owners only.
1128/// Returns `Outcome<FeatureState>`.
1129#[derive(Debug, Serialize, Deserialize)]
1130pub struct CancelSubscriptionArgs {
1131 pub actor: User,
1132 pub workspace: String,
1133 pub feature: Feature,
1134 #[serde(default)]
1135 pub resume: bool,
1136}
1137
1138/// `has_feature`: whether a feature works for a workspace now, asked by the
1139/// service that provides it before doing paid work. Returns
1140/// `Outcome<bool>`: a failure, with the reason to show, when it does not.
1141/// True everywhere when no card processor is configured.
1142#[derive(Debug, Serialize, Deserialize)]
1143pub struct HasFeatureArgs {
1144 pub workspace: String,
1145 pub feature: Feature,
1146}
1147
1148/// `charge_feature`: usage of a feature past its plan's allowance, charged
1149/// from the workspace's credit at cost plus the margin, whatever
1150/// `FREE_WHILE_BUILDING` says. Called by the service that provides it.
1151/// Charged once per `reference`. Returns `Outcome<bool>`: false if that
1152/// reference was charged before.
1153#[derive(Debug, Serialize, Deserialize)]
1154#[serde(rename_all = "camelCase")]
1155pub struct ChargeFeatureArgs {
1156 pub workspace: String,
1157 pub feature: Feature,
1158 /// What it cost g1t, in millionths of a dollar, before the margin.
1159 pub cost_micros: i64,
1160 pub description: String,
1161 /// `namespace/name`, when the usage was one repository's.
1162 pub repo: Option<String>,
1163 /// Unique to this charge, e.g. `deployments/acme/2026-10`.
1164 pub reference: String,
1165}
1166
Models per workspace: several providers, routed by kind of work1167#[cfg(test)]
1168mod tests {
1169 use super::*;
1170
1171 #[test]
Paid features: a workspace turns on Deployments with a monthly plan1172 fn features_are_named_as_the_site_sends_them() {
1173 assert_eq!(
1174 serde_json::to_value(Feature::Deployments).unwrap(),
1175 serde_json::json!("deployments")
1176 );
1177 assert_eq!(Feature::parse("deployments"), Some(Feature::Deployments));
1178 assert!(SubscriptionStatus::Canceling.on());
1179 assert!(!SubscriptionStatus::PastDue.on());
1180 }
1181
1182 #[test]
Models per workspace: several providers, routed by kind of work1183 fn who_pays_is_read_as_the_runner_sends_it() {
1184 let run: StartRunArgs = serde_json::from_value(serde_json::json!({
1185 "workspace": "acme",
1186 "repo": { "namespace": "acme", "name": "web" },
1187 "number": 7,
1188 "task": "implement",
1189 "model": "Claude Sonnet 5.5",
1190 "billedTo": "workspace",
1191 }))
1192 .unwrap();
1193 assert_eq!(run.billed_to, "workspace");
1194 }
1195}