g1t/crates/contracts/src/billing.rs

2,937 lines106,507 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`: a workspace's trial credit, so people can try g1t (its agents on
38/// g1t's hosted models among it) without a key or a card of their own. Each
39/// new workspace gets one grant of usage credit (`TRIAL_WORKSPACE_MICROS`),
40/// made when it first uses something, out of a pool for everyone that
41/// resets each calendar month (`TRIAL_MONTHLY_POOL_MICROS`). When this
42/// month's pool is given out, new grants wait for the next month. Returns
43/// `Trial`.
44#[derive(Debug, Serialize, Deserialize)]
45#[serde(rename_all = "camelCase")]
46pub struct TrialArgs {
47 pub workspace: String,
48 /// Workspaces open to hosted models anyway, whose use is not counted
49 /// against the pool.
50 #[serde(default)]
51 pub exempt: Vec<String>,
52}
53
54#[derive(Clone, Debug, Serialize, Deserialize)]
55#[serde(rename_all = "camelCase")]
56pub struct Trial {
57 /// Whether its agents may use g1t's hosted models on the trial now: it
58 /// has credit left, or this month's pool can still grant it some.
59 pub open: bool,
60 /// What the trial has paid for so far, in millionths of a dollar.
61 pub used_micros: i64,
62 /// Its grant, or what it would be granted.
63 pub limit_micros: i64,
64 /// No longer used: the trial does not end on a date. Kept for older
65 /// readers; always null.
66 pub ends_at: Option<String>,
67 /// Why it is closed: `off` (no trials), `used` (this workspace's grant
68 /// is spent) or `pool` (this month's grants are all given out; see
69 /// `waits_until`). `ended` is no longer sent.
70 pub reason: Option<String>,
71 /// Whether the workspace has its grant already.
72 #[serde(default)]
73 pub granted: bool,
74 /// RFC 3339: when a workspace waiting for a grant can get one, the
75 /// first of next month. Only with reason `pool`.
76 #[serde(default)]
77 pub waits_until: Option<String>,
78}
79
80/// A workspace's standing.
81#[derive(Clone, Debug, Serialize, Deserialize)]
82#[serde(rename_all = "camelCase")]
83pub struct Account {
84 pub workspace: String,
85 /// Credit left, in millionths of a dollar. Can dip below zero by the
86 /// cost of the runs that were under way when it ran out.
87 pub balance_micros: i64,
88 pub status: Status,
89 /// What is added to a run's cost, in percent.
90 pub margin_percent: u32,
91 /// The card g1t charges as the workspace nears its limit and when a
92 /// month closes, if one is on file.
93 #[serde(default)]
94 pub card: Option<Card>,
95}
96
97/// A saved card, as far as it is safe to show.
98#[derive(Clone, Debug, Serialize, Deserialize)]
99#[serde(rename_all = "camelCase")]
100pub struct Card {
101 /// `visa`, `mastercard`, ...
102 pub brand: String,
103 pub last4: String,
104 pub exp_month: u32,
105 pub exp_year: u32,
106}
107
108/// `billing_portal`: Stripe's hosted billing page for the workspace, where
109/// an owner adds or replaces the card, sees invoices and receipts, and sets
110/// the billing email and address. g1t never handles card numbers. Owners
111/// only. Returns `Outcome<Checkout>` (its `url`); Stripe sends them back
112/// to `return_url`.
113#[derive(Debug, Serialize, Deserialize)]
114pub struct BillingPortalArgs {
115 pub actor: User,
116 pub workspace: String,
117 pub return_url: String,
118}
119
120/// `admin_billing_link`: for staff to send a customer: their Stripe billing
121/// page. Returns `Outcome<BillingLink>`.
122#[derive(Debug, Serialize, Deserialize)]
123pub struct AdminBillingLinkArgs {
124 pub workspace: String,
125 pub by: String,
126}
127
128#[derive(Clone, Debug, Serialize, Deserialize)]
129#[serde(rename_all = "camelCase")]
130pub struct BillingLink {
131 /// A one-time session on Stripe's billing page, signed in already.
132 pub portal_url: String,
133 /// The billing page's sign-in page, which does not expire: the
134 /// customer signs in with the email Stripe has for them.
135 pub login_url: Option<String>,
136 pub customer_email: Option<String>,
137 pub expires_note: String,
138}
139
140#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
141#[serde(rename_all = "snake_case")]
142pub enum EntryKind {
143 /// Credit bought with a card.
144 TopUp,
145 /// An agent's run, or a paid feature's usage past its allowance.
146 Usage,
147}
148
149/// One line of a workspace's statement.
150#[derive(Clone, Debug, Serialize, Deserialize)]
151#[serde(rename_all = "camelCase")]
152pub struct LedgerEntry {
153 pub id: String,
154 pub kind: EntryKind,
155 /// Positive for credit added, negative for usage.
156 pub amount_micros: i64,
157 pub description: String,
158 /// For usage: the repository and pull request the agent worked on.
159 pub repo: Option<String>,
160 pub number: Option<u32>,
161 /// For usage: `implement`, `review` or `update`.
162 pub task: Option<String>,
163 /// For usage: the model, by its public name.
164 pub model: Option<String>,
165 /// For usage: `g1t` when g1t paid the model provider, `workspace` when
166 /// the workspace's own account did. Runs on the workspace's own
167 /// provider pay only their sandbox time now, so only older entries
168 /// are `workspace`.
169 #[serde(default = "g1t")]
170 pub billed_to: String,
171 /// For a top-up: the username of whoever paid.
172 pub created_by: Option<String>,
173 /// RFC 3339.
174 pub created_at: String,
175 /// The workspace the line belongs to, which tells an enterprise's
176 /// lines apart.
177 #[serde(default, skip_serializing_if = "Option::is_none")]
178 pub workspace: Option<String>,
179 /// For usage: what the g1t plan's monthly included usage paid of it.
180 /// The entry's `amount_micros` is what is left to pay.
181 #[serde(default)]
182 pub credit_micros: i64,
183 /// For usage: what the workspace's trial credit paid of it.
184 #[serde(default)]
185 pub trial_micros: i64,
186 /// For usage: what g1t's open-source pool paid of it.
187 #[serde(default)]
188 pub oss_micros: i64,
189 /// For usage: what g1t covered itself, such as the part of a free
190 /// workspace's last trial run that went past its trial credit.
191 #[serde(default)]
192 pub given_micros: i64,
193}
194
195fn g1t() -> String {
196 "g1t".to_owned()
197}
198
199/// `account` (`Outcome<Account>`) and `ledger` (`Outcome<Vec<LedgerEntry>>`,
200/// newest first). Members of the workspace only.
201#[derive(Debug, Serialize, Deserialize)]
202pub struct AccountArgs {
203 pub workspace: String,
204 pub viewer: Viewer,
205}
206
207/// `checkout`: prepays usage: money paid in advance, drawn down by usage
208/// after the plan's included usage, which raises what can be used before
209/// work stops by the same amount at once. $25 at the least. By card, with
210/// 3-D Secure; from $1,000 also by bank transfer. Owners of the workspace
211/// only. Returns `Outcome<Checkout>`.
212#[derive(Debug, Serialize, Deserialize)]
213#[serde(rename_all = "camelCase")]
214pub struct CheckoutArgs {
215 pub actor: User,
216 pub workspace: String,
217 /// How much to prepay, in cents.
218 pub amount_cents: u32,
219 /// Where the payment page sends the person afterwards. The payment's
220 /// id is appended as `session`.
221 pub return_url: String,
222 /// `card` (the default) or `bank_transfer` (from $1,000): Stripe gives
223 /// the account details, and the money counts once it arrives.
224 #[serde(default)]
225 pub method: Option<String>,
226}
227
228#[derive(Debug, Serialize, Deserialize)]
229pub struct Checkout {
230 /// The payment page to send the person to.
231 pub url: String,
232}
233
234/// `confirm`: credits a payment once the provider says it was made. Safe
235/// to call any number of times. Returns `Outcome<Account>`.
236#[derive(Debug, Serialize, Deserialize)]
237pub struct ConfirmArgs {
238 pub workspace: String,
239 pub viewer: Viewer,
240 /// The payment's id, as returned to `return_url`.
241 pub session: String,
242}
243
244/// `can_start`: whether a workspace may start an agent now, asked before
245/// anything is opened for it. Returns `Outcome<bool>`: a failure, with the
246/// reason to show, when it has no credit.
247#[derive(Debug, Serialize, Deserialize)]
248pub struct CanStartArgs {
249 pub workspace: String,
250}
251
252/// `start_run`: asks whether a workspace may start an agent, and opens the
253/// run it will be charged for. Called by the runner service. Returns
254/// `Outcome<Option<RunTicket>>`: no ticket when billing is off, a failure
255/// when the workspace has no credit.
256#[derive(Debug, Serialize, Deserialize)]
257pub struct StartRunArgs {
258 pub workspace: String,
259 pub repo: RepoPath,
260 pub number: u32,
261 /// `implement`, `review` or `update`.
262 pub task: String,
263 /// The model, by its public name.
264 pub model: String,
265 /// `workspace` when the run uses the workspace's own model provider.
266 /// The runner, which is TypeScript, sends it as `billedTo`.
267 #[serde(default = "g1t", alias = "billedTo")]
268 pub billed_to: String,
269 /// The model session's id, when its requests go through g1t's AI
270 /// Gateway: settling charges the run what the gateway priced them at.
271 #[serde(default)]
272 pub session: Option<String>,
273 /// `small` or `large`: the tier g1t routed the run to, when g1t pays
274 /// for its model. None on the workspace's own provider.
275 #[serde(default)]
276 pub tier: Option<String>,
277}
278
279#[derive(Clone, Debug, Serialize, Deserialize)]
280#[serde(rename_all = "camelCase")]
281pub struct RunTicket {
282 pub run_id: String,
283 /// Lets the sandbox, and nothing else, report what this run cost.
284 pub token: String,
285}
286
287/// `finish_run`: what a run cost, as its sandbox reports it. Charged once.
288/// Returns `Outcome<bool>`.
289#[derive(Debug, Serialize, Deserialize)]
290#[serde(rename_all = "camelCase")]
291pub struct FinishRunArgs {
292 pub run_id: String,
293 pub token: String,
294 /// What the model provider charged, in US dollars.
295 pub cost_usd: f64,
296 #[serde(default)]
297 pub turns: u32,
298}
299
300
301/// `usage`: what a workspace's agents cost over a period, broken down.
302/// Members only. Returns `Outcome<Usage>`.
303#[derive(Debug, Serialize, Deserialize)]
304pub struct UsageArgs {
305 pub workspace: String,
306 pub viewer: Viewer,
307 /// RFC 3339: the start of the period. The period runs to now.
308 pub since: String,
309}
310
311/// One slice of usage: what it was for, what it cost, how many runs.
312#[derive(Clone, Debug, Serialize, Deserialize)]
313#[serde(rename_all = "camelCase")]
314pub struct UsageSlice {
315 pub key: String,
316 pub micros: i64,
317 pub runs: u32,
318}
319
320/// What a workspace's agents cost over a period.
321#[derive(Clone, Debug, Serialize, Deserialize)]
322#[serde(rename_all = "camelCase")]
323pub struct Usage {
324 pub since: String,
325 /// Charged, including g1t's margin.
326 pub spent_micros: i64,
327 /// What g1t's usage came to at price, less what was charged: the plan's
328 /// included usage, the trial, a pool or a free period paid it. Usage at
329 /// price is `spent_micros` plus this.
330 #[serde(default)]
331 pub covered_micros: i64,
332 /// What g1t's model provider charged, before the margin.
333 pub cost_micros: i64,
334 /// What runs on the workspace's own provider cost there, as the harness
335 /// estimated it. Not charged by g1t.
336 pub provider_micros: i64,
337 /// What the runs used, at cost: g1t's models and the workspace's own
338 /// provider together, whatever was charged for them.
339 pub used_micros: i64,
340 /// g1t charges nothing for now. The slices then measure usage at cost,
341 /// since every charge is zero.
342 pub free: bool,
343 pub runs: u32,
344 /// Spend per day (`YYYY-MM-DD`) and task, as `day/task` keys.
345 pub by_day: Vec<UsageSlice>,
346 /// Per task: implement, review, revise, update, plan.
347 pub by_task: Vec<UsageSlice>,
348 /// Per repository, `namespace/name`.
349 pub by_repo: Vec<UsageSlice>,
350 /// The pull requests that cost most, as `namespace/name#number`.
351 pub by_pull: Vec<UsageSlice>,
352 /// Per model, by its public name.
353 pub by_model: Vec<UsageSlice>,
354 /// Credit bought in the period.
355 pub added_micros: i64,
356}
357
358/// `record_tokens`: what one model answer used, added to the day's count
359/// for its run. The model proxy sends it after each answer. For usage
360/// views only: runs are still priced from AI Gateway. Returns
361/// `Outcome<bool>`: false when there was nothing to count.
362#[derive(Debug, Serialize, Deserialize)]
363#[serde(rename_all = "camelCase")]
364pub struct RecordTokensArgs {
365 pub workspace: String,
366 /// The model session's id (`ModelSession::id`), one per run.
367 pub session: String,
368 /// The person the run is for, by username. Absent when nobody asked.
369 #[serde(default)]
370 pub person: Option<String>,
371 pub model: String,
372 /// On g1t's hosted models: `small` or `large`.
373 #[serde(default)]
374 pub tier: Option<String>,
375 #[serde(default)]
376 pub input: u64,
377 #[serde(default)]
378 pub output: u64,
379 #[serde(default)]
380 pub cache_read: u64,
381 #[serde(default)]
382 pub cache_write: u64,
383}
384
385/// `token_usage`: the model tokens a workspace's runs used, day by day,
386/// for the whole workspace or for one person. Members only; a member may
387/// ask only for themselves, an owner for anyone. Returns
388/// `Outcome<TokenUsage>`.
389#[derive(Debug, Serialize, Deserialize)]
390pub struct TokenUsageArgs {
391 pub workspace: String,
392 pub viewer: Viewer,
393 /// A username: only the runs for them.
394 #[serde(default)]
395 pub person: Option<String>,
396 /// How many days, to today: 42 when absent, 366 at most.
397 #[serde(default)]
398 pub days: Option<u32>,
399}
400
401/// One day's tokens.
402#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
403pub struct DayTokens {
404 /// `YYYY-MM-DD`, UTC.
405 pub day: String,
406 pub tokens: u64,
407}
408
409/// The model tokens runs used over a window of days.
410#[derive(Clone, Debug, Serialize, Deserialize)]
411#[serde(rename_all = "camelCase")]
412pub struct TokenUsage {
413 /// `YYYY-MM-DD`: the first day counted.
414 pub since: String,
415 pub days: u32,
416 /// Null for the whole workspace.
417 pub person: Option<String>,
418 pub total_tokens: u64,
419 pub input_tokens: u64,
420 pub output_tokens: u64,
421 pub cache_read_tokens: u64,
422 pub cache_write_tokens: u64,
423 /// What those runs were charged, as `usage` measures it.
424 pub cost_micros: i64,
425 /// Days in the window with any tokens.
426 pub active_days: u32,
427 /// Every day in the window, oldest first, zeros included.
428 pub by_day: Vec<DayTokens>,
429}
430
431/// What a workspace pays a monthly price for. There is one plan, `plan`
432/// ("g1t"): a flat price per workspace, never per person, with included
433/// usage each month, more private storage, and deployments. Never free:
434/// `FREE_WHILE_BUILDING` does not cover it.
435///
436/// `deployments` is not sold on its own any more: it comes with the plan.
437/// A service that asks `has_feature` for it is told whether the workspace
438/// has the plan, and a Deployments subscription bought before the change
439/// keeps working until its period ends.
440#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
441#[serde(rename_all = "snake_case")]
442pub enum Feature {
443 /// The g1t plan. Older readers called it `team`.
444 #[serde(alias = "team")]
445 Plan,
446 /// Previews per pull request and production on g1t.page: part of the
447 /// plan.
448 Deployments,
449}
450
451impl Feature {
452 /// What is sold: the plan alone.
453 pub const ALL: [Feature; 1] = [Feature::Plan];
454
455 pub fn as_str(self) -> &'static str {
456 match self {
457 Feature::Plan => "plan",
458 Feature::Deployments => "deployments",
459 }
460 }
461
462 pub fn parse(name: &str) -> Option<Feature> {
463 match name {
464 "plan" | "team" => Some(Feature::Plan),
465 "deployments" => Some(Feature::Deployments),
466 _ => None,
467 }
468 }
469
470 pub fn title(self) -> &'static str {
471 match self {
472 Feature::Plan => "g1t",
473 Feature::Deployments => "Deployments",
474 }
475 }
476}
477
478/// What deployments cost g1t, in millionths of a dollar: fallbacks for
479/// when billing's price book cannot be read. Nothing here is an allowance:
480/// on the plan every unit is metered from the first, at cost plus the
481/// margin, and drawn from the plan's included usage before anything is
482/// charged. Projects, previews and the apps behind them are not metered at
483/// all: Cloudflare's Workers for Platforms includes far more scripts than
484/// g1t runs, so an app costs g1t only the requests and CPU it answers with.
485pub mod deployment_costs {
486 /// Workers for Platforms: $0.30 per million requests.
487 pub const MICROS_PER_MILLION_REQUESTS: i64 = 300_000;
488 /// $0.02 per million CPU milliseconds.
489 pub const MICROS_PER_MILLION_CPU_MS: i64 = 20_000;
490 /// What one second of a build's sandbox costs g1t (Cloudflare
491 /// Containers, standard-1: half a vCPU, 4 GiB, 8 GB disk), rounded up,
492 /// as the price keeper measured it on 2026-10-05 (14.5). Only a
493 /// fallback: billing charges builds at the price book's `build_second`,
494 /// which the keeper keeps current.
495 pub const MICROS_PER_BUILD_SECOND: i64 = 15;
496 /// What one custom hostname costs g1t a month (Cloudflare for SaaS):
497 /// $0.10.
498 pub const MICROS_PER_DOMAIN_MONTH: i64 = 100_000;
499}
500
501/// `record_sandbox`: how long one sandbox ran for a workspace, reported by
502/// the runner when it stops. Every sandbox g1t starts for a workspace
503/// (agents, reviews, checks, the merge queue, workflow jobs) is metered by
504/// the second, from the first: recorded once per `reference`, with what it
505/// cost g1t, and charged at the price book's `sandbox_second` price unless
506/// `FREE_WHILE_BUILDING`. Deploy builds are charged by the Deployments plan
507/// instead.
508/// Returns `Outcome<bool>`: false if that reference was recorded before.
509#[derive(Debug, Serialize, Deserialize)]
510#[serde(rename_all = "camelCase")]
511pub struct RecordSandboxArgs {
512 pub workspace: String,
513 pub seconds: u32,
514 /// What ran, e.g. `Checks on acme/api#12`.
515 pub description: String,
516 /// `namespace/name`.
517 pub repo: Option<String>,
518 /// Unique to the run.
519 pub reference: String,
520 /// What ran: `agent`, `check`, `workflow` or `queue`. Decides whether
521 /// g1t's open-source pool may pay for it (checks, workflows and the
522 /// merge queue on public repositories). Absent: not the pool.
523 #[serde(default)]
524 pub kind: Option<ComputeKind>,
525 /// The vCPU-seconds the sandbox used, when it can tell. With it, the
526 /// run is priced on its own CPU (`sandbox_base_second` per second plus
527 /// `sandbox_cpu_second` per vCPU-second); without it, at the average
528 /// (`sandbox_second`).
529 #[serde(default, alias = "cpu_seconds")]
530 pub cpu_seconds: Option<f64>,
531 /// The reservation the work started under, settled with this cost.
532 #[serde(default, alias = "reservation_id")]
533 pub reservation_id: Option<String>,
534 /// It ran on one of the workspace's self-hosted runners: recorded as
535 /// self-hosted time, for the minutes, at $0.
536 #[serde(default, alias = "self_hosted")]
537 pub self_hosted: bool,
538 /// The machine it ran on, by label (`g1t-4core`); absent, the standard
539 /// one. A larger machine's memory and disk cost more each second.
540 #[serde(default)]
541 pub instance: Option<String>,
542}
543
544/// How much a workspace has earned g1t's trust with money, which sets how
545/// far its unpaid usage can go before its work stops.
546#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
547#[serde(rename_all = "snake_case")]
548pub enum Trust {
549 /// No live payment yet: only a little past the free allowances.
550 New,
551 /// Has paid g1t real money: the ceiling grows with what it has paid.
552 Paid,
553 /// Has paid steadily for months, with nothing disputed or declined:
554 /// the ceiling follows its monthly spend, up to $10,000, by itself.
555 Established,
556 /// A ceiling g1t set by hand, after talking to the workspace.
557 Reviewed,
558 /// g1t's own workspaces: no ceiling.
559 Internal,
560}
561
562#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
563#[serde(rename_all = "snake_case")]
564pub enum LimitState {
565 Ok,
566 /// Past 80% of the ceiling.
567 Warning,
568 /// At or past it: no new sandboxes, builds or app requests.
569 Stopped,
570}
571
572/// How far a workspace's unpaid usage has gone this month, and where its
573/// work stops: like Fly's or Cloudflare's limits for new accounts, so no
574/// one runs up costs g1t cannot collect. Usage counts at what it cost g1t
575/// or what it is charged, whichever is more, so it counts while g1t is
576/// free too.
577#[derive(Clone, Debug, Serialize, Deserialize)]
578#[serde(rename_all = "camelCase")]
579pub struct Limit {
580 pub workspace: String,
581 /// The account that pays, whose usage and payments the limit counts:
582 /// the workspace's own, or its enterprise's.
583 #[serde(default)]
584 pub account: String,
585 #[serde(default)]
586 pub account_name: String,
587 pub trust: Trust,
588 /// Usage this month (UTC) less what was paid this month.
589 pub exposure_micros: i64,
590 /// Where work stops: the lower of g1t's ceiling and the owner's own
591 /// spend limit. None for g1t's own workspaces.
592 pub ceiling_micros: Option<i64>,
593 /// The ceiling g1t sets from `trust`.
594 pub trust_ceiling_micros: Option<i64>,
595 /// The owner's own monthly limit, if they set one.
596 pub spend_limit_micros: Option<i64>,
597 pub state: LimitState,
598 /// What to tell people when work is stopped or close to it.
599 pub message: Option<String>,
600 /// Charged this month, which the spend limit is measured against.
601 #[serde(default)]
602 pub spent_micros: i64,
603 /// True while the owners have not chosen a spend limit of their own, so
604 /// the automatic one applies: $200, or twice last month's spend.
605 #[serde(default)]
606 pub default_spend_limit: bool,
607 /// The most the owners may set their own limit to: g1t's ceiling. To
608 /// go past it, they contact g1t.
609 #[serde(default)]
610 pub available_micros: Option<i64>,
611 /// How the ceiling grows from here, in a sentence.
612 #[serde(default)]
613 pub growth: Option<String>,
614 /// Money paid in advance and not used yet. It raises what can be used
615 /// before work stops by the same amount, at once.
616 #[serde(default)]
617 pub prepaid_micros: i64,
618 /// The highest ceiling the workspace has ever had. Owners may set their
619 /// spend limit anywhere up to it (plus what is prepaid) without asking.
620 #[serde(default)]
621 pub max_ceiling_micros: Option<i64>,
622 /// The most the owners may raise the limit to themselves, once, with
623 /// `raise_once`: twice the highest ceiling. None once it is used.
624 #[serde(default)]
625 pub raise_once_micros: Option<i64>,
626 /// When the one-time raise was used, RFC 3339.
627 #[serde(default)]
628 pub raised_at: Option<String>,
629 /// True in a paid workspace's first billing cycle, when the ceiling is
630 /// the starting one (`LIMIT_PAID_START_MICROS`).
631 #[serde(default)]
632 pub first_month: bool,
633}
634
635/// `limit`: a workspace's limit, for its members. Returns `Outcome<Limit>`.
636#[derive(Debug, Serialize, Deserialize)]
637pub struct LimitArgs {
638 pub workspace: String,
639 pub viewer: Viewer,
640}
641
642/// `check_limit`: the same, for the services that enforce it. Returns
643/// `Outcome<Limit>`.
644#[derive(Debug, Serialize, Deserialize)]
645pub struct CheckLimitArgs {
646 pub workspace: String,
647}
648
649/// `note_pending`: usage this month that will be charged later, such as
650/// app traffic past a plan, so the workspace's limit counts it now. Each
651/// report replaces the last for that workspace, source and month. Called
652/// by the service that meters it. Returns `bool`.
653#[derive(Debug, Serialize, Deserialize)]
654#[serde(rename_all = "camelCase")]
655pub struct NotePendingArgs {
656 pub workspace: String,
657 /// `deployments`, `security` (scans), `context` (search embeddings),
658 /// `storage` or `cache` (actions/cache, plan only). Billing charges
659 /// `security`, `context`, `storage` and `cache` itself once the month
660 /// is over; `deployments` charges its own.
661 pub source: String,
662 /// What it cost g1t so far this month, before the margin.
663 pub cost_micros: i64,
664 /// How much of it, for the Billing page: `1.2 million requests and
665 /// 3.4 million CPU ms`, `2 custom domains`.
666 #[serde(default)]
667 pub detail: Option<String>,
668}
669
670/// `usage_meters`: this month's usage for a workspace, one line per kind
671/// of meter, at what it is charged (cost plus the margin, on the account's
672/// terms) before the plan's included usage, the trial or g1t's pools paid
673/// for any of it. Members only. Returns `Outcome<Vec<MeterUsage>>`.
674#[derive(Debug, Serialize, Deserialize)]
675pub struct UsageMetersArgs {
676 pub workspace: String,
677 pub viewer: Viewer,
678}
679
680/// One kind of meter's usage this month.
681#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
682#[serde(rename_all = "camelCase")]
683pub struct MeterUsage {
684 /// `agents` (agent runs, models and sandboxes for checks, workflows
685 /// and the merge queue), `builds`, `requests` (app requests and CPU),
686 /// `domains`, `git_storage` (git operations and private storage) or
687 /// `search_scans` (search embeddings and security scans).
688 pub key: String,
689 pub label: String,
690 /// At price, before what paid for it.
691 pub micros: i64,
692 /// How much, when it is known: `12 runs`, `41 build minutes`.
693 #[serde(default)]
694 pub quantity: Option<String>,
695}
696
697/// `set_spend_limit`: the owner's own monthly ceiling, under g1t's; None
698/// removes it. Owners only. Returns `Outcome<Limit>`.
699#[derive(Debug, Serialize, Deserialize)]
700#[serde(rename_all = "camelCase")]
701pub struct SetSpendLimitArgs {
702 pub actor: User,
703 pub workspace: String,
704 /// A monthly limit, at most what is available; None goes back to the
705 /// default.
706 pub spend_limit_micros: Option<i64>,
707 /// Use everything available, with no limit of their own.
708 #[serde(default)]
709 pub use_full_limit: bool,
710 /// Use the one-time raise: up to twice the highest ceiling the
711 /// workspace has had, without asking. Once per workspace.
712 #[serde(default, alias = "raiseOnce")]
713 pub raise_once: bool,
714}
715
716/// One metered unit: what it costs g1t, and what it is sold at. The price
717/// is always `cost × (100 + markup) / 100`, so it follows the cost.
718#[derive(Clone, Debug, Serialize, Deserialize)]
719#[serde(rename_all = "camelCase")]
720pub struct Price {
721 /// `sandbox_second`, `build_second`, `app_requests`, `app_cpu`, `app_month`.
722 pub meter: String,
723 pub title: String,
724 pub unit: String,
725 /// Millionths of a dollar per unit; may have a fraction.
726 pub cost_micros: f64,
727 pub markup_percent: u32,
728 pub price_micros: f64,
729 /// `list`: Cloudflare's published price. `cloudflare`: what Cloudflare
730 /// actually billed g1t, measured.
731 pub source: String,
732 /// When it was last checked against Cloudflare's bill.
733 pub checked_at: Option<String>,
734 pub updated_at: String,
735}
736
737impl Price {
738 pub fn price_for(cost_micros: f64, markup_percent: u32) -> f64 {
739 cost_micros * f64::from(100 + markup_percent) / 100.0
740 }
741}
742
743/// A cost that moved.
744#[derive(Clone, Debug, Serialize, Deserialize)]
745#[serde(rename_all = "camelCase")]
746pub struct PriceChange {
747 pub meter: String,
748 pub old_cost_micros: f64,
749 pub new_cost_micros: f64,
750 pub markup_percent: u32,
751 /// The markup before, when the change was to the markup rather than
752 /// to the cost. Absent when the markup stayed `markup_percent`.
753 #[serde(default, skip_serializing_if = "Option::is_none")]
754 pub old_markup_percent: Option<u32>,
755 pub reason: String,
756 pub created_at: String,
757 /// When a change still to come takes effect: a rise is announced
758 /// before it is charged. Absent for changes already made.
759 #[serde(default, skip_serializing_if = "Option::is_none")]
760 pub effective_at: Option<String>,
761}
762
763/// `prices`: every metered price and the recent changes. Public. Returns
764/// `PriceBook`.
765#[derive(Clone, Debug, Serialize, Deserialize)]
766#[serde(rename_all = "camelCase")]
767pub struct PriceBook {
768 pub prices: Vec<Price>,
769 pub changes: Vec<PriceChange>,
770 /// The margin on model usage, which is charged at what AI Gateway
771 /// priced each request at.
772 pub model_margin_percent: u32,
773 /// Every plan, as it is sold now.
774 #[serde(default)]
775 pub plans: Vec<Plan>,
776 /// What is free, and what pays for it.
777 #[serde(default)]
778 pub free: Option<FreeTier>,
779}
780
781/// What g1t gives without a plan, each with what pays for it: a capped
782/// budget, never an open-ended allowance.
783#[derive(Clone, Debug, Default, Serialize, Deserialize)]
784#[serde(rename_all = "camelCase")]
785pub struct FreeTier {
786 /// Each new workspace's trial credit, once.
787 pub trial_workspace_micros: i64,
788 /// Trial grants each month, in all; new trials wait when it is spent.
789 pub trial_monthly_pool_micros: i64,
790 /// g1t's open-source pool each month, and any one repository's share.
791 pub oss_pool_micros: i64,
792 pub oss_repo_micros: i64,
793 /// Private repository storage that is free for every workspace. Past
794 /// it, the plan pays at cost plus the margin; a free workspace's pushes
795 /// to private repositories stop instead.
796 pub free_private_storage_bytes: i64,
797 /// Days of audit log a free workspace keeps.
798 pub audit_retention_days: u32,
799 /// Days of audit log the g1t plan keeps, and g1t's own and enterprise
800 /// workspaces. Longer is by arrangement, set per account in sudo.
801 #[serde(default)]
802 pub plan_audit_retention_days: u32,
803 /// The smallest amount a card is charged when a month closes; less
804 /// carries over. Charges at a limit always go through.
805 pub min_charge_micros: i64,
806 /// Git operations (clones, fetches and pushes through g1t) that are
807 /// free for every workspace each month. Past it, the plan pays at cost
808 /// plus the margin and is never slowed; a free workspace is slowed
809 /// down, never charged.
810 #[serde(default)]
811 pub git_operations_included: u64,
812 /// A new paid workspace's ceiling in its first month.
813 #[serde(default)]
814 pub paid_start_ceiling_micros: i64,
815 /// The most a one-click goodwill credit can cost g1t.
816 #[serde(default)]
817 pub overage_forgive_cost_micros: i64,
818}
819
820/// Who pays: a billing account. Every workspace has one; by default its
821/// own. An enterprise account pays for several workspaces at once, as
822/// GitHub Enterprise does: one bill, one limit, one set of terms.
823#[derive(Clone, Debug, Serialize, Deserialize)]
824#[serde(rename_all = "camelCase")]
825pub struct BillingAccount {
826 /// `ws_<slug>` for a workspace's own account; `ent_…` for an enterprise.
827 pub id: String,
828 pub kind: AccountKind,
829 pub name: String,
830 pub terms: Terms,
831 /// The workspaces it pays for.
832 pub workspaces: Vec<String>,
833 /// Where an enterprise's invoices go.
834 #[serde(default)]
835 pub billing_email: Option<String>,
836 /// An enterprise's invoices, newest first. Empty for a workspace's own.
837 #[serde(default)]
838 pub invoices: Vec<EnterpriseInvoice>,
839 pub created_at: String,
840 /// What g1t staff set for the account beyond its terms.
841 #[serde(default)]
842 pub allowances: Allowances,
843}
844
845/// Set per account by g1t staff in sudo, on top of its terms.
846#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
847#[serde(rename_all = "camelCase")]
848pub struct Allowances {
849 /// The g1t plan without paying for its monthly price, such as for a
850 /// partner. Usage is charged as usual. Comped accounts have it anyway.
851 #[serde(default, alias = "team")]
852 pub plan: bool,
853 /// Each of the account's public repositories' monthly cap on g1t's
854 /// open-source pool, in place of `OSS_REPO_MICROS`. None: the default.
855 #[serde(default)]
856 pub oss_repo_micros: Option<i64>,
857 /// The trial credit each of its workspaces gets, in place of
858 /// `TRIAL_WORKSPACE_MICROS`, outside the monthly pool. None: the default.
859 #[serde(default)]
860 pub trial_micros: Option<i64>,
861 /// Agents at once, in place of the plan's (2 in the first month or on
862 /// the trial, then 10). None: the default.
863 #[serde(default)]
864 pub max_concurrent_agents: Option<u32>,
865 /// One run's spend cap, in place of `RUN_CAP_MICROS` and the owners'
866 /// own. None: theirs, or the default.
867 #[serde(default)]
868 pub run_cap_micros: Option<i64>,
869 /// What the agents on one issue may spend in all, in place of
870 /// `ISSUE_CAP_MICROS` and the owners' own. None: theirs, or the default.
871 #[serde(default)]
872 pub issue_cap_micros: Option<i64>,
873 /// Days of audit log its workspaces keep, in place of the plan's (7
874 /// free, 90 on the plan), longer or shorter. None: the plan's.
875 #[serde(default)]
876 pub audit_retention_days: Option<u32>,
877 /// A hold g1t staff put on new compute, with why. None: no hold.
878 #[serde(default)]
879 pub hold: Option<String>,
880}
881
882/// `admin_set_allowances`: the plan on or off without charge, overrides of
883/// the plan's caps, a hold, and the account's share of g1t's pools.
884/// Recorded with who and why. Returns `Outcome<BillingAccount>`.
885#[derive(Debug, Serialize, Deserialize)]
886pub struct AdminSetAllowancesArgs {
887 pub id: String,
888 pub allowances: Allowances,
889 pub note: String,
890 pub by: String,
891}
892
893// --- Entitlements, and compute started under a reservation -----------------
894//
895// Every service that starts compute (sandboxes for agents, checks,
896// workflows and the merge queue; builds; models; semantic search) asks
897// billing first:
898//
899// 1. `entitlements { workspace }` says what the workspace may do at all:
900// its plan, whether it may start compute, its caps, and whether compute
901// is paused.
902// 2. `reserve { workspace, repo, public, kind, estimate_micros }` holds the
903// work's estimated cost against what may pay for it, so that starts at
904// the same moment cannot overshoot the ceiling together. It answers who
905// pays first, or refuses with a stable code and a message for the owner.
906// 3. `settle { reservation_id, actual_micros }` releases the hold once the
907// work is done. The charge itself goes on the ledger the usual way
908// (`finish_run`, `record_sandbox`, `charge_feature`, `note_pending`).
909//
910// A reservation never settled expires after `RESERVATION_HOURS`.
911
912/// A reservation that is never settled stops holding after this long.
913pub const RESERVATION_HOURS: u64 = 3;
914/// What a ceiling reads as when there is none (g1t's own workspaces): a
915/// billion dollars, which JavaScript holds exactly.
916pub const UNLIMITED_MICROS: i64 = 1_000_000_000_000_000;
917
918/// What a workspace pays g1t on, as far as compute is concerned.
919#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
920#[serde(rename_all = "snake_case")]
921pub enum PlanKind {
922 /// No plan: the forge is free; compute only from a trial or g1t's
923 /// open-source pool, after a card check.
924 Free,
925 /// The g1t plan, paid for (or given by g1t staff without its price).
926 Paid,
927 /// g1t's own workspaces and Flagon's (comped terms): the plan without
928 /// being charged. Usage is still recorded at what it cost.
929 Internal,
930 /// Paid for by an enterprise account, invoiced.
931 Enterprise,
932}
933
934impl PlanKind {
935 pub fn as_str(self) -> &'static str {
936 match self {
937 PlanKind::Free => "free",
938 PlanKind::Paid => "paid",
939 PlanKind::Internal => "internal",
940 PlanKind::Enterprise => "enterprise",
941 }
942 }
943
944 /// Whether usage past what is included may be charged (on demand).
945 pub fn on_demand(self) -> bool {
946 !matches!(self, PlanKind::Free)
947 }
948}
949
950/// What compute is for.
951#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
952#[serde(rename_all = "snake_case")]
953pub enum ComputeKind {
954 /// An agent's run: its sandbox and its model.
955 Agent,
956 /// Checks on a pull request.
957 Check,
958 /// A workflow job.
959 Workflow,
960 /// The merge queue's checks.
961 Queue,
962 /// A deployment's build.
963 Deploy,
964 /// Semantic search: embeddings in the context hub.
965 Embedding,
966}
967
968impl ComputeKind {
969 pub fn as_str(self) -> &'static str {
970 match self {
971 ComputeKind::Agent => "agent",
972 ComputeKind::Check => "check",
973 ComputeKind::Workflow => "workflow",
974 ComputeKind::Queue => "queue",
975 ComputeKind::Deploy => "deploy",
976 ComputeKind::Embedding => "embedding",
977 }
978 }
979
980 /// Whether g1t's open-source pool may pay for it on a public
981 /// repository: checks, workflows and the merge queue only.
982 pub fn open_source_pool(self) -> bool {
983 matches!(self, ComputeKind::Check | ComputeKind::Workflow | ComputeKind::Queue)
984 }
985}
986
987/// Who pays first for reserved work. What the first source cannot cover
988/// falls to the next, in this order.
989#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
990#[serde(rename_all = "snake_case")]
991pub enum PaidBy {
992 /// The plan's included usage this month.
993 Credit,
994 /// The workspace's one-time trial credit.
995 Trial,
996 /// g1t's open-source pool.
997 Oss,
998 /// Charged to the workspace, at cost plus the margin.
999 OnDemand,
1000}
1001
1002/// `entitlements`: what a workspace may do now, for the services that
1003/// start compute and the pages that show it. Takes `EntitlementsArgs`;
1004/// returns `Entitlements`. No viewer: callers decide who sees it.
1005#[derive(Debug, Serialize, Deserialize)]
1006pub struct EntitlementsArgs {
1007 pub workspace: String,
1008}
1009
1010/// `audit_retention`: how many days of audit log each workspace keeps, for
1011/// the events service's daily purge. Takes `AuditRetentionArgs`; returns
1012/// `Vec<AuditRetention>`, one for each workspace asked about.
1013#[derive(Debug, Serialize, Deserialize)]
1014pub struct AuditRetentionArgs {
1015 pub workspaces: Vec<String>,
1016}
1017
1018#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1019pub struct AuditRetention {
1020 pub workspace: String,
1021 pub days: u32,
1022}
1023
1024#[derive(Clone, Debug, Serialize, Deserialize)]
1025#[serde(rename_all = "camelCase")]
1026pub struct Entitlements {
1027 pub workspace: String,
1028 pub plan: PlanKind,
1029 /// May start sandboxes, models, deployments and semantic search at all:
1030 /// paid, internal and enterprise workspaces, or a free one with trial
1031 /// credit left. A free workspace may still use the open-source pool
1032 /// for checks, workflows and the merge queue on public repositories
1033 /// after a card check; `reserve` decides that per start.
1034 pub compute: bool,
1035 /// The one-time trial credit left; 0 if none was granted or it is used.
1036 pub trial_micros_left: i64,
1037 /// A card check has been done. The trial and the open-source pool need
1038 /// it.
1039 pub trial_verified: bool,
1040 /// A paid workspace still in its first billing cycle.
1041 pub first_month: bool,
1042 /// Agents at once: 2 in the first month or on the trial, 10 after;
1043 /// staff can override it.
1044 pub max_concurrent_agents: u32,
1045 /// The longest one run may take: 60 minutes in the first month or on
1046 /// the trial; otherwise the guardrails' own caps (`MAX_MINUTES`).
1047 pub max_run_minutes: u32,
1048 /// One run's spend cap (`RUN_CAP_MICROS`, $2 by default); staff can
1049 /// override it.
1050 pub run_cap_micros: i64,
1051 /// What agents may spend on one issue in all (`ISSUE_CAP_MICROS`, $10
1052 /// by default); the owners can set it (`set_caps`), and staff override.
1053 pub issue_cap_micros: i64,
1054 /// Where on-demand work stops: g1t's ceiling on usage not yet paid
1055 /// for. `UNLIMITED_MICROS` for g1t's own workspaces; 0 for a free one,
1056 /// which has no on-demand usage.
1057 pub ceiling_micros: i64,
1058 /// Usage not yet paid for this month, with prepayment taken off.
1059 pub exposure_micros: i64,
1060 /// Why new compute is paused, for the owner: the limit is reached, a
1061 /// spend spike is waiting for an owner to confirm it, or g1t staff put
1062 /// a hold on it. None when it is not.
1063 pub paused: Option<String>,
1064 // What the workspace's plan gives it, for its pages.
1065 /// What open reservations hold now.
1066 #[serde(default)]
1067 pub held_micros: i64,
1068 /// Paid in advance and not used yet.
1069 #[serde(default)]
1070 pub prepaid_micros: i64,
1071 /// The plan's included usage each month, and what of it is used.
1072 #[serde(default)]
1073 pub included_micros: i64,
1074 #[serde(default)]
1075 pub included_used_micros: i64,
1076 /// How far back the audit log can be read and exported, and what is
1077 /// kept: the plan's days, or what g1t staff set for the account.
1078 pub audit_retention_days: u32,
1079 /// Whether `audit_retention_days` is what staff set for the account
1080 /// rather than the plan's.
1081 #[serde(default)]
1082 pub audit_retention_custom: bool,
1083 /// Private repository storage that is free for every workspace: past
1084 /// it, the plan pays for it and a free workspace's pushes stop.
1085 pub free_private_storage_bytes: i64,
1086 /// The last daily measure of the workspace's private repositories.
1087 pub private_storage_bytes: i64,
1088 /// On a paid plan (not Free): storage past the free amounts below is
1089 /// charged, so nothing is refused for it.
1090 #[serde(default)]
1091 pub has_plan: bool,
1092 /// Package storage free for every workspace, public and private: past
1093 /// it, the plan pays for it and a free workspace's pushes are refused.
1094 #[serde(default)]
1095 pub package_public_free_bytes: i64,
1096 #[serde(default)]
1097 pub package_private_free_bytes: i64,
1098 /// What g1t's open-source pool paid for the workspace this month.
1099 pub oss_paid_micros: i64,
1100 /// Deploy build time this month, every second of it metered.
1101 #[serde(default)]
1102 pub build_seconds_used: u32,
1103 /// Git operations this month, and how many are free for every
1104 /// workspace (past it: metered on the plan, slowed when free).
1105 #[serde(default)]
1106 pub git_operations: u64,
1107 #[serde(default)]
1108 pub git_operations_included: u64,
1109 /// The smallest amount a card is charged when a month closes.
1110 pub min_charge_micros: i64,
1111 /// A spend spike waiting for an owner, or decided.
1112 #[serde(default)]
1113 pub spike: Option<Spike>,
1114 /// Where usage stands against what is included and the limits, from 50%.
1115 #[serde(default)]
1116 pub alerts: Vec<UsageAlert>,
1117}
1118
1119/// One level reached: 50, 75, 90 or 100 percent of something.
1120#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1121#[serde(rename_all = "camelCase")]
1122pub struct UsageAlert {
1123 /// `included` (the plan's included usage), `spend_limit` (the owners'
1124 /// own limit) or `ceiling` (g1t's, on usage not yet paid for).
1125 pub meter: String,
1126 pub level: u32,
1127 pub used_micros: i64,
1128 pub limit_micros: i64,
1129 pub message: String,
1130}
1131
1132/// An hour's spend well above the workspace's usual pace: new compute
1133/// waits until an owner says to keep going.
1134#[derive(Clone, Debug, Serialize, Deserialize)]
1135#[serde(rename_all = "camelCase")]
1136pub struct Spike {
1137 pub id: String,
1138 /// `open` (waiting for an owner), `continued` (an owner said keep
1139 /// going) or `stopped` (an owner said stop).
1140 pub status: String,
1141 /// The hour's spend when it was found, and the usual hour's.
1142 pub hour_micros: i64,
1143 pub average_micros: i64,
1144 pub detected_at: String,
1145 #[serde(default)]
1146 pub decided_by: Option<String>,
1147 #[serde(default)]
1148 pub decided_at: Option<String>,
1149 /// While continued: until when, unless spend doubles again first.
1150 #[serde(default)]
1151 pub until: Option<String>,
1152}
1153
1154/// `reserve`: holds an estimate of a start's cost before the work starts.
1155/// Returns `Outcome<Reservation>`, or a failure whose code says why not:
1156///
1157/// - `paused`: a spend spike waiting for an owner, or a hold.
1158/// - `limit`: the spend limit or g1t's ceiling would be passed.
1159/// - `not_paid`: no plan, and nothing else pays for this kind of work (or
1160/// no card check yet).
1161/// - `trial_used`: the one-time trial is spent.
1162/// - `oss_pool_empty`: the open-source pool, or the repository's share of
1163/// it, is spent this month.
1164///
1165/// The message says exactly what to do, with the page to do it on (such as
1166/// `/acme/-/billing`).
1167#[derive(Debug, Serialize, Deserialize)]
1168#[serde(rename_all = "camelCase")]
1169pub struct ReserveArgs {
1170 pub workspace: String,
1171 pub repo: RepoPath,
1172 /// Whether the repository is public: the open-source pool pays only for
1173 /// public repositories' checks, workflows and merge queue.
1174 pub public: bool,
1175 pub kind: ComputeKind,
1176 /// The most the work is expected to cost g1t, before the margin, in
1177 /// millionths of a dollar (billing adds the margin, as it does to every
1178 /// charge). For an agent, its model's average plus its sandbox for its
1179 /// whole time cap.
1180 #[serde(alias = "estimate_micros")]
1181 pub estimate_micros: i64,
1182 /// An agent run on g1t's hosted models (not the workspace's own
1183 /// provider). Unsaid, an agent run is taken to be one. g1t's daily
1184 /// spend breaker pauses these when g1t is paying for them.
1185 #[serde(default, alias = "hosted_model")]
1186 pub hosted_model: Option<bool>,
1187}
1188
1189#[derive(Clone, Debug, Serialize, Deserialize)]
1190#[serde(rename_all = "camelCase")]
1191pub struct Reservation {
1192 pub id: String,
1193 pub paid_by: PaidBy,
1194 /// What is held, at cost; less than the estimate when a free
1195 /// workspace's last bit of trial credit is all there is.
1196 #[serde(default)]
1197 pub held_micros: i64,
1198 /// RFC 3339: when the hold lapses if never settled.
1199 #[serde(default)]
1200 pub expires_at: String,
1201}
1202
1203/// `settle`: releases a reservation's hold with what the work cost. The
1204/// charge goes on the ledger the usual way. Safe to repeat. Returns
1205/// `Outcome<bool>`: false if it was settled or had lapsed before.
1206#[derive(Debug, Serialize, Deserialize)]
1207#[serde(rename_all = "camelCase")]
1208pub struct SettleArgs {
1209 #[serde(alias = "reservation_id")]
1210 pub reservation_id: String,
1211 /// What the work cost g1t, before the margin.
1212 #[serde(alias = "actual_micros")]
1213 pub actual_micros: i64,
1214}
1215
1216// --- Card checks, the plan, prepayment -------------------------------------
1217
1218/// `card_check`: starts Stripe's page to save and verify a card: a setup
1219/// with 3-D Secure where the card supports it, which the card's bank sees
1220/// as a $0 or $1 authorization that is never charged. The trial and the
1221/// open-source pool need it, and it is the card the plan uses. Owners only.
1222/// Returns `Outcome<Checkout>`; the page's id comes back to `return_url` as
1223/// `session`, for `confirm_card_check`.
1224#[derive(Debug, Serialize, Deserialize)]
1225#[serde(rename_all = "camelCase")]
1226pub struct CardCheckArgs {
1227 pub actor: User,
1228 pub workspace: String,
1229 #[serde(alias = "return_url")]
1230 pub return_url: String,
1231}
1232
1233/// `confirm_card_check`: records the check once Stripe says the card was
1234/// verified, and grants the trial if the month's pool has room and the card
1235/// has not had one before. Safe to repeat. Returns `Outcome<Entitlements>`.
1236#[derive(Debug, Serialize, Deserialize)]
1237pub struct ConfirmCardCheckArgs {
1238 pub workspace: String,
1239 pub viewer: Viewer,
1240 pub session: String,
1241}
1242
1243// --- Limits: raising them, and spikes ---------------------------------------
1244
1245/// A request to g1t: a higher limit, or help with usage that went past
1246/// what was meant.
1247#[derive(Clone, Debug, Serialize, Deserialize)]
1248#[serde(rename_all = "camelCase")]
1249pub struct LimitRequest {
1250 pub id: String,
1251 pub workspace: String,
1252 /// `limit` (raise my limit) or `overage` (spent more than meant to).
1253 pub kind: String,
1254 /// The limit asked for; for an overage, what they think went wrong.
1255 pub amount_micros: i64,
1256 pub reason: String,
1257 pub expected_monthly_micros: i64,
1258 /// `open`, `approved` or `declined`.
1259 pub status: String,
1260 /// What was approved, which may differ from what was asked.
1261 #[serde(default)]
1262 pub decided_micros: Option<i64>,
1263 #[serde(default)]
1264 pub decided_by: Option<String>,
1265 /// The answer, as the owner sees it.
1266 #[serde(default)]
1267 pub answer: Option<String>,
1268 pub created_by: String,
1269 pub created_at: String,
1270 #[serde(default)]
1271 pub decided_at: Option<String>,
1272}
1273
1274/// `request_limit`: an owner asks g1t for more, or for help with usage past
1275/// what they meant. Answered within one business day, in the app and by
1276/// email. Owners only. Returns `Outcome<LimitRequest>`.
1277#[derive(Debug, Serialize, Deserialize)]
1278#[serde(rename_all = "camelCase")]
1279pub struct RequestLimitArgs {
1280 pub actor: User,
1281 pub workspace: String,
1282 /// `limit` or `overage`.
1283 pub kind: String,
1284 #[serde(alias = "amount_micros")]
1285 pub amount_micros: i64,
1286 pub reason: String,
1287 #[serde(default, alias = "expected_monthly_micros")]
1288 pub expected_monthly_micros: i64,
1289}
1290
1291/// `limit_requests`: a workspace's requests, newest first. Members only.
1292/// Returns `Outcome<Vec<LimitRequest>>`.
1293#[derive(Debug, Serialize, Deserialize)]
1294pub struct LimitRequestsArgs {
1295 pub workspace: String,
1296 pub viewer: Viewer,
1297}
1298
1299/// `confirm_spike`: an owner's answer to a spend spike. Keep going lifts the
1300/// pause for 24 hours, or until the hour's spend doubles again; stop keeps
1301/// new compute paused until an owner says to keep going. Owners only.
1302/// Returns `Outcome<Entitlements>`.
1303#[derive(Debug, Serialize, Deserialize)]
1304#[serde(rename_all = "camelCase")]
1305pub struct ConfirmSpikeArgs {
1306 pub actor: User,
1307 pub workspace: String,
1308 #[serde(alias = "keep_going")]
1309 pub keep_going: bool,
1310}
1311
1312/// `set_caps`: the owners' own caps on agents: one run's spend ($0.10 to
1313/// $100) and what the agents on one issue may spend in all ($1 to $1,000).
1314/// None goes back to the default ($2 and $10). A cap g1t staff set for the
1315/// account wins over both. Owners only. Returns `Outcome<Entitlements>`.
1316#[derive(Debug, Serialize, Deserialize)]
1317#[serde(rename_all = "camelCase")]
1318pub struct SetCapsArgs {
1319 pub actor: User,
1320 pub workspace: String,
1321 #[serde(default, alias = "run_cap_micros")]
1322 pub run_cap_micros: Option<i64>,
1323 #[serde(default, alias = "issue_cap_micros")]
1324 pub issue_cap_micros: Option<i64>,
1325}
1326
1327/// What staff see beside a request: the workspace's history with g1t.
1328#[derive(Clone, Debug, Default, Serialize, Deserialize)]
1329#[serde(rename_all = "camelCase")]
1330pub struct WorkspaceHistory {
1331 pub plan: Option<PlanKind>,
1332 /// The last six months, oldest first.
1333 pub months: Vec<MonthFigures>,
1334 /// Live payments that have cleared, and how many.
1335 pub paid_cleared_micros: i64,
1336 pub payments: u32,
1337 pub disputes: u32,
1338 pub declines: u32,
1339 /// The first time the workspace appears in billing, RFC 3339.
1340 pub first_seen: Option<String>,
1341 pub ceiling_micros: Option<i64>,
1342 pub max_ceiling_micros: Option<i64>,
1343 pub spend_limit_micros: Option<i64>,
1344 /// Recent velocity: the last hour, the usual hour over the last week,
1345 /// and the last 24 hours, at price.
1346 pub last_hour_micros: i64,
1347 pub average_hour_micros: i64,
1348 pub last_day_micros: i64,
1349}
1350
1351#[derive(Clone, Debug, Serialize, Deserialize)]
1352#[serde(rename_all = "camelCase")]
1353pub struct LimitRequestReview {
1354 pub request: LimitRequest,
1355 pub history: WorkspaceHistory,
1356}
1357
1358/// `admin_limit_requests`: requests for staff, oldest open first. Returns
1359/// `Vec<LimitRequestReview>`.
1360#[derive(Debug, Default, Serialize, Deserialize)]
1361pub struct AdminLimitRequestsArgs {
1362 /// `open` (the default), `approved`, `declined` or `all`.
1363 #[serde(default)]
1364 pub status: Option<String>,
1365}
1366
1367/// `admin_decide_limit_request`: approve (at the amount asked, or
1368/// `amount_micros`) or decline. The owner is told in the app and by email.
1369/// Recorded with who and why. Returns `Outcome<LimitRequest>`.
1370#[derive(Debug, Serialize, Deserialize)]
1371pub struct AdminDecideLimitRequestArgs {
1372 pub id: String,
1373 /// `approve` or `decline`.
1374 pub decision: String,
1375 #[serde(default)]
1376 pub amount_micros: Option<i64>,
1377 /// What the owner is told, beside the decision.
1378 #[serde(default)]
1379 pub note: String,
1380 pub by: String,
1381}
1382
1383/// `admin_record_payment`: money that reached g1t outside the card pages,
1384/// such as a bank transfer, entered as a payment (it raises the limit like
1385/// one). Recorded with who and the transfer's reference. Returns
1386/// `Outcome<LedgerEntry>`.
1387#[derive(Debug, Serialize, Deserialize)]
1388pub struct AdminRecordPaymentArgs {
1389 pub workspace: String,
1390 pub amount_micros: i64,
1391 /// The bank's reference for the transfer, or Stripe's payment id.
1392 pub reference: String,
1393 pub note: String,
1394 pub by: String,
1395}
1396
1397// --- Overages and goodwill (sudo) --------------------------------------------
1398
1399/// What a one-time goodwill credit would come to: g1t's margin on the
1400/// overage, always, plus as much of its underlying cost as the cap allows.
1401#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1402#[serde(rename_all = "camelCase")]
1403pub struct Goodwill {
1404 /// This month's charges above the workspace's typical month.
1405 pub overage_micros: i64,
1406 /// The part of the overage that is g1t's margin.
1407 pub margin_micros: i64,
1408 /// The part that is what g1t paid its providers.
1409 pub cost_micros: i64,
1410 /// The one-click credit: the margin plus the cost up to the cap.
1411 pub credit_micros: i64,
1412 /// Of the credit, the real cost g1t absorbs.
1413 pub absorbed_micros: i64,
1414}
1415
1416/// A workspace whose month went well past its usual, or hit a spike.
1417#[derive(Clone, Debug, Serialize, Deserialize)]
1418#[serde(rename_all = "camelCase")]
1419pub struct Overage {
1420 pub workspace: String,
1421 pub plan: PlanKind,
1422 /// The median of its last three months' charges.
1423 pub typical_month_micros: i64,
1424 pub this_month_micros: i64,
1425 /// What this month cost g1t, and what g1t keeps of it.
1426 pub cost_micros: i64,
1427 pub margin_micros: i64,
1428 /// A spike this month, if there was one.
1429 pub spike: Option<Spike>,
1430 /// The runs that cost the most this month.
1431 pub top_entries: Vec<LedgerEntry>,
1432 pub goodwill: Goodwill,
1433 /// False when a goodwill credit was given in the last 12 months.
1434 pub goodwill_available: bool,
1435 pub last_goodwill_at: Option<String>,
1436 /// An open overage request from the owner, if there is one.
1437 pub request: Option<LimitRequest>,
1438}
1439
1440/// `admin_overages`: the Overages queue. Returns `Vec<Overage>`.
1441#[derive(Debug, Default, Serialize, Deserialize)]
1442pub struct AdminOveragesArgs {}
1443
1444/// `admin_goodwill`: credits a workspace for accidental usage. With no
1445/// amount, the one-click credit (`Goodwill::credit_micros`), once per
1446/// workspace in 12 months. A larger amount, or a second within 12 months,
1447/// needs a typed reason. It shows on the statement as "Credit from g1t:
1448/// accidental usage on <date>". Returns `Outcome<LedgerEntry>`.
1449#[derive(Debug, Serialize, Deserialize)]
1450pub struct AdminGoodwillArgs {
1451 pub workspace: String,
1452 #[serde(default)]
1453 pub amount_micros: Option<i64>,
1454 /// Why, typed by staff; needed past the one-click credit.
1455 #[serde(default)]
1456 pub reason: String,
1457 /// The day the accidental usage happened, `YYYY-MM-DD`; today if absent.
1458 #[serde(default)]
1459 pub day: Option<String>,
1460 pub by: String,
1461}
1462
1463/// One workspace's recent pace, for sudo's velocity view.
1464#[derive(Clone, Debug, Serialize, Deserialize)]
1465#[serde(rename_all = "camelCase")]
1466pub struct Velocity {
1467 pub workspace: String,
1468 pub plan: PlanKind,
1469 pub last_hour_micros: i64,
1470 pub average_hour_micros: i64,
1471 pub last_day_micros: i64,
1472 pub this_month_micros: i64,
1473 /// The last hour over the usual hour; 0 with no history.
1474 pub ratio: f64,
1475 pub spike: Option<Spike>,
1476 pub first_seen: Option<String>,
1477}
1478
1479/// `admin_velocity`: workspaces spending in the last day, fastest first.
1480/// Returns `Vec<Velocity>`.
1481#[derive(Debug, Default, Serialize, Deserialize)]
1482pub struct AdminVelocityArgs {}
1483
1484#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1485#[serde(rename_all = "snake_case")]
1486pub enum AccountKind {
1487 Workspace,
1488 Enterprise,
1489}
1490
1491/// How an account is charged. Standard unless g1t set otherwise in sudo.
1492#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1493#[serde(rename_all = "camelCase")]
1494pub struct Terms {
1495 pub kind: TermsKind,
1496 /// Off every usage charge, in percent. Custom terms only.
1497 #[serde(default)]
1498 pub discount_percent: u32,
1499 /// A ceiling on unpaid usage that replaces the one trust would give.
1500 #[serde(default)]
1501 pub ceiling_micros: Option<i64>,
1502 /// Why, for whoever looks next.
1503 #[serde(default)]
1504 pub note: String,
1505 /// When the terms end and the account goes back to standard.
1506 #[serde(default)]
1507 pub until: Option<String>,
1508 #[serde(default)]
1509 pub set_by: Option<String>,
1510 #[serde(default)]
1511 pub set_at: Option<String>,
1512}
1513
1514impl Terms {
1515 pub fn standard() -> Self {
1516 Terms {
1517 kind: TermsKind::Standard,
1518 discount_percent: 0,
1519 ceiling_micros: None,
1520 note: String::new(),
1521 until: None,
1522 set_by: None,
1523 set_at: None,
1524 }
1525 }
1526
1527 /// What a charge becomes under these terms.
1528 pub fn apply(&self, charge_micros: i64) -> i64 {
1529 match self.kind {
1530 TermsKind::Comped => 0,
1531 TermsKind::Custom => charge_micros * i64::from(100 - self.discount_percent.min(100)) / 100,
1532 TermsKind::Standard => charge_micros,
1533 }
1534 }
1535
1536 /// What a charge at cost plus the margin becomes under these terms, and
1537 /// how much of it g1t gives away by a discount: a sold charge is never
1538 /// below its cost plus the margin unless the difference is counted as
1539 /// given (`ledger.discount_micros`), never lost. Comped terms give it
1540 /// all, and are counted as comped elsewhere, so their given part is 0
1541 /// here.
1542 pub fn discounted(&self, charge_micros: i64) -> (i64, i64) {
1543 let charged = self.apply(charge_micros);
1544 match self.kind {
1545 TermsKind::Custom => (charged, (charge_micros - charged).max(0)),
1546 TermsKind::Comped | TermsKind::Standard => (charged, 0),
1547 }
1548 }
1549}
1550
1551#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1552#[serde(rename_all = "snake_case")]
1553pub enum TermsKind {
1554 /// Prices as published, limits by trust.
1555 Standard,
1556 /// Nothing charged; usage still recorded with its cost. Paid features
1557 /// are on without a plan. For g1t's own workspaces, partners, and the
1558 /// like.
1559 Comped,
1560 /// A discount, a ceiling, or both.
1561 Custom,
1562}
1563
1564/// `stripe_webhook`: an event from Stripe, as the API received it: the raw
1565/// body and its `Stripe-Signature` header. Billing checks the signature
1566/// against the secret of the endpoint it registered, and handles each
1567/// event once. Returns `Outcome<bool>`: false for one already handled.
1568#[derive(Debug, Serialize, Deserialize)]
1569pub struct StripeWebhookArgs {
1570 pub payload: String,
1571 pub signature: String,
1572}
1573
1574/// `admin_stripe`: where billing stands with Stripe. Staff only. Returns
1575/// `StripeStatus`. With `fix: true`, first enables the destination at
1576/// billing's address and gives it the events billing needs.
1577#[derive(Debug, Default, Serialize, Deserialize)]
1578pub struct AdminStripeArgs {
1579 #[serde(default)]
1580 pub fix: bool,
1581 #[serde(default)]
1582 pub by: Option<String>,
1583}
1584
1585#[derive(Clone, Debug, Serialize, Deserialize)]
1586#[serde(rename_all = "camelCase")]
1587pub struct StripeStatus {
1588 /// `test` or `live`, from the key; `off` without one.
1589 pub mode: String,
1590 /// Whether `STRIPE_WEBHOOK_SECRET` is set, so events can be checked.
1591 pub secret_set: bool,
1592 /// The destination at billing's address in Stripe, as Stripe has it.
1593 pub webhook: Option<StripeWebhook>,
1594 /// Events billing handles that the destination does not send.
1595 pub missing_events: Vec<String>,
1596 /// The latest events handled, newest first.
1597 pub recent_events: Vec<StripeEventSummary>,
1598 /// What went wrong reading or fixing the destination, if it did.
1599 pub error: Option<String>,
1600}
1601
1602#[derive(Clone, Debug, Serialize, Deserialize)]
1603#[serde(rename_all = "camelCase")]
1604pub struct StripeWebhook {
1605 pub url: String,
1606 pub endpoint_id: String,
1607 /// `enabled` or `disabled`.
1608 pub status: String,
1609 pub events: Vec<String>,
1610 pub created_at: String,
1611}
1612
1613#[derive(Clone, Debug, Serialize, Deserialize)]
1614#[serde(rename_all = "camelCase")]
1615pub struct StripeEventSummary {
1616 pub id: String,
1617 pub kind: String,
1618 pub outcome: String,
1619 pub received_at: String,
1620}
1621
1622/// `admin_enterprise_billing`: where an enterprise's invoices go. Creates
1623/// or updates its Stripe customer. Returns `Outcome<BillingAccount>`.
1624#[derive(Debug, Serialize, Deserialize)]
1625pub struct AdminEnterpriseBillingArgs {
1626 pub id: String,
1627 pub email: String,
1628 pub by: String,
1629}
1630
1631/// `admin_invoice_enterprise`: sends an enterprise its invoice now, for
1632/// what its workspaces owe, rather than waiting for the month to close.
1633/// Returns `Outcome<EnterpriseInvoice>`.
1634#[derive(Debug, Serialize, Deserialize)]
1635pub struct AdminInvoiceEnterpriseArgs {
1636 pub id: String,
1637 pub by: String,
1638}
1639
1640/// An enterprise's invoice: one line per workspace, paid on Stripe.
1641#[derive(Clone, Debug, Serialize, Deserialize)]
1642#[serde(rename_all = "camelCase")]
1643pub struct EnterpriseInvoice {
1644 pub invoice_id: String,
1645 /// Stripe's page for it, where it is paid.
1646 pub hosted_url: Option<String>,
1647 pub amount_micros: i64,
1648 /// `open`, `paid`, `overdue` or `void`.
1649 pub status: String,
1650 pub period: String,
1651 pub lines: Vec<InvoiceLine>,
1652 pub created_at: String,
1653}
1654
1655#[derive(Clone, Debug, Serialize, Deserialize)]
1656#[serde(rename_all = "camelCase")]
1657pub struct InvoiceLine {
1658 pub workspace: String,
1659 pub amount_micros: i64,
1660}
1661
1662/// A workspace's invoice from g1t: one per month, and one each time it is
1663/// charged near its limit. Itemised, charged to the card on file, and kept
1664/// in Stripe's billing page with its PDF.
1665#[derive(Clone, Debug, Serialize, Deserialize)]
1666#[serde(rename_all = "camelCase")]
1667pub struct WorkspaceInvoice {
1668 pub invoice_id: String,
1669 pub workspace: String,
1670 /// `month` (2026-10) or `threshold`.
1671 pub reason: String,
1672 pub period: String,
1673 pub amount_micros: i64,
1674 /// `paid`, `open`, `failed` or `void`.
1675 pub status: String,
1676 pub hosted_url: Option<String>,
1677 pub pdf_url: Option<String>,
1678 pub lines: Vec<InvoiceItem>,
1679 pub created_at: String,
1680}
1681
1682#[derive(Clone, Debug, Serialize, Deserialize)]
1683#[serde(rename_all = "camelCase")]
1684pub struct InvoiceItem {
1685 pub description: String,
1686 pub amount_micros: i64,
1687}
1688
1689/// `invoices`: a workspace's invoices from g1t, newest first. Members
1690/// only. Returns `Outcome<Vec<WorkspaceInvoice>>`.
1691#[derive(Debug, Serialize, Deserialize)]
1692pub struct InvoicesArgs {
1693 pub workspace: String,
1694 pub viewer: Viewer,
1695}
1696
1697/// `admin_workspace_invoices`: the same, for staff. Returns
1698/// `Vec<WorkspaceInvoice>`.
1699#[derive(Debug, Serialize, Deserialize)]
1700pub struct AdminWorkspaceInvoicesArgs {
1701 pub workspace: String,
1702}
1703
1704/// `statement`: a month of a workspace's ledger, grouped by day (or by
1705/// project) with a line per kind of charge. Members only. Returns
1706/// `Outcome<Statement>`.
1707#[derive(Debug, Serialize, Deserialize)]
1708pub struct StatementArgs {
1709 pub workspace: String,
1710 pub viewer: Viewer,
1711 /// YYYY-MM; this month when absent.
1712 #[serde(default)]
1713 pub month: Option<String>,
1714 /// `day` (the default) or `project`.
1715 #[serde(default)]
1716 pub group: Option<String>,
1717}
1718
1719#[derive(Clone, Debug, Serialize, Deserialize)]
1720#[serde(rename_all = "camelCase")]
1721pub struct Statement {
1722 pub month: String,
1723 /// Months with any entries, newest first.
1724 pub months: Vec<String>,
1725 pub groups: Vec<StatementGroup>,
1726 pub totals: StatementTotals,
1727}
1728
1729#[derive(Clone, Debug, Serialize, Deserialize)]
1730#[serde(rename_all = "camelCase")]
1731pub struct StatementGroup {
1732 /// The day (YYYY-MM-DD) or the project (`owner/name`, or empty).
1733 pub key: String,
1734 pub label: String,
1735 pub lines: Vec<StatementLine>,
1736 /// What the group's charges come to.
1737 pub charged_micros: i64,
1738}
1739
1740#[derive(Clone, Debug, Serialize, Deserialize)]
1741#[serde(rename_all = "camelCase")]
1742pub struct StatementLine {
1743 /// Agent runs, Sandbox time, Deployments, Payments, Credits from g1t,
1744 /// Refunds, and, for older entries, Runs on your own model provider.
1745 pub kind: String,
1746 pub count: u32,
1747 /// Charges positive; money in (payments, credits) negative.
1748 pub charged_micros: i64,
1749 pub cost_micros: i64,
1750 /// Of the usage on the line, what was paid for before it was charged:
1751 /// by the plan's included usage, the trial credit, g1t's open-source
1752 /// pool, or g1t itself. Not in `charged_micros`.
1753 #[serde(default)]
1754 pub covered_micros: i64,
1755}
1756
1757#[derive(Clone, Debug, Serialize, Deserialize)]
1758#[serde(rename_all = "camelCase")]
1759pub struct StatementTotals {
1760 pub charged_micros: i64,
1761 pub paid_micros: i64,
1762 pub cost_micros: i64,
1763 pub entries: u32,
1764 /// What paid for usage before it was charged, one line per source,
1765 /// such as "Paid by g1t's open-source pool".
1766 #[serde(default)]
1767 pub covered: Vec<Covered>,
1768 /// Owed when the month closed but under the minimum charge, so it
1769 /// carries over to the next invoice. Zero when nothing carried.
1770 #[serde(default)]
1771 pub carried_micros: i64,
1772}
1773
1774/// One source that paid for usage before it was charged.
1775#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1776#[serde(rename_all = "camelCase")]
1777pub struct Covered {
1778 /// `included`, `trial`, `oss_pool` or `given`.
1779 pub source: String,
1780 /// "Paid by your plan's included usage", "Paid by your trial credit",
1781 /// "Paid by g1t's open-source pool", "Covered by g1t".
1782 pub label: String,
1783 pub micros: i64,
1784}
1785
1786/// `statement_entries`: one statement line's entries, newest first, 50 at
1787/// a time (`before` = the last id seen). Returns `Outcome<Vec<LedgerEntry>>`.
1788#[derive(Debug, Serialize, Deserialize)]
1789pub struct StatementEntriesArgs {
1790 pub workspace: String,
1791 pub viewer: Viewer,
1792 pub month: String,
1793 pub kind: String,
1794 #[serde(default)]
1795 pub day: Option<String>,
1796 #[serde(default)]
1797 pub project: Option<String>,
1798 #[serde(default)]
1799 pub before: Option<String>,
1800}
1801
1802// --- Sales (sudo.g1t.sh) ------------------------------------------------------
1803//
1804// What staff need to know to reach out: who is growing, who is close to
1805// their limit, who was declined, who has become a steady customer. And what
1806// was done about it: a stage, an owner on g1t's side, a next step, notes.
1807
1808/// Why a workspace is worth a look.
1809#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1810#[serde(rename_all = "snake_case")]
1811pub enum SignalKind {
1812 /// At its limit, or its own spend limit: work is stopped.
1813 AtLimit,
1814 /// Past 80% of what is available to it: about to need more.
1815 NearCeiling,
1816 /// Its card was declined or a payment disputed.
1817 Declined,
1818 /// This month is well ahead of last month.
1819 Growing,
1820 /// Became Established: the ceiling now follows its spend.
1821 Established,
1822 /// Paid g1t for the first time.
1823 FirstPayment,
1824 /// Spending enough that custom terms or an enterprise may suit it.
1825 HighSpend,
1826 /// Costs g1t more on Cloudflare than it pays, over 30 days: a pricing
1827 /// gap or abuse to look at (billing's `margin`).
1828 CostOverRevenue,
1829}
1830
1831#[derive(Clone, Debug, Serialize, Deserialize)]
1832#[serde(rename_all = "camelCase")]
1833pub struct Signal {
1834 pub workspace: String,
1835 pub kind: SignalKind,
1836 /// One sentence, with the figures.
1837 pub detail: String,
1838 /// The figure that matters, such as this month's spend.
1839 pub value_micros: i64,
1840 /// Its sales stage, if staff gave it one.
1841 pub stage: Option<String>,
1842 pub owner: Option<String>,
1843 #[serde(default)]
1844 pub next_step: Option<String>,
1845 /// When the next step is due, `YYYY-MM-DD`.
1846 #[serde(default)]
1847 pub next_at: Option<String>,
1848}
1849
1850/// `admin_invoices`: every invoice g1t has sent, workspaces' and
1851/// enterprises', newest first. Returns `Vec<InvoiceSummary>`.
1852#[derive(Debug, Default, Serialize, Deserialize)]
1853pub struct AdminInvoicesArgs {
1854 /// `paid`, `open`, `failed`, `overdue` or `void`.
1855 #[serde(default)]
1856 pub status: Option<String>,
1857 /// YYYY-MM, by when it was sent.
1858 #[serde(default)]
1859 pub month: Option<String>,
1860}
1861
1862#[derive(Clone, Debug, Serialize, Deserialize)]
1863#[serde(rename_all = "camelCase")]
1864pub struct InvoiceSummary {
1865 pub invoice_id: String,
1866 /// `workspace` or `enterprise`.
1867 pub kind: String,
1868 /// The workspace's slug, or the enterprise's account id.
1869 pub account: String,
1870 /// What to call it: the workspace, or the enterprise's name.
1871 pub name: String,
1872 pub reason: String,
1873 pub period: String,
1874 pub amount_micros: i64,
1875 pub status: String,
1876 pub hosted_url: Option<String>,
1877 pub created_at: String,
1878 pub paid_at: Option<String>,
1879}
1880
1881/// `admin_audit`: every change made in sudo, and by Stripe, newest first.
1882/// Returns `Vec<AdminAction>`.
1883#[derive(Debug, Default, Serialize, Deserialize)]
1884pub struct AdminAuditArgs {
1885 #[serde(default)]
1886 pub by: Option<String>,
1887 #[serde(default)]
1888 pub action: Option<String>,
1889 /// Only those before this time, for paging.
1890 #[serde(default)]
1891 pub before: Option<String>,
1892}
1893
1894/// `admin_signals`: every workspace worth reaching out to, most urgent
1895/// first. Returns `Vec<Signal>`.
1896#[derive(Debug, Default, Serialize, Deserialize)]
1897pub struct AdminSignalsArgs {}
1898
1899/// What staff are doing about a workspace.
1900#[derive(Clone, Debug, Serialize, Deserialize)]
1901#[serde(rename_all = "camelCase")]
1902pub struct SalesRecord {
1903 pub workspace: String,
1904 /// `none`, `lead`, `contacted`, `negotiating`, `won`, `lost` or `churn_risk`.
1905 pub stage: String,
1906 /// The staff member looking after it.
1907 pub owner: Option<String>,
1908 pub next_step: Option<String>,
1909 /// RFC 3339 date.
1910 pub next_at: Option<String>,
1911 pub notes: Vec<SalesNote>,
1912 pub updated_at: Option<String>,
1913}
1914
1915#[derive(Clone, Debug, Serialize, Deserialize)]
1916#[serde(rename_all = "camelCase")]
1917pub struct SalesNote {
1918 pub id: String,
1919 pub text: String,
1920 pub by: String,
1921 pub created_at: String,
1922}
1923
1924/// `admin_sales`: a workspace's sales record. Returns `SalesRecord`.
1925#[derive(Debug, Serialize, Deserialize)]
1926pub struct AdminSalesArgs {
1927 pub workspace: String,
1928}
1929
1930/// `admin_set_sales`: its stage, owner and next step. Returns `Outcome<SalesRecord>`.
1931#[derive(Debug, Serialize, Deserialize)]
1932pub struct AdminSetSalesArgs {
1933 pub workspace: String,
1934 pub stage: String,
1935 #[serde(default)]
1936 pub owner: Option<String>,
1937 #[serde(default)]
1938 pub next_step: Option<String>,
1939 #[serde(default)]
1940 pub next_at: Option<String>,
1941 pub by: String,
1942}
1943
1944/// `admin_add_note`. Returns `Outcome<SalesRecord>`.
1945#[derive(Debug, Serialize, Deserialize)]
1946pub struct AdminAddNoteArgs {
1947 pub workspace: String,
1948 pub text: String,
1949 pub by: String,
1950}
1951
1952/// `admin_overview`: the business at a glance. Returns `Overview`.
1953#[derive(Debug, Default, Serialize, Deserialize)]
1954pub struct AdminOverviewArgs {}
1955
1956#[derive(Clone, Debug, Serialize, Deserialize)]
1957#[serde(rename_all = "camelCase")]
1958pub struct Overview {
1959 /// YYYY-MM.
1960 pub month: String,
1961 /// The last six months, oldest first, all workspaces together.
1962 pub months: Vec<MonthFigures>,
1963 /// This month by kind of usage: models, sandbox, deployments, plans.
1964 pub by_kind: Vec<KindFigures>,
1965 pub paying_workspaces: u32,
1966 pub stopped: u32,
1967 pub near_ceiling: u32,
1968 pub declined: u32,
1969 /// Sent and not yet paid, workspaces and enterprises.
1970 pub open_invoices_micros: i64,
1971 /// Follow-ups due today or earlier.
1972 pub follow_ups_due: u32,
1973 /// The capped budgets g1t pays from, this month.
1974 #[serde(default)]
1975 pub pools: Option<Pools>,
1976 /// This month's revenue: usage charged plus the plan's price paid.
1977 #[serde(default)]
1978 pub revenue_micros: i64,
1979 /// Workspaces on the paid plan now, and what their price comes to a
1980 /// month.
1981 #[serde(default)]
1982 pub active_plans: u32,
1983 #[serde(default)]
1984 pub plan_mrr_micros: i64,
1985 /// What g1t gave this month, by source, apart from its margin.
1986 #[serde(default)]
1987 pub given: Vec<GivenFigures>,
1988 /// g1t's own and Flagon's workspaces this month: what their use cost,
1989 /// and why they are not charged.
1990 #[serde(default)]
1991 pub internal: Vec<InternalUse>,
1992 /// Open limit requests, and workspaces in the Overages queue.
1993 #[serde(default)]
1994 pub open_requests: u32,
1995 #[serde(default)]
1996 pub overages: u32,
1997 /// Spend spikes waiting for an owner.
1998 #[serde(default)]
1999 pub open_spikes: u32,
2000}
2001
2002/// What g1t gave this month from one source.
2003#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
2004#[serde(rename_all = "camelCase")]
2005pub struct GivenFigures {
2006 /// `internal`, `trial`, `oss_pool`, `goodwill` or `covered`.
2007 pub source: String,
2008 pub label: String,
2009 /// At price, and what it cost g1t.
2010 pub micros: i64,
2011 pub cost_micros: i64,
2012}
2013
2014/// One internal workspace's use this month.
2015#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
2016#[serde(rename_all = "camelCase")]
2017pub struct InternalUse {
2018 pub workspace: String,
2019 /// Why it is not charged: its terms' note.
2020 pub reason: String,
2021 pub cost_micros: i64,
2022 pub entries: u32,
2023}
2024
2025/// g1t's capped budgets for free usage, this calendar month (UTC).
2026#[derive(Clone, Debug, Default, Serialize, Deserialize)]
2027#[serde(rename_all = "camelCase")]
2028pub struct Pools {
2029 /// YYYY-MM.
2030 pub month: String,
2031 /// Trial grants made this month, against the month's pool.
2032 pub trial_granted_micros: i64,
2033 pub trial_pool_micros: i64,
2034 pub trial_grants: u32,
2035 /// What the open-source pool paid this month, against its cap.
2036 pub oss_used_micros: i64,
2037 pub oss_pool_micros: i64,
2038 /// Each public repository's monthly cap on the pool.
2039 pub oss_repo_micros: i64,
2040}
2041
2042#[derive(Clone, Debug, Serialize, Deserialize)]
2043#[serde(rename_all = "camelCase")]
2044pub struct KindFigures {
2045 pub kind: String,
2046 pub charged_micros: i64,
2047 pub cost_micros: i64,
2048}
2049
2050// --- Staff (sudo.g1t.sh) ------------------------------------------------------
2051//
2052// Called only by the sudo app, which only g1t staff can reach (behind
2053// Cloudflare Access). Each change names who made it, and is kept in the
2054// audit log.
2055
2056/// `admin_accounts`: every billing account, with where each stands this
2057/// month. Returns `Vec<AccountSummary>`.
2058#[derive(Debug, Default, Serialize, Deserialize)]
2059pub struct AdminAccountsArgs {
2060 #[serde(default)]
2061 pub query: Option<String>,
2062 /// Exactly these workspaces' accounts, such as one page of sudo's
2063 /// list; every account with activity when absent.
2064 #[serde(default)]
2065 pub workspaces: Option<Vec<String>>,
2066}
2067
2068#[derive(Clone, Debug, Serialize, Deserialize)]
2069#[serde(rename_all = "camelCase")]
2070pub struct AccountSummary {
2071 pub account: BillingAccount,
2072 pub limit: Limit,
2073 /// Charged this month, after terms.
2074 pub charged_micros: i64,
2075 /// What this month's usage cost g1t.
2076 pub cost_micros: i64,
2077 /// Paid, ever.
2078 pub paid_micros: i64,
2079 /// The same figures for each of the account's workspaces that has
2080 /// any, so staff can see what one member of an enterprise used.
2081 #[serde(default)]
2082 pub by_workspace: Vec<WorkspaceFigures>,
2083 /// The last six months, oldest first, for trends.
2084 #[serde(default)]
2085 pub months: Vec<MonthFigures>,
2086}
2087
2088/// One month of an account's billing.
2089#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
2090#[serde(rename_all = "camelCase")]
2091pub struct MonthFigures {
2092 /// YYYY-MM.
2093 pub month: String,
2094 /// Usage charged, after what paid for it first.
2095 pub charged_micros: i64,
2096 /// What usage cost g1t: only what g1t paid for, never a workspace's own
2097 /// model provider.
2098 pub cost_micros: i64,
2099 pub paid_micros: i64,
2100 /// The plan's monthly price, paid.
2101 #[serde(default)]
2102 pub plans_micros: i64,
2103 /// What g1t gave, at price: internal (comped) use, trials, the
2104 /// open-source pool, goodwill credits and what g1t covered. Not margin.
2105 #[serde(default)]
2106 pub given_micros: i64,
2107}
2108
2109/// One workspace's share of an [`AccountSummary`].
2110#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
2111#[serde(rename_all = "camelCase")]
2112pub struct WorkspaceFigures {
2113 pub workspace: String,
2114 pub charged_micros: i64,
2115 pub cost_micros: i64,
2116 pub paid_micros: i64,
2117}
2118
2119/// `admin_account`: one account in full. Returns `Outcome<AccountDetail>`.
2120#[derive(Debug, Serialize, Deserialize)]
2121pub struct AdminAccountArgs {
2122 /// An account id, or a workspace slug.
2123 pub id: String,
2124}
2125
2126#[derive(Clone, Debug, Serialize, Deserialize)]
2127#[serde(rename_all = "camelCase")]
2128pub struct AccountDetail {
2129 pub summary: AccountSummary,
2130 /// Each workspace's limit, for an enterprise.
2131 pub workspaces: Vec<Limit>,
2132 pub ledger: Vec<LedgerEntry>,
2133 pub audit: Vec<AdminAction>,
2134}
2135
2136/// `admin_set_terms`. Returns `Outcome<BillingAccount>`.
2137#[derive(Debug, Serialize, Deserialize)]
2138pub struct AdminSetTermsArgs {
2139 pub id: String,
2140 pub terms: Terms,
2141 pub by: String,
2142}
2143
2144/// `admin_create_enterprise`. Returns `Outcome<BillingAccount>`.
2145#[derive(Debug, Serialize, Deserialize)]
2146pub struct AdminCreateEnterpriseArgs {
2147 pub name: String,
2148 pub workspaces: Vec<String>,
2149 pub by: String,
2150}
2151
2152/// `admin_attach`: moves a workspace onto an enterprise account, or back
2153/// onto its own with `account: None`. Returns `Outcome<BillingAccount>`.
2154#[derive(Debug, Serialize, Deserialize)]
2155pub struct AdminAttachArgs {
2156 pub workspace: String,
2157 pub account: Option<String>,
2158 pub by: String,
2159}
2160
2161/// `admin_credit`: money g1t gives a workspace, such as a refund or a
2162/// goodwill credit. Returns `Outcome<LedgerEntry>`.
2163#[derive(Debug, Serialize, Deserialize)]
2164pub struct AdminCreditArgs {
2165 pub workspace: String,
2166 pub amount_micros: i64,
2167 pub note: String,
2168 pub by: String,
2169}
2170
2171/// `admin_reset_billing`: a test workspace's billing wiped, so it starts
2172/// again as a new customer. Only while billing runs on Stripe's test key;
2173/// never a comped workspace or one an enterprise pays for. `confirm` is the
2174/// workspace's slug typed out. Returns `Outcome<BillingReset>`.
2175#[derive(Debug, Serialize, Deserialize)]
2176pub struct AdminResetBillingArgs {
2177 pub workspace: String,
2178 pub confirm: String,
2179 pub note: String,
2180 pub by: String,
2181}
2182
2183/// What a reset removed.
2184#[derive(Clone, Debug, Serialize, Deserialize)]
2185#[serde(rename_all = "camelCase")]
2186pub struct BillingReset {
2187 pub workspace: String,
2188 pub rows: u32,
2189 /// Whether the costs analysis ran again after it, so the margin
2190 /// figures no longer hold the workspace's past usage.
2191 #[serde(default)]
2192 pub refreshed: bool,
2193}
2194
2195/// One change made in sudo.
2196#[derive(Clone, Debug, Serialize, Deserialize)]
2197#[serde(rename_all = "camelCase")]
2198pub struct AdminAction {
2199 pub id: String,
2200 pub account: String,
2201 pub action: String,
2202 pub detail: String,
2203 pub by: String,
2204 pub created_at: String,
2205}
2206
2207/// What a feature's plan costs and includes.
2208#[derive(Clone, Debug, Serialize, Deserialize)]
2209#[serde(rename_all = "camelCase")]
2210pub struct Plan {
2211 pub feature: Feature,
2212 pub title: String,
2213 /// Charged every month while the plan is on, in cents.
2214 pub monthly_cents: u32,
2215 /// What the monthly price includes, one line each, for people to read.
2216 pub includes: Vec<String>,
2217 /// How usage past the allowance is charged, for people to read.
2218 pub overage: String,
2219}
2220
2221#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
2222#[serde(rename_all = "snake_case")]
2223pub enum SubscriptionStatus {
2224 /// Paid up; the feature works.
2225 Active,
2226 /// Paid up to the end of the period, and ends then.
2227 Canceling,
2228 /// The last payment failed; the feature is off until it is paid.
2229 PastDue,
2230 /// Ended.
2231 Canceled,
2232}
2233
2234impl SubscriptionStatus {
2235 /// Whether the feature works in this state.
2236 pub fn on(self) -> bool {
2237 matches!(self, SubscriptionStatus::Active | SubscriptionStatus::Canceling)
2238 }
2239}
2240
2241/// A workspace's plan for one feature.
2242#[derive(Clone, Debug, Serialize, Deserialize)]
2243#[serde(rename_all = "camelCase")]
2244pub struct Subscription {
2245 pub feature: Feature,
2246 pub status: SubscriptionStatus,
2247 /// RFC 3339: when the period paid for ends, and the plan renews or
2248 /// ends.
2249 pub period_end: Option<String>,
2250 /// Username of whoever turned it on.
2251 pub started_by: String,
2252 /// RFC 3339.
2253 pub started_at: String,
2254}
2255
2256/// A feature as a workspace sees it: what it costs, and its plan if it has
2257/// one.
2258#[derive(Clone, Debug, Serialize, Deserialize)]
2259#[serde(rename_all = "camelCase")]
2260pub struct FeatureState {
2261 pub plan: Plan,
2262 pub subscription: Option<Subscription>,
2263 /// Whether the feature works for the workspace now.
2264 pub on: bool,
2265 /// On without a plan: comped terms, or given by g1t. Nothing to pay
2266 /// and nothing to turn off.
2267 #[serde(default)]
2268 pub included: bool,
2269}
2270
2271/// `features`: every paid feature and the workspace's plan for each.
2272/// Members only. Returns `Outcome<Vec<FeatureState>>`.
2273#[derive(Debug, Serialize, Deserialize)]
2274pub struct FeaturesArgs {
2275 pub workspace: String,
2276 pub viewer: Viewer,
2277}
2278
2279/// `subscribe`: starts the card page for a feature's monthly plan. Owners
2280/// only. Returns `Outcome<Checkout>`; the page's id comes back to
2281/// `return_url` as `session`, for `confirm_subscription`.
2282#[derive(Debug, Serialize, Deserialize)]
2283#[serde(rename_all = "camelCase")]
2284pub struct SubscribeArgs {
2285 pub actor: User,
2286 pub workspace: String,
2287 pub feature: Feature,
2288 pub return_url: String,
2289}
2290
2291/// `confirm_subscription`: turns the feature on once the processor says
2292/// the plan was paid for. Safe to call any number of times. Returns
2293/// `Outcome<FeatureState>`.
2294#[derive(Debug, Serialize, Deserialize)]
2295pub struct ConfirmSubscriptionArgs {
2296 pub workspace: String,
2297 pub viewer: Viewer,
2298 pub session: String,
2299}
2300
2301/// `admin_log`: a staff change another service made to a workspace, kept
2302/// in sudo's audit log with billing's own (`admin_audit`). For identity's
2303/// restores and purges of deleted workspaces. Returns `bool`.
2304#[derive(Debug, Serialize, Deserialize)]
2305pub struct AdminLogArgs {
2306 pub workspace: String,
2307 pub action: String,
2308 pub detail: String,
2309 /// The staff member's email.
2310 pub by: String,
2311}
2312
2313/// `close_workspace`: settles a workspace that is about to be deleted.
2314/// Owners only. Refused while it has an invoice that failed, while it
2315/// holds prepaid credit, or while it owes money it cannot be charged for
2316/// now; otherwise what it owes is invoiced to its card at once (no
2317/// minimum), its plan is cancelled at Stripe straight away, and its
2318/// account is marked closed, so the month-end close, autopay and limit
2319/// warnings pass it by. Its ledger, invoices and statements stay. With
2320/// `dry_run`, only says whether it could, changing nothing. Returns
2321/// `Outcome<bool>`.
2322#[derive(Debug, Serialize, Deserialize)]
2323#[serde(rename_all = "camelCase")]
2324pub struct CloseWorkspaceArgs {
2325 pub actor: User,
2326 pub workspace: String,
2327 #[serde(default)]
2328 pub dry_run: bool,
2329}
2330
2331/// `cancel_subscription` (`resume` false) ends a plan at the end of the
2332/// period paid for; with `resume` true, takes that back. Owners only.
2333/// Returns `Outcome<FeatureState>`.
2334#[derive(Debug, Serialize, Deserialize)]
2335pub struct CancelSubscriptionArgs {
2336 pub actor: User,
2337 pub workspace: String,
2338 pub feature: Feature,
2339 #[serde(default)]
2340 pub resume: bool,
2341}
2342
2343/// `has_feature`: whether a feature works for a workspace now, asked by the
2344/// service that provides it before doing paid work. Returns
2345/// `Outcome<bool>`: a failure, with the reason to show, when it does not.
2346/// True everywhere when no card processor is configured.
2347#[derive(Debug, Serialize, Deserialize)]
2348pub struct HasFeatureArgs {
2349 pub workspace: String,
2350 pub feature: Feature,
2351}
2352
2353/// `charge_feature`: usage of a feature past its plan's allowance, charged
2354/// from the workspace's credit at cost plus the margin, whatever
2355/// `FREE_WHILE_BUILDING` says. Called by the service that provides it.
2356/// Charged once per `reference`. Returns `Outcome<bool>`: false if that
2357/// reference was charged before.
2358#[derive(Debug, Serialize, Deserialize)]
2359#[serde(rename_all = "camelCase")]
2360pub struct ChargeFeatureArgs {
2361 pub workspace: String,
2362 pub feature: Feature,
2363 /// What it cost g1t, in millionths of a dollar, before the margin.
2364 pub cost_micros: i64,
2365 pub description: String,
2366 /// `namespace/name`, when the usage was one repository's.
2367 pub repo: Option<String>,
2368 /// Unique to this charge, e.g. `deployments/acme/2026-10`.
2369 pub reference: String,
2370 /// For a build: how long it ran. The plan's included build time this
2371 /// month pays for what it can, and only the rest of `cost_micros` is
2372 /// charged.
2373 #[serde(default)]
2374 pub build_seconds: Option<u32>,
2375}
2376
2377// ---------------------------------------------------------------------
2378// Costs and margin: what Cloudflare charges g1t against what g1t
2379// charges (billing's costs.rs, margin.rs and pricing.rs). Staff only.
2380// ---------------------------------------------------------------------
2381
2382/// `admin_costs`: the Costs & margin page. Returns `CostsReport`.
2383#[derive(Debug, Default, Serialize, Deserialize)]
2384pub struct AdminCostsArgs {
2385 /// How many days back, 7 to 90; 30 when absent.
2386 #[serde(default)]
2387 pub days: Option<u32>,
2388}
2389
2390/// One of g1t's products on one day.
2391#[derive(Clone, Debug, Default, Serialize, Deserialize)]
2392#[serde(rename_all = "camelCase")]
2393pub struct CostDay {
2394 pub day: String,
2395 pub bucket: String,
2396 /// What Cloudflare charged g1t.
2397 pub cf_cost_micros: i64,
2398 /// What g1t's meters recorded it cost, at the price book's cost.
2399 pub own_cost_micros: i64,
2400 /// What customers were charged for it at price, before included
2401 /// usage, trials and pools paid for some.
2402 pub value_micros: i64,
2403 /// Of that, what workspaces paid.
2404 pub cash_micros: i64,
2405}
2406
2407/// One product over the range.
2408#[derive(Clone, Debug, Default, Serialize, Deserialize)]
2409#[serde(rename_all = "camelCase")]
2410pub struct ProductMargin {
2411 pub bucket: String,
2412 pub title: String,
2413 /// The cost the margin is taken from: Cloudflare's bill, or g1t's own
2414 /// figure for what Cloudflare does not bill (models).
2415 pub cost_micros: i64,
2416 pub cf_cost_micros: i64,
2417 pub own_cost_micros: i64,
2418 pub value_micros: i64,
2419 pub margin_micros: i64,
2420 pub margin_percent: Option<f64>,
2421 /// `cloudflare` or `ledger`.
2422 pub cost_source: String,
2423 /// Running g1t itself, paid for by the plan.
2424 pub overhead: bool,
2425}
2426
2427/// All of g1t over the range: money in against every cost, and against
2428/// the cost of what was sold (every cost less what g1t gave away).
2429#[derive(Clone, Debug, Default, Serialize, Deserialize)]
2430#[serde(rename_all = "camelCase")]
2431pub struct OverallMargin {
2432 /// What workspaces paid for usage, and for the plan.
2433 pub usage_micros: i64,
2434 pub plans_micros: i64,
2435 pub cost_micros: i64,
2436 pub margin_micros: i64,
2437 pub margin_percent: Option<f64>,
2438 /// Of `cost_micros`, what went on usage g1t gave away on purpose:
2439 /// comped workspaces, free periods, the trial and the open-source pool.
2440 #[serde(default)]
2441 pub given_micros: i64,
2442 /// Money in against `cost_micros - given_micros`.
2443 #[serde(default)]
2444 pub sold_margin_micros: i64,
2445 #[serde(default)]
2446 pub sold_margin_percent: Option<f64>,
2447 /// What was sold, apart: usage (`usage_micros` against what that usage
2448 /// cost, less what was given), running g1t (`plans_micros` against the
2449 /// platform's cost, less its given share) and what no mapping names.
2450 #[serde(default)]
2451 pub usage_cost_micros: i64,
2452 #[serde(default)]
2453 pub usage_margin_micros: i64,
2454 #[serde(default)]
2455 pub usage_margin_percent: Option<f64>,
2456 #[serde(default)]
2457 pub running_cost_micros: i64,
2458 #[serde(default)]
2459 pub unmapped_cost_micros: i64,
2460 /// `given_micros` by why: comped workspaces, free use (free periods,
2461 /// free allowances, overruns g1t covered), the trial, the open-source pool.
2462 #[serde(default)]
2463 pub given_comped_micros: i64,
2464 #[serde(default)]
2465 pub given_free_micros: i64,
2466 #[serde(default)]
2467 pub given_trial_micros: i64,
2468 #[serde(default)]
2469 pub given_pool_micros: i64,
2470 /// What discounts on an account's terms took below cost plus the
2471 /// margin: given, so a discounted sale is not margin lost.
2472 #[serde(default)]
2473 pub given_discount_micros: i64,
2474 /// `cost_micros` by who g1t pays: Cloudflare's bill (billed amounts,
2475 /// after the included allowances), and model providers (the ledger's
2476 /// cost of the tokens, which Cloudflare's bill does not show).
2477 /// What the plan's included usage paid for, at price (the ledger's
2478 /// `credit_micros`, comped workspaces left out): money in for usage,
2479 /// paid out of `plans_micros`.
2480 #[serde(default)]
2481 pub included_micros: i64,
2482 #[serde(default)]
2483 pub cloudflare_cost_micros: i64,
2484 #[serde(default)]
2485 pub models_cost_micros: i64,
2486}
2487
2488/// A count, cost or leak that does not add up.
2489#[derive(Clone, Debug, Serialize, Deserialize)]
2490#[serde(rename_all = "camelCase")]
2491pub struct CostDrift {
2492 pub bucket: String,
2493 pub title: String,
2494 /// `count` (units g1t counted against Cloudflare's), `cost` (the bill
2495 /// against the price book's cost of the same usage; for models, what AI
2496 /// Gateway priced g1t's provider traffic at against the ledger's model
2497 /// cost), `unpriced` (model usage AI Gateway put no price on, so its
2498 /// cost is not the providers'), or `leak`.
2499 pub kind: String,
2500 pub ours: f64,
2501 pub cloudflare: f64,
2502 pub delta_percent: Option<f64>,
2503 pub detail: String,
2504 pub found_at: String,
2505}
2506
2507/// A margin alert, open while its condition lasts.
2508#[derive(Clone, Debug, Serialize, Deserialize)]
2509#[serde(rename_all = "camelCase")]
2510pub struct MarginAlert {
2511 pub id: String,
2512 /// `margin`, `overall`, `leak`, `drift` or `workspace`.
2513 pub kind: String,
2514 /// The product, or the workspace.
2515 pub subject: String,
2516 pub detail: String,
2517 pub since: String,
2518 pub opened_at: String,
2519 pub emailed_at: Option<String>,
2520}
2521
2522/// A change to a price the reconciler measured.
2523#[derive(Clone, Debug, Serialize, Deserialize)]
2524#[serde(rename_all = "camelCase")]
2525pub struct PriceProposal {
2526 pub id: String,
2527 pub meter: String,
2528 pub title: String,
2529 pub unit: String,
2530 pub current_cost_micros: f64,
2531 pub proposed_cost_micros: f64,
2532 pub change_percent: f64,
2533 pub markup_percent: u32,
2534 pub reason: String,
2535 /// `keeper` or `reconciler`.
2536 pub source: String,
2537 /// Far off the current cost: look before approving.
2538 pub suspect: bool,
2539 /// `open`, `applied`, `approved`, `rejected` or `superseded`.
2540 pub status: String,
2541 pub created_at: String,
2542 pub decided_at: Option<String>,
2543 pub decided_by: Option<String>,
2544 pub note: Option<String>,
2545 /// When it takes or took effect, once approved or applied.
2546 pub effective_at: Option<String>,
2547}
2548
2549/// One version of one meter's price. Never changed once written.
2550#[derive(Clone, Debug, Serialize, Deserialize)]
2551#[serde(rename_all = "camelCase")]
2552pub struct PriceVersion {
2553 pub id: String,
2554 pub meter: String,
2555 pub version: u32,
2556 pub cost_micros: f64,
2557 pub markup_percent: u32,
2558 pub price_micros: f64,
2559 pub effective_at: String,
2560 pub reason: String,
2561 pub created_by: String,
2562 /// When the price book took it on; absent while it waits for its date.
2563 pub applied_at: Option<String>,
2564}
2565
2566/// What a workspace cost g1t over the range, Cloudflare's costs shared
2567/// out by g1t's own meters, against what it paid.
2568#[derive(Clone, Debug, Serialize, Deserialize)]
2569#[serde(rename_all = "camelCase")]
2570pub struct WorkspaceCost {
2571 pub workspace: String,
2572 pub cost_micros: i64,
2573 pub revenue_micros: i64,
2574 /// Of `cost_micros`, what g1t gave away.
2575 #[serde(default)]
2576 pub given_micros: i64,
2577 /// One of g1t's own (comped) workspaces.
2578 pub internal: bool,
2579}
2580
2581/// One Cloudflare meter over the range, and the product it is a cost of.
2582#[derive(Clone, Debug, Serialize, Deserialize)]
2583#[serde(rename_all = "camelCase")]
2584pub struct CostLineSummary {
2585 pub product: String,
2586 pub meter: String,
2587 pub raw_name: String,
2588 pub unit: String,
2589 pub source: String,
2590 pub quantity: f64,
2591 pub cost_micros: i64,
2592 /// Absent when no mapping claims it.
2593 pub bucket: Option<String>,
2594}
2595
2596/// A row of the mapping from Cloudflare's meters to g1t's products.
2597#[derive(Clone, Debug, Serialize, Deserialize)]
2598#[serde(rename_all = "camelCase")]
2599pub struct CostMapping {
2600 pub product: String,
2601 pub meter: String,
2602 pub bucket: String,
2603 pub price_meter: Option<String>,
2604 pub own_meter: Option<String>,
2605 pub scale_to_own: bool,
2606 pub drift_percent: f64,
2607 pub note: String,
2608 pub updated_at: String,
2609 pub updated_by: String,
2610}
2611
2612/// The guardrails on prices and the alerts.
2613#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
2614#[serde(rename_all = "camelCase")]
2615pub struct CostSettings {
2616 /// Apply small moves without staff.
2617 pub auto_apply: bool,
2618 /// The largest move applied without staff, either way, in percent.
2619 pub auto_apply_percent: f64,
2620 /// Days between telling customers of a rise and charging it.
2621 pub notice_days: u32,
2622 /// Below this margin, in percent, for `alert_days` days in a row, alert.
2623 pub margin_floor_percent: f64,
2624 pub alert_days: u32,
2625 /// Days with less cost than this say nothing about a margin.
2626 pub min_daily_cost_micros: i64,
2627 /// A workspace costing more than its revenue times this, over 30 days,
2628 /// and at least `anomaly_floor_micros`, is flagged.
2629 pub anomaly_factor: f64,
2630 pub anomaly_floor_micros: i64,
2631}
2632
2633impl Default for CostSettings {
2634 fn default() -> Self {
2635 CostSettings {
2636 auto_apply: true,
2637 auto_apply_percent: 25.0,
2638 notice_days: 14,
2639 margin_floor_percent: 10.0,
2640 alert_days: 3,
2641 min_daily_cost_micros: 100_000,
2642 anomaly_factor: 1.0,
2643 anomaly_floor_micros: 1_000_000,
2644 }
2645 }
2646}
2647
2648/// The Costs & margin page.
2649#[derive(Clone, Debug, Default, Serialize, Deserialize)]
2650#[serde(rename_all = "camelCase")]
2651pub struct CostsReport {
2652 /// A token to read Cloudflare's bill is set.
2653 pub configured: bool,
2654 /// When Cloudflare's bill was last read.
2655 pub fetched_at: Option<String>,
2656 /// The days shown, YYYY-MM-DD.
2657 pub since: String,
2658 pub until: String,
2659 pub days: Vec<CostDay>,
2660 pub products: Vec<ProductMargin>,
2661 pub overall: OverallMargin,
2662 pub drift: Vec<CostDrift>,
2663 pub alerts: Vec<MarginAlert>,
2664 pub proposals: Vec<PriceProposal>,
2665 pub versions: Vec<PriceVersion>,
2666 pub top_workspaces: Vec<WorkspaceCost>,
2667 pub lines: Vec<CostLineSummary>,
2668 pub mappings: Vec<CostMapping>,
2669 pub settings: CostSettings,
2670 /// g1t's own spend against its two caps.
2671 #[serde(default)]
2672 pub caps: SpendCaps,
2673}
2674
2675/// What g1t itself pays for, against its caps (billing's `budget`): the
2676/// daily breaker on all of it, and each comped account's monthly budget.
2677/// One of Cloudflare's subscriptions, at what it comes to a month.
2678#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
2679#[serde(rename_all = "camelCase")]
2680pub struct FixedCost {
2681 pub name: String,
2682 pub monthly_micros: i64,
2683}
2684
2685/// At cost, never at price. What sudo's Costs page and its red bar show.
2686#[derive(Clone, Debug, Default, Serialize, Deserialize)]
2687#[serde(rename_all = "camelCase")]
2688pub struct SpendCaps {
2689 /// Today (UTC), YYYY-MM-DD, and this month, YYYY-MM.
2690 pub day: String,
2691 pub month: String,
2692 /// What g1t paid for itself today across every workspace: comped work,
2693 /// the trial and open-source pools, free workspaces' overruns, and
2694 /// anything charged without real money behind it.
2695 pub today_micros: i64,
2696 /// `PLATFORM_DAILY_SPEND_CAP_MICROS`. Zero: no breaker.
2697 pub daily_cap_micros: i64,
2698 /// The breaker is open: new hosted-model agent runs that g1t would pay
2699 /// for wait until tomorrow (UTC) or until staff lift it.
2700 pub tripped: bool,
2701 pub tripped_at: Option<String>,
2702 /// Staff lifted it for the rest of the day.
2703 pub lifted_by: Option<String>,
2704 pub lifted_at: Option<String>,
2705 pub lift_note: Option<String>,
2706 /// This month so far, by what paid: `comped`, `trial`, `oss`, `given`,
2707 /// `unpaid`.
2708 pub month_buckets: Vec<SpendBucket>,
2709 /// Each comped account's monthly budget.
2710 pub comped: Vec<CompedBudget>,
2711 /// Free workspaces' share of this month's reconciled costs (git,
2712 /// storage, platform), through yesterday.
2713 pub free_tier_micros: i64,
2714 /// Cloudflare's subscriptions a month: as read from Cloudflare each
2715 /// day, else `CLOUDFLARE_FIXED_MONTHLY_MICROS`, an estimate.
2716 pub fixed_monthly_micros: i64,
2717 /// `cloudflare` or `estimate`.
2718 #[serde(default)]
2719 pub fixed_source: String,
2720 #[serde(default)]
2721 pub fixed_read_at: Option<String>,
2722 /// Each subscription, when read from Cloudflare.
2723 #[serde(default)]
2724 pub fixed_items: Vec<FixedCost>,
2725 /// Money in this month, through the last reconciled day.
2726 pub revenue_micros: i64,
2727}
2728
2729#[derive(Clone, Debug, Default, Serialize, Deserialize)]
2730#[serde(rename_all = "camelCase")]
2731pub struct SpendBucket {
2732 pub bucket: String,
2733 pub title: String,
2734 pub micros: i64,
2735}
2736
2737/// A comped account's monthly budget: what its work cost g1t this month.
2738#[derive(Clone, Debug, Default, Serialize, Deserialize)]
2739#[serde(rename_all = "camelCase")]
2740pub struct CompedBudget {
2741 pub account: String,
2742 pub name: String,
2743 pub used_micros: i64,
2744 /// Zero: no budget.
2745 pub ceiling_micros: i64,
2746 /// The ceiling is `COMPED_MONTHLY_CEILING_MICROS`, not the account's own.
2747 pub default_ceiling: bool,
2748 /// 50, 75, 90, 100, or 0.
2749 pub level: u32,
2750}
2751
2752/// `admin_spend_caps`: g1t's own spend against its caps. Returns `SpendCaps`.
2753#[derive(Debug, Default, Serialize, Deserialize)]
2754pub struct AdminSpendCapsArgs {}
2755
2756/// `admin_lift_breaker`: lets hosted-model runs start again for the rest
2757/// of today (UTC), with why. Recorded in the audit log. Returns
2758/// `Outcome<SpendCaps>`.
2759#[derive(Debug, Serialize, Deserialize)]
2760pub struct AdminLiftBreakerArgs {
2761 pub note: String,
2762 pub by: String,
2763}
2764
2765/// `admin_cost_alerts`: the open margin alerts, for sudo's banner.
2766/// Returns `Vec<MarginAlert>`.
2767#[derive(Debug, Default, Serialize, Deserialize)]
2768pub struct AdminCostAlertsArgs {}
2769
2770/// `admin_decide_proposal`: approve or reject a price proposal. An
2771/// approved rise takes effect after the notice period. Returns
2772/// `Outcome<PriceProposal>`.
2773#[derive(Debug, Serialize, Deserialize)]
2774pub struct AdminDecideProposalArgs {
2775 pub id: String,
2776 /// `approve` or `reject`.
2777 pub decision: String,
2778 #[serde(default)]
2779 pub note: String,
2780 pub by: String,
2781}
2782
2783/// `admin_set_cost_settings`. Returns `Outcome<CostSettings>`.
2784#[derive(Debug, Serialize, Deserialize)]
2785pub struct AdminSetCostSettingsArgs {
2786 pub settings: CostSettings,
2787 pub by: String,
2788}
2789
2790/// `admin_set_cost_mapping`: adds, changes or (with `remove`) removes a
2791/// mapping row. Returns `Outcome<CostMapping>`.
2792#[derive(Debug, Serialize, Deserialize)]
2793pub struct AdminSetCostMappingArgs {
2794 pub product: String,
2795 pub meter: String,
2796 #[serde(default)]
2797 pub bucket: String,
2798 #[serde(default)]
2799 pub price_meter: Option<String>,
2800 #[serde(default)]
2801 pub own_meter: Option<String>,
2802 #[serde(default)]
2803 pub scale_to_own: bool,
2804 #[serde(default)]
2805 pub drift_percent: Option<f64>,
2806 #[serde(default)]
2807 pub note: String,
2808 #[serde(default)]
2809 pub remove: bool,
2810 pub by: String,
2811}
2812
2813/// `admin_run_costs`: reads Cloudflare's bill and reconciles now, as the
2814/// daily run does. Returns `Outcome<CostsRun>`.
2815#[derive(Debug, Default, Serialize, Deserialize)]
2816pub struct AdminRunCostsArgs {
2817 #[serde(default)]
2818 pub by: String,
2819}
2820
2821#[derive(Clone, Debug, Default, Serialize, Deserialize)]
2822#[serde(rename_all = "camelCase")]
2823pub struct CostsRun {
2824 pub lines: u32,
2825 pub days: u32,
2826 pub proposals: u32,
2827 pub alerts: u32,
2828 /// What could not be read, in words.
2829 pub problems: Vec<String>,
2830}
2831
2832#[cfg(test)]
2833mod tests {
2834 use super::*;
2835
2836 #[test]
2837 fn an_account_carries_no_run_fee() {
2838 let account = Account {
2839 workspace: "acme".into(),
2840 balance_micros: 0,
2841 status: Status { enabled: true, live: false, free: false },
2842 margin_percent: 20,
2843 card: None,
2844 };
2845 let json = serde_json::to_value(account).unwrap();
2846 let mut keys: Vec<&str> = json.as_object().unwrap().keys().map(String::as_str).collect();
2847 keys.sort_unstable();
2848 assert_eq!(keys, ["balanceMicros", "card", "marginPercent", "status", "workspace"]);
2849 }
2850
2851 #[test]
2852 fn a_price_change_says_when_the_markup_moved() {
2853 let change = PriceChange {
2854 meter: "sandbox_second".into(),
2855 old_cost_micros: 21.0,
2856 new_cost_micros: 21.0,
2857 markup_percent: 20,
2858 old_markup_percent: Some(138),
2859 reason: "Sandbox time is now charged at cost plus 20% from the first second".into(),
2860 created_at: "2026-10-05T00:00:00Z".into(),
2861 effective_at: None,
2862 };
2863 assert_eq!(serde_json::to_value(&change).unwrap()["oldMarkupPercent"], 138);
2864 let cost_only = PriceChange { old_markup_percent: None, ..change };
2865 assert!(serde_json::to_value(&cost_only).unwrap().get("oldMarkupPercent").is_none());
2866 }
2867
2868 #[test]
2869 fn features_are_named_as_the_site_sends_them() {
2870 assert_eq!(
2871 serde_json::to_value(Feature::Deployments).unwrap(),
2872 serde_json::json!("deployments")
2873 );
2874 assert_eq!(Feature::parse("deployments"), Some(Feature::Deployments));
2875 assert_eq!(serde_json::to_value(Feature::Plan).unwrap(), serde_json::json!("plan"));
2876 assert_eq!(Feature::parse("plan"), Some(Feature::Plan));
2877 // Older readers named the plan Team.
2878 assert_eq!(Feature::parse("team"), Some(Feature::Plan));
2879 assert_eq!(serde_json::from_value::<Feature>(serde_json::json!("team")).unwrap(), Feature::Plan);
2880 assert_eq!(Feature::ALL, [Feature::Plan]);
2881 assert!(SubscriptionStatus::Canceling.on());
2882 assert!(!SubscriptionStatus::PastDue.on());
2883 }
2884
2885 #[test]
2886 fn a_reservation_is_asked_for_and_answered_in_camel_case() {
2887 let asked: ReserveArgs = serde_json::from_value(serde_json::json!({
2888 "workspace": "acme",
2889 "repo": { "namespace": "acme", "name": "web" },
2890 "public": true,
2891 "kind": "check",
2892 "estimateMicros": 2_000_000,
2893 }))
2894 .unwrap();
2895 assert_eq!(asked.kind, ComputeKind::Check);
2896 assert!(asked.kind.open_source_pool());
2897 assert!(!ComputeKind::Agent.open_source_pool());
2898 // Rust callers that write snake_case are read too.
2899 let snake: ReserveArgs = serde_json::from_value(serde_json::json!({
2900 "workspace": "acme",
2901 "repo": { "namespace": "acme", "name": "web" },
2902 "public": false,
2903 "kind": "agent",
2904 "estimate_micros": 1,
2905 }))
2906 .unwrap();
2907 assert_eq!(snake.estimate_micros, 1);
2908 let answer = Reservation { id: "rsv_1".into(), paid_by: PaidBy::OnDemand, held_micros: 5, expires_at: String::new() };
2909 assert_eq!(serde_json::to_value(&answer).unwrap()["paidBy"], "on_demand");
2910 assert_eq!(serde_json::to_value(PlanKind::Internal).unwrap(), "internal");
2911 assert!(!PlanKind::Free.on_demand() && PlanKind::Enterprise.on_demand());
2912 }
2913
2914 #[test]
2915 fn a_refusal_carries_its_own_code() {
2916 let refused: crate::Outcome<Reservation> =
2917 crate::Outcome::fail(crate::FailureCode::OssPoolEmpty, "The open-source pool is spent.");
2918 let json = serde_json::to_value(&refused).unwrap();
2919 assert_eq!(json["error"]["code"], "oss_pool_empty");
2920 assert_eq!(crate::FailureCode::NotPaid.http_status(), 402);
2921 assert_eq!(crate::FailureCode::Paused.http_status(), 409);
2922 }
2923
2924 #[test]
2925 fn who_pays_is_read_as_the_runner_sends_it() {
2926 let run: StartRunArgs = serde_json::from_value(serde_json::json!({
2927 "workspace": "acme",
2928 "repo": { "namespace": "acme", "name": "web" },
2929 "number": 7,
2930 "task": "implement",
2931 "model": "Claude Sonnet 5.5",
2932 "billedTo": "workspace",
2933 }))
2934 .unwrap();
2935 assert_eq!(run.billed_to, "workspace");
2936 }
2937}