g1t/crates/contracts/src/billing.rs

642 lines22,504 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}
81
82#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
83#[serde(rename_all = "snake_case")]
84pub enum EntryKind {
85 /// Credit bought with a card.
86 TopUp,
87 /// An agent's run, or a paid feature's usage past its allowance.
88 Usage,
89}
90
91/// One line of a workspace's statement.
92#[derive(Clone, Debug, Serialize, Deserialize)]
93#[serde(rename_all = "camelCase")]
94pub struct LedgerEntry {
95 pub id: String,
96 pub kind: EntryKind,
97 /// Positive for credit added, negative for usage.
98 pub amount_micros: i64,
99 pub description: String,
100 /// For usage: the repository and pull request the agent worked on.
101 pub repo: Option<String>,
102 pub number: Option<u32>,
103 /// For usage: `implement`, `review` or `update`.
104 pub task: Option<String>,
105 /// For usage: the model, by its public name.
106 pub model: Option<String>,
107 /// For usage: `g1t` when g1t paid the model provider, `workspace` when
108 /// the workspace's own account did and only orchestration is charged.
109 #[serde(default = "g1t")]
110 pub billed_to: String,
111 /// For a top-up: the username of whoever paid.
112 pub created_by: Option<String>,
113 /// RFC 3339.
114 pub created_at: String,
115}
116
117fn g1t() -> String {
118 "g1t".to_owned()
119}
120
121/// `account` (`Outcome<Account>`) and `ledger` (`Outcome<Vec<LedgerEntry>>`,
122/// newest first). Members of the workspace only.
123#[derive(Debug, Serialize, Deserialize)]
124pub struct AccountArgs {
125 pub workspace: String,
126 pub viewer: Viewer,
127}
128
129/// `checkout`: starts a card payment for credit. Owners of the workspace
130/// only. Returns `Outcome<Checkout>`.
131#[derive(Debug, Serialize, Deserialize)]
132#[serde(rename_all = "camelCase")]
133pub struct CheckoutArgs {
134 pub actor: User,
135 pub workspace: String,
136 /// How much credit to buy, in cents.
137 pub amount_cents: u32,
138 /// Where the payment page sends the person afterwards. The payment's
139 /// id is appended as `session`.
140 pub return_url: String,
141}
142
143#[derive(Debug, Serialize, Deserialize)]
144pub struct Checkout {
145 /// The payment page to send the person to.
146 pub url: String,
147}
148
149/// `confirm`: credits a payment once the provider says it was made. Safe
150/// to call any number of times. Returns `Outcome<Account>`.
151#[derive(Debug, Serialize, Deserialize)]
152pub struct ConfirmArgs {
153 pub workspace: String,
154 pub viewer: Viewer,
155 /// The payment's id, as returned to `return_url`.
156 pub session: String,
157}
158
159/// `can_start`: whether a workspace may start an agent now, asked before
160/// anything is opened for it. Returns `Outcome<bool>`: a failure, with the
161/// reason to show, when it has no credit.
162#[derive(Debug, Serialize, Deserialize)]
163pub struct CanStartArgs {
164 pub workspace: String,
165}
166
167/// `start_run`: asks whether a workspace may start an agent, and opens the
168/// run it will be charged for. Called by the runner service. Returns
169/// `Outcome<Option<RunTicket>>`: no ticket when billing is off, a failure
170/// when the workspace has no credit.
171#[derive(Debug, Serialize, Deserialize)]
172pub struct StartRunArgs {
173 pub workspace: String,
174 pub repo: RepoPath,
175 pub number: u32,
176 /// `implement`, `review` or `update`.
177 pub task: String,
178 /// The model, by its public name.
179 pub model: String,
180 /// `workspace` when the run uses the workspace's own model provider.
181 /// The runner, which is TypeScript, sends it as `billedTo`.
182 #[serde(default = "g1t", alias = "billedTo")]
183 pub billed_to: String,
184 /// The model session's id, when its requests go through g1t's AI
185 /// Gateway: settling charges the run what the gateway priced them at.
186 #[serde(default)]
187 pub session: Option<String>,
188}
189
190#[derive(Clone, Debug, Serialize, Deserialize)]
191#[serde(rename_all = "camelCase")]
192pub struct RunTicket {
193 pub run_id: String,
194 /// Lets the sandbox, and nothing else, report what this run cost.
195 pub token: String,
196}
197
198/// `finish_run`: what a run cost, as its sandbox reports it. Charged once.
199/// Returns `Outcome<bool>`.
200#[derive(Debug, Serialize, Deserialize)]
201#[serde(rename_all = "camelCase")]
202pub struct FinishRunArgs {
203 pub run_id: String,
204 pub token: String,
205 /// What the model provider charged, in US dollars.
206 pub cost_usd: f64,
207 #[serde(default)]
208 pub turns: u32,
209}
210
211
212/// `usage`: what a workspace's agents cost over a period, broken down.
213/// Members only. Returns `Outcome<Usage>`.
214#[derive(Debug, Serialize, Deserialize)]
215pub struct UsageArgs {
216 pub workspace: String,
217 pub viewer: Viewer,
218 /// RFC 3339: the start of the period. The period runs to now.
219 pub since: String,
220}
221
222/// One slice of usage: what it was for, what it cost, how many runs.
223#[derive(Clone, Debug, Serialize, Deserialize)]
224#[serde(rename_all = "camelCase")]
225pub struct UsageSlice {
226 pub key: String,
227 pub micros: i64,
228 pub runs: u32,
229}
230
231/// What a workspace's agents cost over a period.
232#[derive(Clone, Debug, Serialize, Deserialize)]
233#[serde(rename_all = "camelCase")]
234pub struct Usage {
235 pub since: String,
236 /// Charged, including g1t's margin.
237 pub spent_micros: i64,
238 /// What g1t's model provider charged, before the margin.
239 pub cost_micros: i64,
240 /// What runs on the workspace's own provider cost there, as the harness
241 /// estimated it. Not charged by g1t.
242 pub provider_micros: i64,
243 /// What the runs used, at cost: g1t's models and the workspace's own
244 /// provider together, whatever was charged for them.
245 pub used_micros: i64,
246 /// g1t charges nothing for now. The slices then measure usage at cost,
247 /// since every charge is zero.
248 pub free: bool,
249 pub runs: u32,
250 /// Spend per day (`YYYY-MM-DD`) and task, as `day/task` keys.
251 pub by_day: Vec<UsageSlice>,
252 /// Per task: implement, review, revise, update, plan.
253 pub by_task: Vec<UsageSlice>,
254 /// Per repository, `namespace/name`.
255 pub by_repo: Vec<UsageSlice>,
256 /// The pull requests that cost most, as `namespace/name#number`.
257 pub by_pull: Vec<UsageSlice>,
258 /// Per model, by its public name.
259 pub by_model: Vec<UsageSlice>,
260 /// Credit bought in the period.
261 pub added_micros: i64,
262}
263
264/// A paid feature a workspace turns on with a monthly plan, the way
265/// Cloudflare's Workers for Platforms or Vercel's Pro are bought. Never
266/// free: `FREE_WHILE_BUILDING` and the free model allowance do not cover
267/// it.
268#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
269#[serde(rename_all = "snake_case")]
270pub enum Feature {
271 /// Previews per pull request and production on g1t.page.
272 Deployments,
273}
274
275impl Feature {
276 pub const ALL: [Feature; 1] = [Feature::Deployments];
277
278 pub fn as_str(self) -> &'static str {
279 match self {
280 Feature::Deployments => "deployments",
281 }
282 }
283
284 pub fn parse(name: &str) -> Option<Feature> {
285 Feature::ALL.into_iter().find(|feature| feature.as_str() == name)
286 }
287
288 pub fn title(self) -> &'static str {
289 match self {
290 Feature::Deployments => "Deployments",
291 }
292 }
293}
294
295/// What the Deployments plan includes each month; usage past it is charged
296/// at cost plus the margin. The billing service describes the plan with
297/// these and the deployments service meters against them.
298pub mod deployments_allowance {
299 /// Apps deployed at once: production and previews together.
300 pub const APPS: u32 = 10;
301 pub const REQUESTS: u64 = 1_000_000;
302 pub const CPU_MS: u64 = 3_000_000;
303 /// What Cloudflare charges g1t past that, in millionths of a dollar.
304 pub const MICROS_PER_APP_MONTH: i64 = 20_000;
305 pub const MICROS_PER_MILLION_REQUESTS: i64 = 300_000;
306 pub const MICROS_PER_MILLION_CPU_MS: i64 = 20_000;
307 /// What one second of a build's sandbox costs g1t (Cloudflare
308 /// Containers, standard-1: half a vCPU, 4 GiB, 8 GB disk), rounded up.
309 /// Builds are not in the allowance: each is charged at this plus the
310 /// margin.
311 pub const MICROS_PER_BUILD_SECOND: i64 = 21;
312}
313
314/// Sandbox time: every sandbox g1t starts for a workspace (agents,
315/// reviews, checks, the merge queue, workflow jobs) is metered by the
316/// second. Deploy builds are charged by the Deployments plan instead.
317pub mod sandbox_allowance {
318 /// Free each calendar month (UTC): 500 minutes.
319 pub const FREE_SECONDS: i64 = 30_000;
320 /// What one second costs g1t (Cloudflare Containers, standard-1),
321 /// rounded up. Recorded with every entry.
322 pub const COST_MICROS_PER_SECOND: i64 = super::deployments_allowance::MICROS_PER_BUILD_SECOND;
323 /// What one second past the free minutes is charged: $0.003 a minute.
324 pub const MICROS_PER_SECOND: i64 = 50;
325}
326
327/// `record_sandbox`: how long one sandbox ran for a workspace, reported by
328/// the runner when it stops. Recorded once per `reference`, with what it
329/// cost g1t; seconds past the month's free minutes are charged at
330/// `sandbox_allowance::MICROS_PER_SECOND`, unless `FREE_WHILE_BUILDING`.
331/// Returns `Outcome<bool>`: false if that reference was recorded before.
332#[derive(Debug, Serialize, Deserialize)]
333#[serde(rename_all = "camelCase")]
334pub struct RecordSandboxArgs {
335 pub workspace: String,
336 pub seconds: u32,
337 /// What ran, e.g. `Checks on acme/api#12`.
338 pub description: String,
339 /// `namespace/name`.
340 pub repo: Option<String>,
341 /// Unique to the run.
342 pub reference: String,
343}
344
345/// How much a workspace has earned g1t's trust with money, which sets how
346/// far its unpaid usage can go before its work stops.
347#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
348#[serde(rename_all = "snake_case")]
349pub enum Trust {
350 /// No live payment yet: only a little past the free allowances.
351 New,
352 /// Has paid g1t real money: the ceiling grows with what it has paid.
353 Paid,
354 /// A ceiling g1t set by hand, after talking to the workspace.
355 Reviewed,
356 /// g1t's own workspaces: no ceiling.
357 Internal,
358}
359
360#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
361#[serde(rename_all = "snake_case")]
362pub enum LimitState {
363 Ok,
364 /// Past 80% of the ceiling.
365 Warning,
366 /// At or past it: no new sandboxes, builds or app requests.
367 Stopped,
368}
369
370/// How far a workspace's unpaid usage has gone this month, and where its
371/// work stops: like Fly's or Cloudflare's limits for new accounts, so no
372/// one runs up costs g1t cannot collect. Usage counts at what it cost g1t
373/// or what it is charged, whichever is more, so it counts while g1t is
374/// free too.
375#[derive(Clone, Debug, Serialize, Deserialize)]
376#[serde(rename_all = "camelCase")]
377pub struct Limit {
378 pub workspace: String,
379 pub trust: Trust,
380 /// Usage this month (UTC) less what was paid this month.
381 pub exposure_micros: i64,
382 /// Where work stops: the lower of g1t's ceiling and the owner's own
383 /// spend limit. None for g1t's own workspaces.
384 pub ceiling_micros: Option<i64>,
385 /// The ceiling g1t sets from `trust`.
386 pub trust_ceiling_micros: Option<i64>,
387 /// The owner's own monthly limit, if they set one.
388 pub spend_limit_micros: Option<i64>,
389 pub state: LimitState,
390 /// What to tell people when work is stopped or close to it.
391 pub message: Option<String>,
392}
393
394/// `limit`: a workspace's limit, for its members. Returns `Outcome<Limit>`.
395#[derive(Debug, Serialize, Deserialize)]
396pub struct LimitArgs {
397 pub workspace: String,
398 pub viewer: Viewer,
399}
400
401/// `check_limit`: the same, for the services that enforce it. Returns
402/// `Outcome<Limit>`.
403#[derive(Debug, Serialize, Deserialize)]
404pub struct CheckLimitArgs {
405 pub workspace: String,
406}
407
408/// `note_pending`: usage this month that will be charged later, such as
409/// app traffic past a plan, so the workspace's limit counts it now. Each
410/// report replaces the last for that workspace, source and month. Called
411/// by the service that meters it. Returns `bool`.
412#[derive(Debug, Serialize, Deserialize)]
413#[serde(rename_all = "camelCase")]
414pub struct NotePendingArgs {
415 pub workspace: String,
416 /// `deployments`.
417 pub source: String,
418 /// What it cost g1t so far this month, before the margin.
419 pub cost_micros: i64,
420}
421
422/// `set_spend_limit`: the owner's own monthly ceiling, under g1t's; None
423/// removes it. Owners only. Returns `Outcome<Limit>`.
424#[derive(Debug, Serialize, Deserialize)]
425#[serde(rename_all = "camelCase")]
426pub struct SetSpendLimitArgs {
427 pub actor: User,
428 pub workspace: String,
429 pub spend_limit_micros: Option<i64>,
430}
431
432/// One metered unit: what it costs g1t, and what it is sold at. The price
433/// is always `cost × (100 + markup) / 100`, so it follows the cost.
434#[derive(Clone, Debug, Serialize, Deserialize)]
435#[serde(rename_all = "camelCase")]
436pub struct Price {
437 /// `sandbox_second`, `build_second`, `app_requests`, `app_cpu`, `app_month`.
438 pub meter: String,
439 pub title: String,
440 pub unit: String,
441 /// Millionths of a dollar per unit; may have a fraction.
442 pub cost_micros: f64,
443 pub markup_percent: u32,
444 pub price_micros: f64,
445 /// `list`: Cloudflare's published price. `cloudflare`: what Cloudflare
446 /// actually billed g1t, measured.
447 pub source: String,
448 /// When it was last checked against Cloudflare's bill.
449 pub checked_at: Option<String>,
450 pub updated_at: String,
451}
452
453impl Price {
454 pub fn price_for(cost_micros: f64, markup_percent: u32) -> f64 {
455 cost_micros * f64::from(100 + markup_percent) / 100.0
456 }
457}
458
459/// A cost that moved.
460#[derive(Clone, Debug, Serialize, Deserialize)]
461#[serde(rename_all = "camelCase")]
462pub struct PriceChange {
463 pub meter: String,
464 pub old_cost_micros: f64,
465 pub new_cost_micros: f64,
466 pub markup_percent: u32,
467 pub reason: String,
468 pub created_at: String,
469}
470
471/// `prices`: every metered price and the recent changes. Public. Returns
472/// `PriceBook`.
473#[derive(Clone, Debug, Serialize, Deserialize)]
474#[serde(rename_all = "camelCase")]
475pub struct PriceBook {
476 pub prices: Vec<Price>,
477 pub changes: Vec<PriceChange>,
478 /// The margin on model usage, which is charged at what AI Gateway
479 /// priced each request at.
480 pub model_margin_percent: u32,
481}
482
483/// What a feature's plan costs and includes.
484#[derive(Clone, Debug, Serialize, Deserialize)]
485#[serde(rename_all = "camelCase")]
486pub struct Plan {
487 pub feature: Feature,
488 pub title: String,
489 /// Charged every month while the plan is on, in cents.
490 pub monthly_cents: u32,
491 /// What the monthly price includes, one line each, for people to read.
492 pub includes: Vec<String>,
493 /// How usage past the allowance is charged, for people to read.
494 pub overage: String,
495}
496
497#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
498#[serde(rename_all = "snake_case")]
499pub enum SubscriptionStatus {
500 /// Paid up; the feature works.
501 Active,
502 /// Paid up to the end of the period, and ends then.
503 Canceling,
504 /// The last payment failed; the feature is off until it is paid.
505 PastDue,
506 /// Ended.
507 Canceled,
508}
509
510impl SubscriptionStatus {
511 /// Whether the feature works in this state.
512 pub fn on(self) -> bool {
513 matches!(self, SubscriptionStatus::Active | SubscriptionStatus::Canceling)
514 }
515}
516
517/// A workspace's plan for one feature.
518#[derive(Clone, Debug, Serialize, Deserialize)]
519#[serde(rename_all = "camelCase")]
520pub struct Subscription {
521 pub feature: Feature,
522 pub status: SubscriptionStatus,
523 /// RFC 3339: when the period paid for ends, and the plan renews or
524 /// ends.
525 pub period_end: Option<String>,
526 /// Username of whoever turned it on.
527 pub started_by: String,
528 /// RFC 3339.
529 pub started_at: String,
530}
531
532/// A feature as a workspace sees it: what it costs, and its plan if it has
533/// one.
534#[derive(Clone, Debug, Serialize, Deserialize)]
535#[serde(rename_all = "camelCase")]
536pub struct FeatureState {
537 pub plan: Plan,
538 pub subscription: Option<Subscription>,
539 /// Whether the feature works for the workspace now.
540 pub on: bool,
541}
542
543/// `features`: every paid feature and the workspace's plan for each.
544/// Members only. Returns `Outcome<Vec<FeatureState>>`.
545#[derive(Debug, Serialize, Deserialize)]
546pub struct FeaturesArgs {
547 pub workspace: String,
548 pub viewer: Viewer,
549}
550
551/// `subscribe`: starts the card page for a feature's monthly plan. Owners
552/// only. Returns `Outcome<Checkout>`; the page's id comes back to
553/// `return_url` as `session`, for `confirm_subscription`.
554#[derive(Debug, Serialize, Deserialize)]
555#[serde(rename_all = "camelCase")]
556pub struct SubscribeArgs {
557 pub actor: User,
558 pub workspace: String,
559 pub feature: Feature,
560 pub return_url: String,
561}
562
563/// `confirm_subscription`: turns the feature on once the processor says
564/// the plan was paid for. Safe to call any number of times. Returns
565/// `Outcome<FeatureState>`.
566#[derive(Debug, Serialize, Deserialize)]
567pub struct ConfirmSubscriptionArgs {
568 pub workspace: String,
569 pub viewer: Viewer,
570 pub session: String,
571}
572
573/// `cancel_subscription` (`resume` false) ends a plan at the end of the
574/// period paid for; with `resume` true, takes that back. Owners only.
575/// Returns `Outcome<FeatureState>`.
576#[derive(Debug, Serialize, Deserialize)]
577pub struct CancelSubscriptionArgs {
578 pub actor: User,
579 pub workspace: String,
580 pub feature: Feature,
581 #[serde(default)]
582 pub resume: bool,
583}
584
585/// `has_feature`: whether a feature works for a workspace now, asked by the
586/// service that provides it before doing paid work. Returns
587/// `Outcome<bool>`: a failure, with the reason to show, when it does not.
588/// True everywhere when no card processor is configured.
589#[derive(Debug, Serialize, Deserialize)]
590pub struct HasFeatureArgs {
591 pub workspace: String,
592 pub feature: Feature,
593}
594
595/// `charge_feature`: usage of a feature past its plan's allowance, charged
596/// from the workspace's credit at cost plus the margin, whatever
597/// `FREE_WHILE_BUILDING` says. Called by the service that provides it.
598/// Charged once per `reference`. Returns `Outcome<bool>`: false if that
599/// reference was charged before.
600#[derive(Debug, Serialize, Deserialize)]
601#[serde(rename_all = "camelCase")]
602pub struct ChargeFeatureArgs {
603 pub workspace: String,
604 pub feature: Feature,
605 /// What it cost g1t, in millionths of a dollar, before the margin.
606 pub cost_micros: i64,
607 pub description: String,
608 /// `namespace/name`, when the usage was one repository's.
609 pub repo: Option<String>,
610 /// Unique to this charge, e.g. `deployments/acme/2026-10`.
611 pub reference: String,
612}
613
614#[cfg(test)]
615mod tests {
616 use super::*;
617
618 #[test]
619 fn features_are_named_as_the_site_sends_them() {
620 assert_eq!(
621 serde_json::to_value(Feature::Deployments).unwrap(),
622 serde_json::json!("deployments")
623 );
624 assert_eq!(Feature::parse("deployments"), Some(Feature::Deployments));
625 assert!(SubscriptionStatus::Canceling.on());
626 assert!(!SubscriptionStatus::PastDue.on());
627 }
628
629 #[test]
630 fn who_pays_is_read_as_the_runner_sends_it() {
631 let run: StartRunArgs = serde_json::from_value(serde_json::json!({
632 "workspace": "acme",
633 "repo": { "namespace": "acme", "name": "web" },
634 "number": 7,
635 "task": "implement",
636 "model": "Claude Sonnet 5.5",
637 "billedTo": "workspace",
638 }))
639 .unwrap();
640 assert_eq!(run.billed_to, "workspace");
641 }
642}