Skip to content
3,711 linesCodeBlameRaw
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 /// For usage: what the account's discount took off its price. The
194 /// price is `-amount_micros` plus this and what paid for it.
195 #[serde(default)]
196 pub discount_micros: i64,
197 /// For a credit from g1t, and for what of one expired or was revoked:
198 /// its kind.
199 #[serde(default, skip_serializing_if = "Option::is_none")]
200 pub credit_kind: Option<CreditKind>,
201}
202
203fn g1t() -> String {
204 "g1t".to_owned()
205}
206
207/// `account` (`Outcome<Account>`) and `ledger` (`Outcome<Vec<LedgerEntry>>`,
208/// newest first). Members of the workspace only.
209#[derive(Debug, Serialize, Deserialize)]
210pub struct AccountArgs {
211 pub workspace: String,
212 pub viewer: Viewer,
213}
214
215/// `checkout`: prepays usage: money paid in advance, drawn down by usage
216/// after the plan's included usage, which raises what can be used before
217/// work stops by the same amount at once. $25 at the least. By card, with
218/// 3-D Secure; from $1,000 also by bank transfer. Owners of the workspace
219/// only. Returns `Outcome<Checkout>`.
220#[derive(Debug, Serialize, Deserialize)]
221#[serde(rename_all = "camelCase")]
222pub struct CheckoutArgs {
223 pub actor: User,
224 pub workspace: String,
225 /// How much to prepay, in cents.
226 pub amount_cents: u32,
227 /// Where the payment page sends the person afterwards. The payment's
228 /// id is appended as `session`.
229 pub return_url: String,
230 /// `card` (the default) or `bank_transfer` (from $1,000): Stripe gives
231 /// the account details, and the money counts once it arrives.
232 #[serde(default)]
233 pub method: Option<String>,
234}
235
236#[derive(Debug, Serialize, Deserialize)]
237pub struct Checkout {
238 /// The payment page to send the person to.
239 pub url: String,
240}
241
242/// `confirm`: credits a payment once the provider says it was made. Safe
243/// to call any number of times. Returns `Outcome<Account>`.
244#[derive(Debug, Serialize, Deserialize)]
245pub struct ConfirmArgs {
246 pub workspace: String,
247 pub viewer: Viewer,
248 /// The payment's id, as returned to `return_url`.
249 pub session: String,
250}
251
252/// `can_start`: whether a workspace may start an agent now, asked before
253/// anything is opened for it. Returns `Outcome<bool>`: a failure, with the
254/// reason to show, when it has no credit.
255#[derive(Debug, Serialize, Deserialize)]
256pub struct CanStartArgs {
257 pub workspace: String,
258}
259
260/// `start_run`: asks whether a workspace may start an agent, and opens the
261/// run it will be charged for. Called by the runner service. Returns
262/// `Outcome<Option<RunTicket>>`: no ticket when billing is off, a failure
263/// when the workspace has no credit.
264#[derive(Debug, Serialize, Deserialize)]
265pub struct StartRunArgs {
266 pub workspace: String,
267 pub repo: RepoPath,
268 pub number: u32,
269 /// `implement`, `review` or `update`.
270 pub task: String,
271 /// The model, by its public name.
272 pub model: String,
273 /// `workspace` when the run uses the workspace's own model provider.
274 /// The runner, which is TypeScript, sends it as `billedTo`.
275 #[serde(default = "g1t", alias = "billedTo")]
276 pub billed_to: String,
277 /// The model session's id, when its requests go through g1t's AI
278 /// Gateway: settling charges the run what the gateway priced them at.
279 #[serde(default)]
280 pub session: Option<String>,
281 /// `small` or `large`: the tier g1t routed the run to, when g1t pays
282 /// for its model. None on the workspace's own provider.
283 #[serde(default)]
284 pub tier: Option<String>,
285}
286
287#[derive(Clone, Debug, Serialize, Deserialize)]
288#[serde(rename_all = "camelCase")]
289pub struct RunTicket {
290 pub run_id: String,
291 /// Lets the sandbox, and nothing else, report what this run cost.
292 pub token: String,
293}
294
295/// `finish_run`: what a run cost, as its sandbox reports it. Charged once.
296/// Returns `Outcome<bool>`.
297#[derive(Debug, Serialize, Deserialize)]
298#[serde(rename_all = "camelCase")]
299pub struct FinishRunArgs {
300 pub run_id: String,
301 pub token: String,
302 /// What the model provider charged, in US dollars.
303 pub cost_usd: f64,
304 #[serde(default)]
305 pub turns: u32,
306}
307
308
309/// `usage`: what a workspace's agents cost over a period, broken down.
310/// Members only. Returns `Outcome<Usage>`.
311#[derive(Debug, Serialize, Deserialize)]
312pub struct UsageArgs {
313 pub workspace: String,
314 pub viewer: Viewer,
315 /// RFC 3339: the start of the period. The period runs to now.
316 pub since: String,
317}
318
319/// One slice of usage: what it was for, what it cost, how many runs.
320#[derive(Clone, Debug, Serialize, Deserialize)]
321#[serde(rename_all = "camelCase")]
322pub struct UsageSlice {
323 pub key: String,
324 pub micros: i64,
325 pub runs: u32,
326}
327
328/// What a workspace's agents cost over a period.
329#[derive(Clone, Debug, Serialize, Deserialize)]
330#[serde(rename_all = "camelCase")]
331pub struct Usage {
332 pub since: String,
333 /// Charged, including g1t's margin.
334 pub spent_micros: i64,
335 /// What g1t's usage came to at price, less what was charged: the plan's
336 /// included usage, the trial, a pool or a free period paid it. Usage at
337 /// price is `spent_micros` plus this.
338 #[serde(default)]
339 pub covered_micros: i64,
340 /// What the account's discount took off the price. Usage at price is
341 /// `spent_micros` plus `covered_micros` plus this.
342 #[serde(default)]
343 pub discount_micros: i64,
344 /// The account's discount now, in percent; absent without one. With
345 /// one, the slices measure usage at price.
346 #[serde(default)]
347 pub discount_percent: Option<u32>,
348 /// Usage at price: `spent_micros` plus `covered_micros` plus
349 /// `discount_micros`, from the same ledger lines. The one figure every
350 /// page shows as usage (mission control, the agent fleet, Usage and
351 /// Billing), labelled "usage at price".
352 #[serde(default)]
353 pub price_micros: i64,
354 /// What g1t's model provider charged, before the margin.
355 pub cost_micros: i64,
356 /// What runs on the workspace's own provider cost there, as the harness
357 /// estimated it. Not charged by g1t.
358 pub provider_micros: i64,
359 /// What the runs used, at cost: g1t's models and the workspace's own
360 /// provider together, whatever was charged for them.
361 pub used_micros: i64,
362 /// g1t charges nothing for now. The slices then measure usage at cost,
363 /// since every charge is zero.
364 pub free: bool,
365 pub runs: u32,
366 /// Spend per day (`YYYY-MM-DD`) and task, as `day/task` keys.
367 pub by_day: Vec<UsageSlice>,
368 /// Per task: implement, review, revise, update, plan.
369 pub by_task: Vec<UsageSlice>,
370 /// Per repository, `namespace/name`.
371 pub by_repo: Vec<UsageSlice>,
372 /// The pull requests that cost most, as `namespace/name#number`.
373 pub by_pull: Vec<UsageSlice>,
374 /// Per model, by its public name.
375 pub by_model: Vec<UsageSlice>,
376 /// Credit bought in the period.
377 pub added_micros: i64,
378}
379
380/// `record_tokens`: what one model answer used, added to the day's count
381/// for its run. The model proxy sends it after each answer. For usage
382/// views only: runs are still priced from AI Gateway. Returns
383/// `Outcome<bool>`: false when there was nothing to count.
384#[derive(Debug, Serialize, Deserialize)]
385#[serde(rename_all = "camelCase")]
386pub struct RecordTokensArgs {
387 pub workspace: String,
388 /// The model session's id (`ModelSession::id`), one per run.
389 pub session: String,
390 /// The person the run is for, by username. Absent when nobody asked.
391 #[serde(default)]
392 pub person: Option<String>,
393 pub model: String,
394 /// On g1t's hosted models: `small` or `large`.
395 #[serde(default)]
396 pub tier: Option<String>,
397 #[serde(default)]
398 pub input: u64,
399 #[serde(default)]
400 pub output: u64,
401 #[serde(default)]
402 pub cache_read: u64,
403 #[serde(default)]
404 pub cache_write: u64,
405}
406
407/// `token_usage`: the model tokens a workspace's runs used, day by day,
408/// for the whole workspace or for one person. Members only; a member may
409/// ask only for themselves, an owner for anyone. Returns
410/// `Outcome<TokenUsage>`.
411#[derive(Debug, Serialize, Deserialize)]
412pub struct TokenUsageArgs {
413 pub workspace: String,
414 pub viewer: Viewer,
415 /// A username: only the runs for them.
416 #[serde(default)]
417 pub person: Option<String>,
418 /// How many days, to today: 42 when absent, 366 at most.
419 #[serde(default)]
420 pub days: Option<u32>,
421}
422
423/// One day's tokens.
424#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
425pub struct DayTokens {
426 /// `YYYY-MM-DD`, UTC.
427 pub day: String,
428 pub tokens: u64,
429}
430
431/// The model tokens runs used over a window of days.
432#[derive(Clone, Debug, Serialize, Deserialize)]
433#[serde(rename_all = "camelCase")]
434pub struct TokenUsage {
435 /// `YYYY-MM-DD`: the first day counted.
436 pub since: String,
437 pub days: u32,
438 /// Null for the whole workspace.
439 pub person: Option<String>,
440 pub total_tokens: u64,
441 pub input_tokens: u64,
442 pub output_tokens: u64,
443 pub cache_read_tokens: u64,
444 pub cache_write_tokens: u64,
445 /// What those runs were charged, as `usage` measures it.
446 pub cost_micros: i64,
447 /// Days in the window with any tokens.
448 pub active_days: u32,
449 /// Every day in the window, oldest first, zeros included.
450 pub by_day: Vec<DayTokens>,
451}
452
453/// What a workspace pays a monthly price for. There is one plan, `plan`
454/// ("g1t"): a flat price per workspace, never per person, with included
455/// usage each month, more private storage, and deployments. Never free:
456/// `FREE_WHILE_BUILDING` does not cover it.
457///
458/// `deployments` is not sold on its own any more: it comes with the plan.
459/// A service that asks `has_feature` for it is told whether the workspace
460/// has the plan, and a Deployments subscription bought before the change
461/// keeps working until its period ends.
462#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
463#[serde(rename_all = "snake_case")]
464pub enum Feature {
465 /// The g1t plan. Older readers called it `team`.
466 #[serde(alias = "team")]
467 Plan,
468 /// Previews per pull request and production on g1t.page: part of the
469 /// plan.
470 Deployments,
471 /// The Security and quality activation: the security suite's paid
472 /// features on private repositories, for a monthly price per workspace
473 /// from the price book (`security_activation`). Sold on its own; it
474 /// does not need the plan, and the plan does not include it.
475 Security,
476}
477
478impl Feature {
479 /// What is sold: the plan, and the Security and quality activation.
480 pub const ALL: [Feature; 2] = [Feature::Plan, Feature::Security];
481
482 pub fn as_str(self) -> &'static str {
483 match self {
484 Feature::Plan => "plan",
485 Feature::Deployments => "deployments",
486 Feature::Security => "security",
487 }
488 }
489
490 pub fn parse(name: &str) -> Option<Feature> {
491 match name {
492 "plan" | "team" => Some(Feature::Plan),
493 "deployments" => Some(Feature::Deployments),
494 "security" => Some(Feature::Security),
495 _ => None,
496 }
497 }
498
499 pub fn title(self) -> &'static str {
500 match self {
501 Feature::Plan => "g1t",
502 Feature::Deployments => "Deployments",
503 Feature::Security => "Security and quality",
504 }
505 }
506}
507
508/// What deployments cost g1t, in millionths of a dollar: fallbacks for
509/// when billing's price book cannot be read. Nothing here is an allowance:
510/// on the plan every unit is metered from the first, at cost plus the
511/// margin, and drawn from the plan's included usage before anything is
512/// charged. Projects, previews and the apps behind them are not metered at
513/// all: Cloudflare's Workers for Platforms includes far more scripts than
514/// g1t runs, so an app costs g1t only the requests and CPU it answers with.
515pub mod deployment_costs {
516 /// Workers for Platforms: $0.30 per million requests.
517 pub const MICROS_PER_MILLION_REQUESTS: i64 = 300_000;
518 /// $0.02 per million CPU milliseconds.
519 pub const MICROS_PER_MILLION_CPU_MS: i64 = 20_000;
520 /// What one second of a build's sandbox costs g1t (Cloudflare
521 /// Containers, standard-1: half a vCPU, 4 GiB, 8 GB disk), rounded up,
522 /// as the price keeper measured it on 2026-10-05 (14.5). Only a
523 /// fallback: billing charges builds at the price book's `build_second`,
524 /// which the keeper keeps current.
525 pub const MICROS_PER_BUILD_SECOND: i64 = 15;
526 /// What one custom hostname costs g1t a month (Cloudflare for SaaS):
527 /// $0.10.
528 pub const MICROS_PER_DOMAIN_MONTH: i64 = 100_000;
529}
530
531/// `record_sandbox`: how long one sandbox ran for a workspace, reported by
532/// the runner when it stops. Every sandbox g1t starts for a workspace
533/// (agents, reviews, checks, the merge queue, workflow jobs) is metered by
534/// the second, from the first: recorded once per `reference`, with what it
535/// cost g1t, and charged at the price book's `sandbox_second` price unless
536/// `FREE_WHILE_BUILDING`. Deploy builds are charged by the Deployments plan
537/// instead.
538/// Returns `Outcome<bool>`: false if that reference was recorded before.
539#[derive(Debug, Serialize, Deserialize)]
540#[serde(rename_all = "camelCase")]
541pub struct RecordSandboxArgs {
542 pub workspace: String,
543 pub seconds: u32,
544 /// What ran, e.g. `Checks on acme/api#12`.
545 pub description: String,
546 /// `namespace/name`.
547 pub repo: Option<String>,
548 /// Unique to the run.
549 pub reference: String,
550 /// What ran: `agent`, `check`, `workflow` or `queue`. Decides whether
551 /// g1t's open-source pool may pay for it (checks, workflows and the
552 /// merge queue on public repositories). Absent: not the pool.
553 #[serde(default)]
554 pub kind: Option<ComputeKind>,
555 /// The vCPU-seconds the sandbox used, when it can tell. With it, the
556 /// run is priced on its own CPU (`sandbox_base_second` per second plus
557 /// `sandbox_cpu_second` per vCPU-second); without it, at the average
558 /// (`sandbox_second`).
559 #[serde(default, alias = "cpu_seconds")]
560 pub cpu_seconds: Option<f64>,
561 /// The reservation the work started under, settled with this cost.
562 #[serde(default, alias = "reservation_id")]
563 pub reservation_id: Option<String>,
564 /// It ran on one of the workspace's self-hosted runners: recorded as
565 /// self-hosted time, for the minutes, at $0.
566 #[serde(default, alias = "self_hosted")]
567 pub self_hosted: bool,
568 /// The machine it ran on, by label (`g1t-4core`); absent, the standard
569 /// one. A larger machine's memory and disk cost more each second.
570 #[serde(default)]
571 pub instance: Option<String>,
572}
573
574/// How much a workspace has earned g1t's trust with money, which sets how
575/// far its unpaid usage can go before its work stops.
576#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
577#[serde(rename_all = "snake_case")]
578pub enum Trust {
579 /// No live payment yet: only a little past the free allowances.
580 New,
581 /// Has paid g1t real money: the ceiling grows with what it has paid.
582 Paid,
583 /// Has paid steadily for months, with nothing disputed or declined:
584 /// the ceiling follows its monthly spend, up to $10,000, by itself.
585 Established,
586 /// A ceiling g1t set by hand, after talking to the workspace.
587 Reviewed,
588 /// g1t's own workspaces: no ceiling.
589 Internal,
590}
591
592#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
593#[serde(rename_all = "snake_case")]
594pub enum LimitState {
595 Ok,
596 /// Past 80% of the ceiling.
597 Warning,
598 /// At or past it: no new sandboxes, builds or app requests.
599 Stopped,
600}
601
602/// How far a workspace's unpaid usage has gone this month, and where its
603/// work stops: like Fly's or Cloudflare's limits for new accounts, so no
604/// one runs up costs g1t cannot collect. Usage counts at what it cost g1t
605/// or what it is charged, whichever is more, so it counts while g1t is
606/// free too.
607#[derive(Clone, Debug, Serialize, Deserialize)]
608#[serde(rename_all = "camelCase")]
609pub struct Limit {
610 pub workspace: String,
611 /// The account that pays, whose usage and payments the limit counts:
612 /// the workspace's own, or its enterprise's.
613 #[serde(default)]
614 pub account: String,
615 #[serde(default)]
616 pub account_name: String,
617 pub trust: Trust,
618 /// Usage this month (UTC) less what was paid this month.
619 pub exposure_micros: i64,
620 /// Where work stops: the lower of g1t's ceiling and the owner's own
621 /// spend limit. None for g1t's own workspaces.
622 pub ceiling_micros: Option<i64>,
623 /// The ceiling g1t sets from `trust`.
624 pub trust_ceiling_micros: Option<i64>,
625 /// The owner's own monthly limit, if they set one.
626 pub spend_limit_micros: Option<i64>,
627 pub state: LimitState,
628 /// What to tell people when work is stopped or close to it.
629 pub message: Option<String>,
630 /// Charged this month, which the spend limit is measured against.
631 #[serde(default)]
632 pub spent_micros: i64,
633 /// True while the owners have not chosen a spend limit of their own, so
634 /// the automatic one applies: $200, or twice last month's spend.
635 #[serde(default)]
636 pub default_spend_limit: bool,
637 /// The most the owners may set their own limit to: g1t's ceiling. To
638 /// go past it, they contact g1t.
639 #[serde(default)]
640 pub available_micros: Option<i64>,
641 /// How the ceiling grows from here, in a sentence.
642 #[serde(default)]
643 pub growth: Option<String>,
644 /// Money paid in advance and not used yet. It raises what can be used
645 /// before work stops by the same amount, at once.
646 #[serde(default)]
647 pub prepaid_micros: i64,
648 /// The highest ceiling the workspace has ever had. Owners may set their
649 /// spend limit anywhere up to it (plus what is prepaid) without asking.
650 #[serde(default)]
651 pub max_ceiling_micros: Option<i64>,
652 /// The most the owners may raise the limit to themselves, once, with
653 /// `raise_once`: twice the highest ceiling. None once it is used.
654 #[serde(default)]
655 pub raise_once_micros: Option<i64>,
656 /// When the one-time raise was used, RFC 3339.
657 #[serde(default)]
658 pub raised_at: Option<String>,
659 /// True in a paid workspace's first billing cycle, when the ceiling is
660 /// the starting one (`LIMIT_PAID_START_MICROS`).
661 #[serde(default)]
662 pub first_month: bool,
663 /// The budget's alerts, in percent of the spend limit: some of 50, 75,
664 /// 90 and 100. Each is emailed to the owners once a month.
665 #[serde(default)]
666 pub alert_levels: Vec<u32>,
667 /// Whether usage pauses at the spend limit (the default). Off, the
668 /// limit only alerts; g1t's own ceiling still applies.
669 #[serde(default = "yes")]
670 pub pause_at_limit: bool,
671 /// An HTTPS address told of each budget alert with a JSON POST.
672 #[serde(default)]
673 pub budget_webhook: Option<String>,
674}
675
676fn yes() -> bool {
677 true
678}
679
680/// `limit`: a workspace's limit, for its members. Returns `Outcome<Limit>`.
681#[derive(Debug, Serialize, Deserialize)]
682pub struct LimitArgs {
683 pub workspace: String,
684 pub viewer: Viewer,
685}
686
687/// `check_limit`: the same, for the services that enforce it. Returns
688/// `Outcome<Limit>`.
689#[derive(Debug, Serialize, Deserialize)]
690pub struct CheckLimitArgs {
691 pub workspace: String,
692}
693
694/// `note_pending`: usage this month that will be charged later, such as
695/// app traffic past a plan, so the workspace's limit counts it now. Each
696/// report replaces the last for that workspace, source and month. Called
697/// by the service that meters it. Returns `bool`.
698#[derive(Debug, Serialize, Deserialize)]
699#[serde(rename_all = "camelCase")]
700pub struct NotePendingArgs {
701 pub workspace: String,
702 /// `deployments`, `security` (scans), `context` (search embeddings),
703 /// `storage` or `cache` (actions/cache, plan only). Billing charges
704 /// `security`, `context`, `storage` and `cache` itself once the month
705 /// is over; `deployments` charges its own.
706 pub source: String,
707 /// What it cost g1t so far this month, before the margin.
708 pub cost_micros: i64,
709 /// How much of it, for the Billing page: `1.2 million requests and
710 /// 3.4 million CPU ms`, `2 custom domains`.
711 #[serde(default)]
712 pub detail: Option<String>,
713}
714
715/// `usage_meters`: this month's usage for a workspace, one line per kind
716/// of meter, at what it is charged (cost plus the margin, on the account's
717/// terms) before the plan's included usage, the trial or g1t's pools paid
718/// for any of it. Members only. Returns `Outcome<Vec<MeterUsage>>`.
719#[derive(Debug, Serialize, Deserialize)]
720pub struct UsageMetersArgs {
721 pub workspace: String,
722 pub viewer: Viewer,
723}
724
725/// One kind of meter's usage this month.
726#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
727#[serde(rename_all = "camelCase")]
728pub struct MeterUsage {
729 /// `agents` (agent runs, models and sandboxes for checks, workflows
730 /// and the merge queue), `builds`, `requests` (app requests and CPU),
731 /// `domains`, `git_storage` (git operations and private storage) or
732 /// `search_scans` (search embeddings and security scans).
733 pub key: String,
734 pub label: String,
735 /// At price, before what paid for it.
736 pub micros: i64,
737 /// How much, when it is known: `12 runs`, `41 build minutes`.
738 #[serde(default)]
739 pub quantity: Option<String>,
740}
741
742/// `set_spend_limit`: the owner's own monthly ceiling, under g1t's; None
743/// removes it. Owners only. Returns `Outcome<Limit>`.
744#[derive(Debug, Serialize, Deserialize)]
745#[serde(rename_all = "camelCase")]
746pub struct SetSpendLimitArgs {
747 pub actor: User,
748 pub workspace: String,
749 /// A monthly limit, at most what is available; None goes back to the
750 /// default.
751 pub spend_limit_micros: Option<i64>,
752 /// Use everything available, with no limit of their own.
753 #[serde(default)]
754 pub use_full_limit: bool,
755 /// Use the one-time raise: up to twice the highest ceiling the
756 /// workspace has had, without asking. Once per workspace.
757 #[serde(default, alias = "raiseOnce")]
758 pub raise_once: bool,
759}
760
761/// One metered unit: what it costs g1t, and what it is sold at. The price
762/// is always `cost × (100 + markup) / 100`, so it follows the cost.
763#[derive(Clone, Debug, Serialize, Deserialize)]
764#[serde(rename_all = "camelCase")]
765pub struct Price {
766 /// `sandbox_second`, `build_second`, `app_requests`, `app_cpu`, `app_month`.
767 pub meter: String,
768 pub title: String,
769 pub unit: String,
770 /// Millionths of a dollar per unit; may have a fraction.
771 pub cost_micros: f64,
772 pub markup_percent: u32,
773 pub price_micros: f64,
774 /// `list`: Cloudflare's published price. `cloudflare`: what Cloudflare
775 /// actually billed g1t, measured.
776 pub source: String,
777 /// When it was last checked against Cloudflare's bill.
778 pub checked_at: Option<String>,
779 pub updated_at: String,
780}
781
782impl Price {
783 pub fn price_for(cost_micros: f64, markup_percent: u32) -> f64 {
784 cost_micros * f64::from(100 + markup_percent) / 100.0
785 }
786}
787
788/// A cost that moved.
789#[derive(Clone, Debug, Serialize, Deserialize)]
790#[serde(rename_all = "camelCase")]
791pub struct PriceChange {
792 pub meter: String,
793 pub old_cost_micros: f64,
794 pub new_cost_micros: f64,
795 pub markup_percent: u32,
796 /// The markup before, when the change was to the markup rather than
797 /// to the cost. Absent when the markup stayed `markup_percent`.
798 #[serde(default, skip_serializing_if = "Option::is_none")]
799 pub old_markup_percent: Option<u32>,
800 pub reason: String,
801 pub created_at: String,
802 /// When a change still to come takes effect: a rise is announced
803 /// before it is charged. Absent for changes already made.
804 #[serde(default, skip_serializing_if = "Option::is_none")]
805 pub effective_at: Option<String>,
806}
807
808/// `prices`: every metered price and the recent changes. Public. Returns
809/// `PriceBook`.
810#[derive(Clone, Debug, Serialize, Deserialize)]
811#[serde(rename_all = "camelCase")]
812pub struct PriceBook {
813 pub prices: Vec<Price>,
814 pub changes: Vec<PriceChange>,
815 /// The margin on model usage, which is charged at what AI Gateway
816 /// priced each request at.
817 pub model_margin_percent: u32,
818 /// Every plan, as it is sold now.
819 #[serde(default)]
820 pub plans: Vec<Plan>,
821 /// What is free, and what pays for it.
822 #[serde(default)]
823 pub free: Option<FreeTier>,
824}
825
826/// What g1t gives without a plan, each with what pays for it: a capped
827/// budget, never an open-ended allowance.
828#[derive(Clone, Debug, Default, Serialize, Deserialize)]
829#[serde(rename_all = "camelCase")]
830pub struct FreeTier {
831 /// Each new workspace's trial credit, once.
832 pub trial_workspace_micros: i64,
833 /// Trial grants each month, in all; new trials wait when it is spent.
834 pub trial_monthly_pool_micros: i64,
835 /// g1t's open-source pool each month, and any one repository's share.
836 pub oss_pool_micros: i64,
837 pub oss_repo_micros: i64,
838 /// Private repository storage that is free for every workspace. Past
839 /// it, the plan pays at cost plus the margin; a free workspace's pushes
840 /// to private repositories stop instead.
841 pub free_private_storage_bytes: i64,
842 /// Days of audit log a free workspace keeps.
843 pub audit_retention_days: u32,
844 /// Days of audit log the g1t plan keeps, and g1t's own and enterprise
845 /// workspaces. Longer is by arrangement, set per account in sudo.
846 #[serde(default)]
847 pub plan_audit_retention_days: u32,
848 /// The smallest amount a card is charged when a month closes; less
849 /// carries over. Charges at a limit always go through.
850 pub min_charge_micros: i64,
851 /// Git operations (clones, fetches and pushes through g1t) that are
852 /// free for every workspace each month. Past it, the plan pays at cost
853 /// plus the margin and is never slowed; a free workspace is slowed
854 /// down, never charged.
855 #[serde(default)]
856 pub git_operations_included: u64,
857 /// A new paid workspace's ceiling in its first month.
858 #[serde(default)]
859 pub paid_start_ceiling_micros: i64,
860 /// The most a one-click goodwill credit can cost g1t.
861 #[serde(default)]
862 pub overage_forgive_cost_micros: i64,
863}
864
865/// Who pays: a billing account. Every workspace has one; by default its
866/// own. An enterprise account pays for several workspaces at once, as
867/// GitHub Enterprise does: one bill, one limit, one set of terms.
868#[derive(Clone, Debug, Serialize, Deserialize)]
869#[serde(rename_all = "camelCase")]
870pub struct BillingAccount {
871 /// `ws_<slug>` for a workspace's own account; `ent_…` for an enterprise.
872 pub id: String,
873 pub kind: AccountKind,
874 pub name: String,
875 pub terms: Terms,
876 /// The workspaces it pays for.
877 pub workspaces: Vec<String>,
878 /// Where an enterprise's invoices go.
879 #[serde(default)]
880 pub billing_email: Option<String>,
881 /// An enterprise's invoices, newest first. Empty for a workspace's own.
882 #[serde(default)]
883 pub invoices: Vec<EnterpriseInvoice>,
884 pub created_at: String,
885 /// What g1t staff set for the account beyond its terms.
886 #[serde(default)]
887 pub allowances: Allowances,
888}
889
890/// Set per account by g1t staff in sudo, on top of its terms.
891#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
892#[serde(rename_all = "camelCase")]
893pub struct Allowances {
894 /// The g1t plan without paying for its monthly price, such as for a
895 /// partner. Usage is charged as usual. Comped accounts have it anyway.
896 #[serde(default, alias = "team")]
897 pub plan: bool,
898 /// Each of the account's public repositories' monthly cap on g1t's
899 /// open-source pool, in place of `OSS_REPO_MICROS`. None: the default.
900 #[serde(default)]
901 pub oss_repo_micros: Option<i64>,
902 /// The trial credit each of its workspaces gets, in place of
903 /// `TRIAL_WORKSPACE_MICROS`, outside the monthly pool. None: the default.
904 #[serde(default)]
905 pub trial_micros: Option<i64>,
906 /// Agents at once, in place of the plan's (2 in the first month or on
907 /// the trial, then 10). None: the default.
908 #[serde(default)]
909 pub max_concurrent_agents: Option<u32>,
910 /// One run's spend cap, in place of `RUN_CAP_MICROS` and the owners'
911 /// own. None: theirs, or the default.
912 #[serde(default)]
913 pub run_cap_micros: Option<i64>,
914 /// What the agents on one issue may spend in all, in place of
915 /// `ISSUE_CAP_MICROS` and the owners' own. None: theirs, or the default.
916 #[serde(default)]
917 pub issue_cap_micros: Option<i64>,
918 /// Days of audit log its workspaces keep, in place of the plan's (7
919 /// free, 90 on the plan), longer or shorter. None: the plan's.
920 #[serde(default)]
921 pub audit_retention_days: Option<u32>,
922 /// A hold g1t staff put on new compute, with why. None: no hold.
923 #[serde(default)]
924 pub hold: Option<String>,
925}
926
927/// `admin_set_allowances`: the plan on or off without charge, overrides of
928/// the plan's caps, a hold, and the account's share of g1t's pools.
929/// Recorded with who and why. Returns `Outcome<BillingAccount>`.
930#[derive(Debug, Serialize, Deserialize)]
931pub struct AdminSetAllowancesArgs {
932 pub id: String,
933 pub allowances: Allowances,
934 pub note: String,
935 pub by: String,
936}
937
938// --- Entitlements, and compute started under a reservation -----------------
939//
940// Every service that starts compute (sandboxes for agents, checks,
941// workflows and the merge queue; builds; models; semantic search) asks
942// billing first:
943//
944// 1. `entitlements { workspace }` says what the workspace may do at all:
945// its plan, whether it may start compute, its caps, and whether compute
946// is paused.
947// 2. `reserve { workspace, repo, public, kind, estimate_micros }` holds the
948// work's estimated cost against what may pay for it, so that starts at
949// the same moment cannot overshoot the ceiling together. It answers who
950// pays first, or refuses with a stable code and a message for the owner.
951// 3. `settle { reservation_id, actual_micros }` releases the hold once the
952// work is done. The charge itself goes on the ledger the usual way
953// (`finish_run`, `record_sandbox`, `charge_feature`, `note_pending`).
954//
955// A reservation never settled expires after `RESERVATION_HOURS`.
956
957/// A reservation that is never settled stops holding after this long.
958pub const RESERVATION_HOURS: u64 = 3;
959/// What a ceiling reads as when there is none (g1t's own workspaces): a
960/// billion dollars, which JavaScript holds exactly.
961pub const UNLIMITED_MICROS: i64 = 1_000_000_000_000_000;
962
963/// What a workspace pays g1t on, as far as compute is concerned.
964#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
965#[serde(rename_all = "snake_case")]
966pub enum PlanKind {
967 /// No plan: the forge is free; compute only from a trial or g1t's
968 /// open-source pool, after a card check.
969 Free,
970 /// The g1t plan, paid for (or given by g1t staff without its price).
971 Paid,
972 /// g1t's own workspaces and Flagon's (comped terms): the plan without
973 /// being charged. Usage is still recorded at what it cost.
974 Internal,
975 /// Paid for by an enterprise account, invoiced.
976 Enterprise,
977}
978
979impl PlanKind {
980 pub fn as_str(self) -> &'static str {
981 match self {
982 PlanKind::Free => "free",
983 PlanKind::Paid => "paid",
984 PlanKind::Internal => "internal",
985 PlanKind::Enterprise => "enterprise",
986 }
987 }
988
989 /// Whether usage past what is included may be charged (on demand).
990 pub fn on_demand(self) -> bool {
991 !matches!(self, PlanKind::Free)
992 }
993}
994
995/// What compute is for.
996#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
997#[serde(rename_all = "snake_case")]
998pub enum ComputeKind {
999 /// An agent's run: its sandbox and its model.
1000 Agent,
1001 /// Checks on a pull request.
1002 Check,
1003 /// A workflow job.
1004 Workflow,
1005 /// The merge queue's checks.
1006 Queue,
1007 /// A deployment's build.
1008 Deploy,
1009 /// Semantic search: embeddings in the context hub.
1010 Embedding,
1011}
1012
1013impl ComputeKind {
1014 pub fn as_str(self) -> &'static str {
1015 match self {
1016 ComputeKind::Agent => "agent",
1017 ComputeKind::Check => "check",
1018 ComputeKind::Workflow => "workflow",
1019 ComputeKind::Queue => "queue",
1020 ComputeKind::Deploy => "deploy",
1021 ComputeKind::Embedding => "embedding",
1022 }
1023 }
1024
1025 /// Whether g1t's open-source pool may pay for it on a public
1026 /// repository: checks, workflows and the merge queue only.
1027 pub fn open_source_pool(self) -> bool {
1028 matches!(self, ComputeKind::Check | ComputeKind::Workflow | ComputeKind::Queue)
1029 }
1030}
1031
1032/// Who pays first for reserved work. What the first source cannot cover
1033/// falls to the next, in this order.
1034#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1035#[serde(rename_all = "snake_case")]
1036pub enum PaidBy {
1037 /// The plan's included usage this month.
1038 Credit,
1039 /// The workspace's one-time trial credit.
1040 Trial,
1041 /// g1t's open-source pool.
1042 Oss,
1043 /// Charged to the workspace, at cost plus the margin.
1044 OnDemand,
1045}
1046
1047/// `entitlements`: what a workspace may do now, for the services that
1048/// start compute and the pages that show it. Takes `EntitlementsArgs`;
1049/// returns `Entitlements`. No viewer: callers decide who sees it.
1050#[derive(Debug, Serialize, Deserialize)]
1051pub struct EntitlementsArgs {
1052 pub workspace: String,
1053}
1054
1055/// `audit_retention`: how many days of audit log each workspace keeps, for
1056/// the events service's daily purge. Takes `AuditRetentionArgs`; returns
1057/// `Vec<AuditRetention>`, one for each workspace asked about.
1058#[derive(Debug, Serialize, Deserialize)]
1059pub struct AuditRetentionArgs {
1060 pub workspaces: Vec<String>,
1061}
1062
1063#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1064pub struct AuditRetention {
1065 pub workspace: String,
1066 pub days: u32,
1067}
1068
1069#[derive(Clone, Debug, Serialize, Deserialize)]
1070#[serde(rename_all = "camelCase")]
1071pub struct Entitlements {
1072 pub workspace: String,
1073 pub plan: PlanKind,
1074 /// May start sandboxes, models, deployments and semantic search at all:
1075 /// paid, internal and enterprise workspaces, or a free one with trial
1076 /// credit left. A free workspace may still use the open-source pool
1077 /// for checks, workflows and the merge queue on public repositories
1078 /// after a card check; `reserve` decides that per start.
1079 pub compute: bool,
1080 /// The one-time trial credit left; 0 if none was granted or it is used.
1081 pub trial_micros_left: i64,
1082 /// A card check has been done. The trial and the open-source pool need
1083 /// it.
1084 pub trial_verified: bool,
1085 /// A paid workspace still in its first billing cycle.
1086 pub first_month: bool,
1087 /// Agents at once: 2 in the first month or on the trial, 10 after;
1088 /// staff can override it.
1089 pub max_concurrent_agents: u32,
1090 /// The longest one run may take: 60 minutes in the first month or on
1091 /// the trial; otherwise the guardrails' own caps (`MAX_MINUTES`).
1092 pub max_run_minutes: u32,
1093 /// One run's spend cap (`RUN_CAP_MICROS`, $2 by default); staff can
1094 /// override it.
1095 pub run_cap_micros: i64,
1096 /// What agents may spend on one issue in all (`ISSUE_CAP_MICROS`, $10
1097 /// by default); the owners can set it (`set_caps`), and staff override.
1098 pub issue_cap_micros: i64,
1099 /// Where on-demand work stops: g1t's ceiling on usage not yet paid
1100 /// for. `UNLIMITED_MICROS` for g1t's own workspaces; 0 for a free one,
1101 /// which has no on-demand usage.
1102 pub ceiling_micros: i64,
1103 /// Usage not yet paid for this month, with prepayment taken off.
1104 pub exposure_micros: i64,
1105 /// Why new compute is paused, for the owner: the limit is reached, a
1106 /// spend spike is waiting for an owner to confirm it, or g1t staff put
1107 /// a hold on it. None when it is not.
1108 pub paused: Option<String>,
1109 // What the workspace's plan gives it, for its pages.
1110 /// What open reservations hold now.
1111 #[serde(default)]
1112 pub held_micros: i64,
1113 /// Paid in advance and not used yet.
1114 #[serde(default)]
1115 pub prepaid_micros: i64,
1116 /// The plan's included usage each month, and what of it is used.
1117 #[serde(default)]
1118 pub included_micros: i64,
1119 #[serde(default)]
1120 pub included_used_micros: i64,
1121 /// How far back the audit log can be read and exported, and what is
1122 /// kept: the plan's days, or what g1t staff set for the account.
1123 pub audit_retention_days: u32,
1124 /// Whether `audit_retention_days` is what staff set for the account
1125 /// rather than the plan's.
1126 #[serde(default)]
1127 pub audit_retention_custom: bool,
1128 /// Private repository storage that is free for every workspace: past
1129 /// it, the plan pays for it and a free workspace's pushes stop.
1130 pub free_private_storage_bytes: i64,
1131 /// The last daily measure of the workspace's private repositories.
1132 pub private_storage_bytes: i64,
1133 /// On a paid plan (not Free): storage past the free amounts below is
1134 /// charged, so nothing is refused for it.
1135 #[serde(default)]
1136 pub has_plan: bool,
1137 /// Package storage free for every workspace, public and private: past
1138 /// it, the plan pays for it and a free workspace's pushes are refused.
1139 #[serde(default)]
1140 pub package_public_free_bytes: i64,
1141 #[serde(default)]
1142 pub package_private_free_bytes: i64,
1143 /// What g1t's open-source pool paid for the workspace this month.
1144 pub oss_paid_micros: i64,
1145 /// Deploy build time this month, every second of it metered.
1146 #[serde(default)]
1147 pub build_seconds_used: u32,
1148 /// Git operations this month, and how many are free for every
1149 /// workspace (past it: metered on the plan, slowed when free).
1150 #[serde(default)]
1151 pub git_operations: u64,
1152 #[serde(default)]
1153 pub git_operations_included: u64,
1154 /// The smallest amount a card is charged when a month closes.
1155 pub min_charge_micros: i64,
1156 /// A spend spike waiting for an owner, or decided.
1157 #[serde(default)]
1158 pub spike: Option<Spike>,
1159 /// Where usage stands against what is included and the limits, from 50%.
1160 #[serde(default)]
1161 pub alerts: Vec<UsageAlert>,
1162}
1163
1164/// One level reached: 50, 75, 90 or 100 percent of something.
1165#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1166#[serde(rename_all = "camelCase")]
1167pub struct UsageAlert {
1168 /// `included` (the plan's included usage), `spend_limit` (the owners'
1169 /// own limit) or `ceiling` (g1t's, on usage not yet paid for).
1170 pub meter: String,
1171 pub level: u32,
1172 pub used_micros: i64,
1173 pub limit_micros: i64,
1174 pub message: String,
1175}
1176
1177/// An hour's spend well above the workspace's usual pace: new compute
1178/// waits until an owner says to keep going.
1179#[derive(Clone, Debug, Serialize, Deserialize)]
1180#[serde(rename_all = "camelCase")]
1181pub struct Spike {
1182 pub id: String,
1183 /// `open` (waiting for an owner), `continued` (an owner said keep
1184 /// going) or `stopped` (an owner said stop).
1185 pub status: String,
1186 /// The hour's spend when it was found, and the usual hour's.
1187 pub hour_micros: i64,
1188 pub average_micros: i64,
1189 pub detected_at: String,
1190 #[serde(default)]
1191 pub decided_by: Option<String>,
1192 #[serde(default)]
1193 pub decided_at: Option<String>,
1194 /// While continued: until when, unless spend doubles again first.
1195 #[serde(default)]
1196 pub until: Option<String>,
1197}
1198
1199/// `reserve`: holds an estimate of a start's cost before the work starts.
1200/// Returns `Outcome<Reservation>`, or a failure whose code says why not:
1201///
1202/// - `paused`: a spend spike waiting for an owner, or a hold.
1203/// - `limit`: the spend limit or g1t's ceiling would be passed.
1204/// - `not_paid`: no plan, and nothing else pays for this kind of work (or
1205/// no card check yet).
1206/// - `trial_used`: the one-time trial is spent.
1207/// - `oss_pool_empty`: the open-source pool, or the repository's share of
1208/// it, is spent this month.
1209///
1210/// The message says exactly what to do, with the page to do it on (such as
1211/// `/acme/-/billing`).
1212#[derive(Debug, Serialize, Deserialize)]
1213#[serde(rename_all = "camelCase")]
1214pub struct ReserveArgs {
1215 pub workspace: String,
1216 pub repo: RepoPath,
1217 /// Whether the repository is public: the open-source pool pays only for
1218 /// public repositories' checks, workflows and merge queue.
1219 pub public: bool,
1220 pub kind: ComputeKind,
1221 /// The most the work is expected to cost g1t, before the margin, in
1222 /// millionths of a dollar (billing adds the margin, as it does to every
1223 /// charge). For an agent, its model's average plus its sandbox for its
1224 /// whole time cap.
1225 #[serde(alias = "estimate_micros")]
1226 pub estimate_micros: i64,
1227 /// An agent run on g1t's hosted models (not the workspace's own
1228 /// provider). Unsaid, an agent run is taken to be one. g1t's daily
1229 /// spend breaker pauses these when g1t is paying for them.
1230 #[serde(default, alias = "hosted_model")]
1231 pub hosted_model: Option<bool>,
1232}
1233
1234#[derive(Clone, Debug, Serialize, Deserialize)]
1235#[serde(rename_all = "camelCase")]
1236pub struct Reservation {
1237 pub id: String,
1238 pub paid_by: PaidBy,
1239 /// What is held, at cost; less than the estimate when a free
1240 /// workspace's last bit of trial credit is all there is.
1241 #[serde(default)]
1242 pub held_micros: i64,
1243 /// RFC 3339: when the hold lapses if never settled.
1244 #[serde(default)]
1245 pub expires_at: String,
1246}
1247
1248/// `settle`: releases a reservation's hold with what the work cost. The
1249/// charge goes on the ledger the usual way. Safe to repeat. Returns
1250/// `Outcome<bool>`: false if it was settled or had lapsed before.
1251#[derive(Debug, Serialize, Deserialize)]
1252#[serde(rename_all = "camelCase")]
1253pub struct SettleArgs {
1254 #[serde(alias = "reservation_id")]
1255 pub reservation_id: String,
1256 /// What the work cost g1t, before the margin.
1257 #[serde(alias = "actual_micros")]
1258 pub actual_micros: i64,
1259}
1260
1261// --- Card checks, the plan, prepayment -------------------------------------
1262
1263/// `card_check`: starts Stripe's page to save and verify a card: a setup
1264/// with 3-D Secure where the card supports it, which the card's bank sees
1265/// as a $0 or $1 authorization that is never charged. The trial and the
1266/// open-source pool need it, and it is the card the plan uses. Owners only.
1267/// Returns `Outcome<Checkout>`; the page's id comes back to `return_url` as
1268/// `session`, for `confirm_card_check`.
1269#[derive(Debug, Serialize, Deserialize)]
1270#[serde(rename_all = "camelCase")]
1271pub struct CardCheckArgs {
1272 pub actor: User,
1273 pub workspace: String,
1274 #[serde(alias = "return_url")]
1275 pub return_url: String,
1276}
1277
1278/// `confirm_card_check`: records the check once Stripe says the card was
1279/// verified, and grants the trial if the month's pool has room and the card
1280/// has not had one before. Safe to repeat. Returns `Outcome<Entitlements>`.
1281#[derive(Debug, Serialize, Deserialize)]
1282pub struct ConfirmCardCheckArgs {
1283 pub workspace: String,
1284 pub viewer: Viewer,
1285 pub session: String,
1286}
1287
1288// --- Limits: raising them, and spikes ---------------------------------------
1289
1290/// A request to g1t: a higher limit, or help with usage that went past
1291/// what was meant.
1292#[derive(Clone, Debug, Serialize, Deserialize)]
1293#[serde(rename_all = "camelCase")]
1294pub struct LimitRequest {
1295 pub id: String,
1296 pub workspace: String,
1297 /// `limit` (raise my limit) or `overage` (spent more than meant to).
1298 pub kind: String,
1299 /// The limit asked for; for an overage, what they think went wrong.
1300 pub amount_micros: i64,
1301 pub reason: String,
1302 pub expected_monthly_micros: i64,
1303 /// `open`, `approved` or `declined`.
1304 pub status: String,
1305 /// What was approved, which may differ from what was asked.
1306 #[serde(default)]
1307 pub decided_micros: Option<i64>,
1308 #[serde(default)]
1309 pub decided_by: Option<String>,
1310 /// The answer, as the owner sees it.
1311 #[serde(default)]
1312 pub answer: Option<String>,
1313 pub created_by: String,
1314 pub created_at: String,
1315 #[serde(default)]
1316 pub decided_at: Option<String>,
1317}
1318
1319/// `request_limit`: an owner asks g1t for more, or for help with usage past
1320/// what they meant. Answered within one business day, in the app and by
1321/// email. Owners only. Returns `Outcome<LimitRequest>`.
1322#[derive(Debug, Serialize, Deserialize)]
1323#[serde(rename_all = "camelCase")]
1324pub struct RequestLimitArgs {
1325 pub actor: User,
1326 pub workspace: String,
1327 /// `limit` or `overage`.
1328 pub kind: String,
1329 #[serde(alias = "amount_micros")]
1330 pub amount_micros: i64,
1331 pub reason: String,
1332 #[serde(default, alias = "expected_monthly_micros")]
1333 pub expected_monthly_micros: i64,
1334}
1335
1336/// `limit_requests`: a workspace's requests, newest first. Members only.
1337/// Returns `Outcome<Vec<LimitRequest>>`.
1338#[derive(Debug, Serialize, Deserialize)]
1339pub struct LimitRequestsArgs {
1340 pub workspace: String,
1341 pub viewer: Viewer,
1342}
1343
1344/// `confirm_spike`: an owner's answer to a spend spike. Keep going lifts the
1345/// pause for 24 hours, or until the hour's spend doubles again; stop keeps
1346/// new compute paused until an owner says to keep going. Owners only.
1347/// Returns `Outcome<Entitlements>`.
1348#[derive(Debug, Serialize, Deserialize)]
1349#[serde(rename_all = "camelCase")]
1350pub struct ConfirmSpikeArgs {
1351 pub actor: User,
1352 pub workspace: String,
1353 #[serde(alias = "keep_going")]
1354 pub keep_going: bool,
1355}
1356
1357/// `set_caps`: the owners' own caps on agents: one run's spend ($0.10 to
1358/// $100) and what the agents on one issue may spend in all ($1 to $1,000).
1359/// None goes back to the default ($2 and $10). A cap g1t staff set for the
1360/// account wins over both. Owners only. Returns `Outcome<Entitlements>`.
1361#[derive(Debug, Serialize, Deserialize)]
1362#[serde(rename_all = "camelCase")]
1363pub struct SetCapsArgs {
1364 pub actor: User,
1365 pub workspace: String,
1366 #[serde(default, alias = "run_cap_micros")]
1367 pub run_cap_micros: Option<i64>,
1368 #[serde(default, alias = "issue_cap_micros")]
1369 pub issue_cap_micros: Option<i64>,
1370}
1371
1372/// What staff see beside a request: the workspace's history with g1t.
1373#[derive(Clone, Debug, Default, Serialize, Deserialize)]
1374#[serde(rename_all = "camelCase")]
1375pub struct WorkspaceHistory {
1376 pub plan: Option<PlanKind>,
1377 /// The last six months, oldest first.
1378 pub months: Vec<MonthFigures>,
1379 /// Live payments that have cleared, and how many.
1380 pub paid_cleared_micros: i64,
1381 pub payments: u32,
1382 pub disputes: u32,
1383 pub declines: u32,
1384 /// The first time the workspace appears in billing, RFC 3339.
1385 pub first_seen: Option<String>,
1386 pub ceiling_micros: Option<i64>,
1387 pub max_ceiling_micros: Option<i64>,
1388 pub spend_limit_micros: Option<i64>,
1389 /// Recent velocity: the last hour, the usual hour over the last week,
1390 /// and the last 24 hours, at price.
1391 pub last_hour_micros: i64,
1392 pub average_hour_micros: i64,
1393 pub last_day_micros: i64,
1394}
1395
1396#[derive(Clone, Debug, Serialize, Deserialize)]
1397#[serde(rename_all = "camelCase")]
1398pub struct LimitRequestReview {
1399 pub request: LimitRequest,
1400 pub history: WorkspaceHistory,
1401}
1402
1403/// `admin_limit_requests`: requests for staff, oldest open first. Returns
1404/// `Vec<LimitRequestReview>`.
1405#[derive(Debug, Default, Serialize, Deserialize)]
1406pub struct AdminLimitRequestsArgs {
1407 /// `open` (the default), `approved`, `declined` or `all`.
1408 #[serde(default)]
1409 pub status: Option<String>,
1410}
1411
1412/// `admin_decide_limit_request`: approve (at the amount asked, or
1413/// `amount_micros`) or decline. The owner is told in the app and by email.
1414/// Recorded with who and why. Returns `Outcome<LimitRequest>`.
1415#[derive(Debug, Serialize, Deserialize)]
1416pub struct AdminDecideLimitRequestArgs {
1417 pub id: String,
1418 /// `approve` or `decline`.
1419 pub decision: String,
1420 #[serde(default)]
1421 pub amount_micros: Option<i64>,
1422 /// What the owner is told, beside the decision.
1423 #[serde(default)]
1424 pub note: String,
1425 pub by: String,
1426}
1427
1428/// `admin_record_payment`: money that reached g1t outside the card pages,
1429/// such as a bank transfer, entered as a payment (it raises the limit like
1430/// one). Recorded with who and the transfer's reference. Returns
1431/// `Outcome<LedgerEntry>`.
1432#[derive(Debug, Serialize, Deserialize)]
1433pub struct AdminRecordPaymentArgs {
1434 pub workspace: String,
1435 pub amount_micros: i64,
1436 /// The bank's reference for the transfer, or Stripe's payment id.
1437 pub reference: String,
1438 pub note: String,
1439 pub by: String,
1440}
1441
1442// --- Overages and goodwill (sudo) --------------------------------------------
1443
1444/// What a one-time goodwill credit would come to: g1t's margin on the
1445/// overage, always, plus as much of its underlying cost as the cap allows.
1446#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1447#[serde(rename_all = "camelCase")]
1448pub struct Goodwill {
1449 /// This month's charges above the workspace's typical month.
1450 pub overage_micros: i64,
1451 /// The part of the overage that is g1t's margin.
1452 pub margin_micros: i64,
1453 /// The part that is what g1t paid its providers.
1454 pub cost_micros: i64,
1455 /// The one-click credit: the margin plus the cost up to the cap.
1456 pub credit_micros: i64,
1457 /// Of the credit, the real cost g1t absorbs.
1458 pub absorbed_micros: i64,
1459}
1460
1461/// A workspace whose month went well past its usual, or hit a spike.
1462#[derive(Clone, Debug, Serialize, Deserialize)]
1463#[serde(rename_all = "camelCase")]
1464pub struct Overage {
1465 pub workspace: String,
1466 pub plan: PlanKind,
1467 /// The median of its last three months' charges.
1468 pub typical_month_micros: i64,
1469 pub this_month_micros: i64,
1470 /// What this month cost g1t, and what g1t keeps of it.
1471 pub cost_micros: i64,
1472 pub margin_micros: i64,
1473 /// A spike this month, if there was one.
1474 pub spike: Option<Spike>,
1475 /// The runs that cost the most this month.
1476 pub top_entries: Vec<LedgerEntry>,
1477 pub goodwill: Goodwill,
1478 /// False when a goodwill credit was given in the last 12 months.
1479 pub goodwill_available: bool,
1480 pub last_goodwill_at: Option<String>,
1481 /// An open overage request from the owner, if there is one.
1482 pub request: Option<LimitRequest>,
1483}
1484
1485/// `admin_overages`: the Overages queue. Returns `Vec<Overage>`.
1486#[derive(Debug, Default, Serialize, Deserialize)]
1487pub struct AdminOveragesArgs {}
1488
1489/// `admin_goodwill`: credits a workspace for accidental usage. With no
1490/// amount, the one-click credit (`Goodwill::credit_micros`), once per
1491/// workspace in 12 months. A larger amount, or a second within 12 months,
1492/// needs a typed reason. It shows on the statement as "Credit from g1t:
1493/// accidental usage on <date>". Returns `Outcome<LedgerEntry>`.
1494#[derive(Debug, Serialize, Deserialize)]
1495pub struct AdminGoodwillArgs {
1496 pub workspace: String,
1497 #[serde(default)]
1498 pub amount_micros: Option<i64>,
1499 /// Why, typed by staff; needed past the one-click credit.
1500 #[serde(default)]
1501 pub reason: String,
1502 /// The day the accidental usage happened, `YYYY-MM-DD`; today if absent.
1503 #[serde(default)]
1504 pub day: Option<String>,
1505 pub by: String,
1506}
1507
1508/// One workspace's recent pace, for sudo's velocity view.
1509#[derive(Clone, Debug, Serialize, Deserialize)]
1510#[serde(rename_all = "camelCase")]
1511pub struct Velocity {
1512 pub workspace: String,
1513 pub plan: PlanKind,
1514 pub last_hour_micros: i64,
1515 pub average_hour_micros: i64,
1516 pub last_day_micros: i64,
1517 pub this_month_micros: i64,
1518 /// The last hour over the usual hour; 0 with no history.
1519 pub ratio: f64,
1520 pub spike: Option<Spike>,
1521 pub first_seen: Option<String>,
1522}
1523
1524/// `admin_velocity`: workspaces spending in the last day, fastest first.
1525/// Returns `Vec<Velocity>`.
1526#[derive(Debug, Default, Serialize, Deserialize)]
1527pub struct AdminVelocityArgs {}
1528
1529#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1530#[serde(rename_all = "snake_case")]
1531pub enum AccountKind {
1532 Workspace,
1533 Enterprise,
1534}
1535
1536/// How an account is charged. Standard unless g1t set otherwise in sudo.
1537#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1538#[serde(rename_all = "camelCase")]
1539pub struct Terms {
1540 pub kind: TermsKind,
1541 /// Off every usage charge, in percent. Custom terms only.
1542 #[serde(default)]
1543 pub discount_percent: u32,
1544 /// A ceiling on unpaid usage that replaces the one trust would give.
1545 #[serde(default)]
1546 pub ceiling_micros: Option<i64>,
1547 /// Why, for whoever looks next.
1548 #[serde(default)]
1549 pub note: String,
1550 /// When the terms end and the account goes back to standard.
1551 #[serde(default)]
1552 pub until: Option<String>,
1553 #[serde(default)]
1554 pub set_by: Option<String>,
1555 #[serde(default)]
1556 pub set_at: Option<String>,
1557}
1558
1559impl Terms {
1560 pub fn standard() -> Self {
1561 Terms {
1562 kind: TermsKind::Standard,
1563 discount_percent: 0,
1564 ceiling_micros: None,
1565 note: String::new(),
1566 until: None,
1567 set_by: None,
1568 set_at: None,
1569 }
1570 }
1571
1572 /// The discount in percent, 0 to 100. Terms from before discounts
1573 /// replaced "comped" read as 100%.
1574 pub fn percent_off(&self) -> u32 {
1575 match self.kind {
1576 TermsKind::Comped => 100,
1577 TermsKind::Custom => self.discount_percent.min(100),
1578 TermsKind::Standard => 0,
1579 }
1580 }
1581
1582 /// A 100% discount: nothing is charged, usage is recorded at its price
1583 /// and discounted in full. g1t's own workspaces and partners. Paid
1584 /// features are on without a plan, and g1t's own spend on it is held to
1585 /// a monthly budget (the terms' ceiling, at cost).
1586 pub fn full_discount(&self) -> bool {
1587 self.percent_off() >= 100
1588 }
1589
1590 /// What a charge becomes under these terms.
1591 pub fn apply(&self, charge_micros: i64) -> i64 {
1592 charge_micros * i64::from(100 - self.percent_off()) / 100
1593 }
1594
1595 /// What a charge at cost plus the margin becomes under these terms, and
1596 /// what the discount took off it (`ledger.discount_micros`), so the
1597 /// statement shows the usage at its price and the discount beside it,
1598 /// and a discount below cost plus the margin is counted as given, never
1599 /// lost. A 100% discount takes it all.
1600 pub fn discounted(&self, charge_micros: i64) -> (i64, i64) {
1601 let charged = self.apply(charge_micros);
1602 (charged, (charge_micros - charged).max(0))
1603 }
1604
1605 /// How the statement and sudo name the terms: `100% discount`, `30% off`.
1606 pub fn discount_label(&self) -> Option<String> {
1607 match self.percent_off() {
1608 0 => None,
1609 100 => Some("100% discount".to_owned()),
1610 percent => Some(format!("{percent}% off")),
1611 }
1612 }
1613}
1614
1615#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1616#[serde(rename_all = "snake_case")]
1617pub enum TermsKind {
1618 /// Prices as published, limits by trust.
1619 Standard,
1620 /// Before discounts: what a 100% discount is now. Read as one
1621 /// (`Terms::percent_off`); billing never writes it (migration 0039).
1622 Comped,
1623 /// A discount (up to 100%), a ceiling, or both.
1624 Custom,
1625}
1626
1627/// `stripe_webhook`: an event from Stripe, as the API received it: the raw
1628/// body and its `Stripe-Signature` header. Billing checks the signature
1629/// against the secret of the endpoint it registered, and handles each
1630/// event once. Returns `Outcome<bool>`: false for one already handled.
1631#[derive(Debug, Serialize, Deserialize)]
1632pub struct StripeWebhookArgs {
1633 pub payload: String,
1634 pub signature: String,
1635}
1636
1637/// `admin_stripe`: where billing stands with Stripe. Staff only. Returns
1638/// `StripeStatus`. With `fix: true`, first enables the destination at
1639/// billing's address and gives it the events billing needs.
1640#[derive(Debug, Default, Serialize, Deserialize)]
1641pub struct AdminStripeArgs {
1642 #[serde(default)]
1643 pub fix: bool,
1644 #[serde(default)]
1645 pub by: Option<String>,
1646}
1647
1648#[derive(Clone, Debug, Serialize, Deserialize)]
1649#[serde(rename_all = "camelCase")]
1650pub struct StripeStatus {
1651 /// `test` or `live`, from the key; `off` without one.
1652 pub mode: String,
1653 /// Whether `STRIPE_WEBHOOK_SECRET` is set, so events can be checked.
1654 pub secret_set: bool,
1655 /// The destination at billing's address in Stripe, as Stripe has it.
1656 pub webhook: Option<StripeWebhook>,
1657 /// Events billing handles that the destination does not send.
1658 pub missing_events: Vec<String>,
1659 /// The latest events handled, newest first.
1660 pub recent_events: Vec<StripeEventSummary>,
1661 /// What went wrong reading or fixing the destination, if it did.
1662 pub error: Option<String>,
1663}
1664
1665#[derive(Clone, Debug, Serialize, Deserialize)]
1666#[serde(rename_all = "camelCase")]
1667pub struct StripeWebhook {
1668 pub url: String,
1669 pub endpoint_id: String,
1670 /// `enabled` or `disabled`.
1671 pub status: String,
1672 pub events: Vec<String>,
1673 pub created_at: String,
1674}
1675
1676#[derive(Clone, Debug, Serialize, Deserialize)]
1677#[serde(rename_all = "camelCase")]
1678pub struct StripeEventSummary {
1679 pub id: String,
1680 pub kind: String,
1681 pub outcome: String,
1682 pub received_at: String,
1683}
1684
1685/// `admin_enterprise_billing`: where an enterprise's invoices go. Creates
1686/// or updates its Stripe customer. Returns `Outcome<BillingAccount>`.
1687#[derive(Debug, Serialize, Deserialize)]
1688pub struct AdminEnterpriseBillingArgs {
1689 pub id: String,
1690 pub email: String,
1691 pub by: String,
1692}
1693
1694/// `admin_enterprise_address`: the enterprise's billing address and tax ID,
1695/// saved on its Stripe customer (made by `admin_enterprise_billing`).
1696/// Stripe Tax works its invoices' tax out from the address; an invoice is
1697/// not sent without one. Returns `Outcome<bool>`.
1698#[derive(Debug, Serialize, Deserialize)]
1699#[serde(rename_all = "camelCase")]
1700pub struct AdminEnterpriseAddressArgs {
1701 pub id: String,
1702 pub address: PostalAddress,
1703 #[serde(default, alias = "tax_id_type")]
1704 pub tax_id_type: Option<String>,
1705 #[serde(default, alias = "tax_id")]
1706 pub tax_id: Option<String>,
1707 pub by: String,
1708}
1709
1710/// `admin_invoice_enterprise`: sends an enterprise its invoice now, for
1711/// what its workspaces owe, rather than waiting for the month to close.
1712/// Returns `Outcome<EnterpriseInvoice>`.
1713#[derive(Debug, Serialize, Deserialize)]
1714pub struct AdminInvoiceEnterpriseArgs {
1715 pub id: String,
1716 pub by: String,
1717}
1718
1719/// An enterprise's invoice: one line per workspace, paid on Stripe.
1720#[derive(Clone, Debug, Serialize, Deserialize)]
1721#[serde(rename_all = "camelCase")]
1722pub struct EnterpriseInvoice {
1723 pub invoice_id: String,
1724 /// Stripe's page for it, where it is paid.
1725 pub hosted_url: Option<String>,
1726 pub amount_micros: i64,
1727 /// `open`, `paid`, `overdue` or `void`.
1728 pub status: String,
1729 pub period: String,
1730 pub lines: Vec<InvoiceLine>,
1731 pub created_at: String,
1732}
1733
1734#[derive(Clone, Debug, Serialize, Deserialize)]
1735#[serde(rename_all = "camelCase")]
1736pub struct InvoiceLine {
1737 pub workspace: String,
1738 pub amount_micros: i64,
1739}
1740
1741/// A workspace's invoice from g1t: one per month, and one each time it is
1742/// charged near its limit. Itemised, charged to the card on file, and kept
1743/// in Stripe's billing page with its PDF.
1744#[derive(Clone, Debug, Serialize, Deserialize)]
1745#[serde(rename_all = "camelCase")]
1746pub struct WorkspaceInvoice {
1747 pub invoice_id: String,
1748 pub workspace: String,
1749 /// `month` (2026-10) or `threshold`.
1750 pub reason: String,
1751 pub period: String,
1752 pub amount_micros: i64,
1753 /// `paid`, `open`, `failed` or `void`.
1754 pub status: String,
1755 pub hosted_url: Option<String>,
1756 pub pdf_url: Option<String>,
1757 pub lines: Vec<InvoiceItem>,
1758 pub created_at: String,
1759 /// The card processing fee on top of `amount_micros`, when the invoice
1760 /// is charged to a card; never part of the usage it pays for.
1761 #[serde(default)]
1762 pub fee_micros: i64,
1763 /// The tax Stripe added on top, once it is known (after paying).
1764 #[serde(default)]
1765 pub tax_micros: i64,
1766}
1767
1768#[derive(Clone, Debug, Serialize, Deserialize)]
1769#[serde(rename_all = "camelCase")]
1770pub struct InvoiceItem {
1771 pub description: String,
1772 pub amount_micros: i64,
1773}
1774
1775/// `invoices`: a workspace's invoices from g1t, newest first. Members
1776/// only. Returns `Outcome<Vec<WorkspaceInvoice>>`.
1777#[derive(Debug, Serialize, Deserialize)]
1778pub struct InvoicesArgs {
1779 pub workspace: String,
1780 pub viewer: Viewer,
1781}
1782
1783/// `admin_workspace_invoices`: the same, for staff. Returns
1784/// `Vec<WorkspaceInvoice>`.
1785#[derive(Debug, Serialize, Deserialize)]
1786pub struct AdminWorkspaceInvoicesArgs {
1787 pub workspace: String,
1788}
1789
1790/// `statement`: a month of a workspace's ledger, grouped by day (or by
1791/// project) with a line per kind of charge. Members only. Returns
1792/// `Outcome<Statement>`.
1793#[derive(Debug, Serialize, Deserialize)]
1794pub struct StatementArgs {
1795 pub workspace: String,
1796 pub viewer: Viewer,
1797 /// YYYY-MM; this month when absent.
1798 #[serde(default)]
1799 pub month: Option<String>,
1800 /// `day` (the default) or `project`.
1801 #[serde(default)]
1802 pub group: Option<String>,
1803}
1804
1805#[derive(Clone, Debug, Serialize, Deserialize)]
1806#[serde(rename_all = "camelCase")]
1807pub struct Statement {
1808 pub month: String,
1809 /// Months with any entries, newest first.
1810 pub months: Vec<String>,
1811 pub groups: Vec<StatementGroup>,
1812 pub totals: StatementTotals,
1813}
1814
1815#[derive(Clone, Debug, Serialize, Deserialize)]
1816#[serde(rename_all = "camelCase")]
1817pub struct StatementGroup {
1818 /// The day (YYYY-MM-DD) or the project (`owner/name`, or empty).
1819 pub key: String,
1820 pub label: String,
1821 pub lines: Vec<StatementLine>,
1822 /// What the group's charges come to.
1823 pub charged_micros: i64,
1824 /// Its usage at price, and what the discount took off it.
1825 #[serde(default)]
1826 pub price_micros: i64,
1827 #[serde(default)]
1828 pub discount_micros: i64,
1829}
1830
1831#[derive(Clone, Debug, Serialize, Deserialize)]
1832#[serde(rename_all = "camelCase")]
1833pub struct StatementLine {
1834 /// Agent runs, Sandbox time, Deployments, Payments, Credits from g1t,
1835 /// Refunds, and, for older entries, Runs on your own model provider.
1836 pub kind: String,
1837 pub count: u32,
1838 /// Charges positive; money in (payments, credits) negative.
1839 pub charged_micros: i64,
1840 pub cost_micros: i64,
1841 /// Of the usage on the line, what was paid for before it was charged:
1842 /// by the plan's included usage, the trial credit, g1t's open-source
1843 /// pool, or g1t itself. Not in `charged_micros`.
1844 #[serde(default)]
1845 pub covered_micros: i64,
1846 /// Usage at its price: charged, plus what paid for it and what the
1847 /// discount took off. Zero for money in.
1848 #[serde(default)]
1849 pub price_micros: i64,
1850 /// What the account's discount took off the line's price.
1851 #[serde(default)]
1852 pub discount_micros: i64,
1853 /// On the `Tax` and `Card processing fees` lines: what was paid with
1854 /// payments on top of what reached the balance (negative for what a
1855 /// refund gave back). Never in `charged_micros` or the balance.
1856 #[serde(default)]
1857 pub passed_micros: i64,
1858}
1859
1860#[derive(Clone, Debug, Serialize, Deserialize)]
1861#[serde(rename_all = "camelCase")]
1862pub struct StatementTotals {
1863 pub charged_micros: i64,
1864 pub paid_micros: i64,
1865 pub cost_micros: i64,
1866 pub entries: u32,
1867 /// Usage at price, and what the discount took off it: charged is the
1868 /// price less the discount and what paid for it.
1869 #[serde(default)]
1870 pub price_micros: i64,
1871 #[serde(default)]
1872 pub discount_micros: i64,
1873 /// The account's discount now, in percent; absent without one.
1874 #[serde(default)]
1875 pub discount_percent: Option<u32>,
1876 /// What paid for usage before it was charged, one line per source,
1877 /// such as "Paid by g1t's open-source pool".
1878 #[serde(default)]
1879 pub covered: Vec<Covered>,
1880 /// Owed when the month closed but under the minimum charge, so it
1881 /// carries over to the next invoice. Zero when nothing carried.
1882 #[serde(default)]
1883 pub carried_micros: i64,
1884 /// Tax and card processing fees paid with the month's payments, on top
1885 /// of `paid_micros`.
1886 #[serde(default)]
1887 pub tax_micros: i64,
1888 #[serde(default)]
1889 pub card_fee_micros: i64,
1890}
1891
1892/// One source that paid for usage before it was charged.
1893#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1894#[serde(rename_all = "camelCase")]
1895pub struct Covered {
1896 /// `included`, `trial`, `oss_pool` or `given`.
1897 pub source: String,
1898 /// "Paid by your plan's included usage", "Paid by your trial credit",
1899 /// "Paid by g1t's open-source pool", "Covered by g1t".
1900 pub label: String,
1901 pub micros: i64,
1902}
1903
1904/// `statement_entries`: one statement line's entries, newest first, 50 at
1905/// a time (`before` = the last id seen). Returns `Outcome<Vec<LedgerEntry>>`.
1906#[derive(Debug, Serialize, Deserialize)]
1907pub struct StatementEntriesArgs {
1908 pub workspace: String,
1909 pub viewer: Viewer,
1910 pub month: String,
1911 pub kind: String,
1912 #[serde(default)]
1913 pub day: Option<String>,
1914 #[serde(default)]
1915 pub project: Option<String>,
1916 #[serde(default)]
1917 pub before: Option<String>,
1918}
1919
1920// --- Sales (sudo.g1t.sh) ------------------------------------------------------
1921//
1922// What staff need to know to reach out: who is growing, who is close to
1923// their limit, who was declined, who has become a steady customer. And what
1924// was done about it: a stage, an owner on g1t's side, a next step, notes.
1925
1926/// Why a workspace is worth a look.
1927#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1928#[serde(rename_all = "snake_case")]
1929pub enum SignalKind {
1930 /// At its limit, or its own spend limit: work is stopped.
1931 AtLimit,
1932 /// Past 80% of what is available to it: about to need more.
1933 NearCeiling,
1934 /// Its card was declined or a payment disputed.
1935 Declined,
1936 /// This month is well ahead of last month.
1937 Growing,
1938 /// Became Established: the ceiling now follows its spend.
1939 Established,
1940 /// Paid g1t for the first time.
1941 FirstPayment,
1942 /// Spending enough that custom terms or an enterprise may suit it.
1943 HighSpend,
1944 /// Costs g1t more on Cloudflare than it pays, over 30 days: a pricing
1945 /// gap or abuse to look at (billing's `margin`).
1946 CostOverRevenue,
1947}
1948
1949#[derive(Clone, Debug, Serialize, Deserialize)]
1950#[serde(rename_all = "camelCase")]
1951pub struct Signal {
1952 pub workspace: String,
1953 pub kind: SignalKind,
1954 /// One sentence, with the figures.
1955 pub detail: String,
1956 /// The figure that matters, such as this month's spend.
1957 pub value_micros: i64,
1958 /// Its sales stage, if staff gave it one.
1959 pub stage: Option<String>,
1960 pub owner: Option<String>,
1961 #[serde(default)]
1962 pub next_step: Option<String>,
1963 /// When the next step is due, `YYYY-MM-DD`.
1964 #[serde(default)]
1965 pub next_at: Option<String>,
1966}
1967
1968/// `admin_invoices`: every invoice g1t has sent, workspaces' and
1969/// enterprises', newest first. Returns `Vec<InvoiceSummary>`.
1970#[derive(Debug, Default, Serialize, Deserialize)]
1971pub struct AdminInvoicesArgs {
1972 /// `paid`, `open`, `failed`, `overdue` or `void`.
1973 #[serde(default)]
1974 pub status: Option<String>,
1975 /// YYYY-MM, by when it was sent.
1976 #[serde(default)]
1977 pub month: Option<String>,
1978}
1979
1980#[derive(Clone, Debug, Serialize, Deserialize)]
1981#[serde(rename_all = "camelCase")]
1982pub struct InvoiceSummary {
1983 pub invoice_id: String,
1984 /// `workspace` or `enterprise`.
1985 pub kind: String,
1986 /// The workspace's slug, or the enterprise's account id.
1987 pub account: String,
1988 /// What to call it: the workspace, or the enterprise's name.
1989 pub name: String,
1990 pub reason: String,
1991 pub period: String,
1992 pub amount_micros: i64,
1993 pub status: String,
1994 pub hosted_url: Option<String>,
1995 pub created_at: String,
1996 pub paid_at: Option<String>,
1997}
1998
1999/// `admin_audit`: every change made in sudo, and by Stripe, newest first.
2000/// Returns `Vec<AdminAction>`.
2001#[derive(Debug, Default, Serialize, Deserialize)]
2002pub struct AdminAuditArgs {
2003 #[serde(default)]
2004 pub by: Option<String>,
2005 #[serde(default)]
2006 pub action: Option<String>,
2007 /// Only those before this time, for paging.
2008 #[serde(default)]
2009 pub before: Option<String>,
2010}
2011
2012/// `admin_signals`: every workspace worth reaching out to, most urgent
2013/// first. Returns `Vec<Signal>`.
2014#[derive(Debug, Default, Serialize, Deserialize)]
2015pub struct AdminSignalsArgs {}
2016
2017/// What staff are doing about a workspace.
2018#[derive(Clone, Debug, Serialize, Deserialize)]
2019#[serde(rename_all = "camelCase")]
2020pub struct SalesRecord {
2021 pub workspace: String,
2022 /// `none`, `lead`, `contacted`, `negotiating`, `won`, `lost` or `churn_risk`.
2023 pub stage: String,
2024 /// The staff member looking after it.
2025 pub owner: Option<String>,
2026 pub next_step: Option<String>,
2027 /// RFC 3339 date.
2028 pub next_at: Option<String>,
2029 pub notes: Vec<SalesNote>,
2030 pub updated_at: Option<String>,
2031}
2032
2033#[derive(Clone, Debug, Serialize, Deserialize)]
2034#[serde(rename_all = "camelCase")]
2035pub struct SalesNote {
2036 pub id: String,
2037 pub text: String,
2038 pub by: String,
2039 pub created_at: String,
2040}
2041
2042/// `admin_sales`: a workspace's sales record. Returns `SalesRecord`.
2043#[derive(Debug, Serialize, Deserialize)]
2044pub struct AdminSalesArgs {
2045 pub workspace: String,
2046}
2047
2048/// `admin_set_sales`: its stage, owner and next step. Returns `Outcome<SalesRecord>`.
2049#[derive(Debug, Serialize, Deserialize)]
2050pub struct AdminSetSalesArgs {
2051 pub workspace: String,
2052 pub stage: String,
2053 #[serde(default)]
2054 pub owner: Option<String>,
2055 #[serde(default)]
2056 pub next_step: Option<String>,
2057 #[serde(default)]
2058 pub next_at: Option<String>,
2059 pub by: String,
2060}
2061
2062/// `admin_add_note`. Returns `Outcome<SalesRecord>`.
2063#[derive(Debug, Serialize, Deserialize)]
2064pub struct AdminAddNoteArgs {
2065 pub workspace: String,
2066 pub text: String,
2067 pub by: String,
2068}
2069
2070/// `admin_overview`: the business at a glance. Returns `Overview`.
2071#[derive(Debug, Default, Serialize, Deserialize)]
2072pub struct AdminOverviewArgs {}
2073
2074#[derive(Clone, Debug, Serialize, Deserialize)]
2075#[serde(rename_all = "camelCase")]
2076pub struct Overview {
2077 /// YYYY-MM.
2078 pub month: String,
2079 /// The last six months, oldest first, all workspaces together.
2080 pub months: Vec<MonthFigures>,
2081 /// This month by kind of usage: models, sandbox, deployments, plans.
2082 pub by_kind: Vec<KindFigures>,
2083 pub paying_workspaces: u32,
2084 pub stopped: u32,
2085 pub near_ceiling: u32,
2086 pub declined: u32,
2087 /// Sent and not yet paid, workspaces and enterprises.
2088 pub open_invoices_micros: i64,
2089 /// Follow-ups due today or earlier.
2090 pub follow_ups_due: u32,
2091 /// The capped budgets g1t pays from, this month.
2092 #[serde(default)]
2093 pub pools: Option<Pools>,
2094 /// This month's revenue: usage charged plus the plan's price paid.
2095 #[serde(default)]
2096 pub revenue_micros: i64,
2097 /// Workspaces on the paid plan now, and what their price comes to a
2098 /// month.
2099 #[serde(default)]
2100 pub active_plans: u32,
2101 #[serde(default)]
2102 pub plan_mrr_micros: i64,
2103 /// What g1t gave this month, by source, apart from its margin.
2104 #[serde(default)]
2105 pub given: Vec<GivenFigures>,
2106 /// g1t's own and Flagon's workspaces this month: what their use cost,
2107 /// and why they are not charged.
2108 #[serde(default)]
2109 pub internal: Vec<InternalUse>,
2110 /// Open limit requests, and workspaces in the Overages queue.
2111 #[serde(default)]
2112 pub open_requests: u32,
2113 #[serde(default)]
2114 pub overages: u32,
2115 /// Spend spikes waiting for an owner.
2116 #[serde(default)]
2117 pub open_spikes: u32,
2118}
2119
2120/// What g1t gave this month from one source.
2121#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
2122#[serde(rename_all = "camelCase")]
2123pub struct GivenFigures {
2124 /// `internal`, `trial`, `oss_pool`, `goodwill` or `covered`.
2125 pub source: String,
2126 pub label: String,
2127 /// At price, and what it cost g1t.
2128 pub micros: i64,
2129 pub cost_micros: i64,
2130}
2131
2132/// One internal workspace's use this month.
2133#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
2134#[serde(rename_all = "camelCase")]
2135pub struct InternalUse {
2136 pub workspace: String,
2137 /// Why it is not charged: its terms' note.
2138 pub reason: String,
2139 pub cost_micros: i64,
2140 pub entries: u32,
2141}
2142
2143/// g1t's capped budgets for free usage, this calendar month (UTC).
2144#[derive(Clone, Debug, Default, Serialize, Deserialize)]
2145#[serde(rename_all = "camelCase")]
2146pub struct Pools {
2147 /// YYYY-MM.
2148 pub month: String,
2149 /// Trial grants made this month, against the month's pool.
2150 pub trial_granted_micros: i64,
2151 pub trial_pool_micros: i64,
2152 pub trial_grants: u32,
2153 /// What the open-source pool paid this month, against its cap.
2154 pub oss_used_micros: i64,
2155 pub oss_pool_micros: i64,
2156 /// Each public repository's monthly cap on the pool.
2157 pub oss_repo_micros: i64,
2158}
2159
2160#[derive(Clone, Debug, Serialize, Deserialize)]
2161#[serde(rename_all = "camelCase")]
2162pub struct KindFigures {
2163 pub kind: String,
2164 pub charged_micros: i64,
2165 pub cost_micros: i64,
2166}
2167
2168// --- Staff (sudo.g1t.sh) ------------------------------------------------------
2169//
2170// Called only by the sudo app, which only g1t staff can reach (behind
2171// Cloudflare Access). Each change names who made it, and is kept in the
2172// audit log.
2173
2174/// `admin_accounts`: every billing account, with where each stands this
2175/// month. Returns `Vec<AccountSummary>`.
2176#[derive(Debug, Default, Serialize, Deserialize)]
2177pub struct AdminAccountsArgs {
2178 #[serde(default)]
2179 pub query: Option<String>,
2180 /// Exactly these workspaces' accounts, such as one page of sudo's
2181 /// list; every account with activity when absent.
2182 #[serde(default)]
2183 pub workspaces: Option<Vec<String>>,
2184}
2185
2186#[derive(Clone, Debug, Serialize, Deserialize)]
2187#[serde(rename_all = "camelCase")]
2188pub struct AccountSummary {
2189 pub account: BillingAccount,
2190 pub limit: Limit,
2191 /// Charged this month, after terms.
2192 pub charged_micros: i64,
2193 /// What this month's usage cost g1t.
2194 pub cost_micros: i64,
2195 /// Paid, ever.
2196 pub paid_micros: i64,
2197 /// The same figures for each of the account's workspaces that has
2198 /// any, so staff can see what one member of an enterprise used.
2199 #[serde(default)]
2200 pub by_workspace: Vec<WorkspaceFigures>,
2201 /// The last six months, oldest first, for trends.
2202 #[serde(default)]
2203 pub months: Vec<MonthFigures>,
2204}
2205
2206/// One month of an account's billing.
2207#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
2208#[serde(rename_all = "camelCase")]
2209pub struct MonthFigures {
2210 /// YYYY-MM.
2211 pub month: String,
2212 /// Usage charged, after what paid for it first.
2213 pub charged_micros: i64,
2214 /// What usage cost g1t: only what g1t paid for, never a workspace's own
2215 /// model provider.
2216 pub cost_micros: i64,
2217 pub paid_micros: i64,
2218 /// The plan's monthly price, paid.
2219 #[serde(default)]
2220 pub plans_micros: i64,
2221 /// What g1t gave, at price: internal (comped) use, trials, the
2222 /// open-source pool, goodwill credits and what g1t covered. Not margin.
2223 #[serde(default)]
2224 pub given_micros: i64,
2225}
2226
2227/// One workspace's share of an [`AccountSummary`].
2228#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
2229#[serde(rename_all = "camelCase")]
2230pub struct WorkspaceFigures {
2231 pub workspace: String,
2232 pub charged_micros: i64,
2233 pub cost_micros: i64,
2234 pub paid_micros: i64,
2235}
2236
2237/// `admin_account`: one account in full. Returns `Outcome<AccountDetail>`.
2238#[derive(Debug, Serialize, Deserialize)]
2239pub struct AdminAccountArgs {
2240 /// An account id, or a workspace slug.
2241 pub id: String,
2242}
2243
2244#[derive(Clone, Debug, Serialize, Deserialize)]
2245#[serde(rename_all = "camelCase")]
2246pub struct AccountDetail {
2247 pub summary: AccountSummary,
2248 /// Each workspace's limit, for an enterprise.
2249 pub workspaces: Vec<Limit>,
2250 pub ledger: Vec<LedgerEntry>,
2251 pub audit: Vec<AdminAction>,
2252}
2253
2254/// `admin_set_terms`. Returns `Outcome<BillingAccount>`.
2255#[derive(Debug, Serialize, Deserialize)]
2256pub struct AdminSetTermsArgs {
2257 pub id: String,
2258 pub terms: Terms,
2259 pub by: String,
2260}
2261
2262/// `admin_create_enterprise`. Returns `Outcome<BillingAccount>`.
2263#[derive(Debug, Serialize, Deserialize)]
2264pub struct AdminCreateEnterpriseArgs {
2265 pub name: String,
2266 pub workspaces: Vec<String>,
2267 pub by: String,
2268}
2269
2270/// `admin_attach`: moves a workspace onto an enterprise account, or back
2271/// onto its own with `account: None`. Returns `Outcome<BillingAccount>`.
2272#[derive(Debug, Serialize, Deserialize)]
2273pub struct AdminAttachArgs {
2274 pub workspace: String,
2275 pub account: Option<String>,
2276 pub by: String,
2277}
2278
2279/// Why g1t gave a workspace credit.
2280#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
2281#[serde(rename_all = "snake_case")]
2282pub enum CreditKind {
2283 /// Marketing: a welcome, a referral, an event. Given away when spent.
2284 Promotional,
2285 /// An apology, or accidental usage forgiven. Given away when spent.
2286 #[default]
2287 Goodwill,
2288 /// Money back for something that went wrong. Not given away: it gives
2289 /// back money already paid, so it comes off what was paid on the day
2290 /// it refunds, and what it pays for later is paid for.
2291 Refund,
2292 /// Bought by the workspace (prepaid AI): money paid in up front, owed
2293 /// as usage until spent. What it pays for is paid for, never given.
2294 /// Staff never give it; its ledger line is a payment, not `crd…`.
2295 Purchased,
2296}
2297
2298impl CreditKind {
2299 pub fn as_str(self) -> &'static str {
2300 match self {
2301 CreditKind::Promotional => "promotional",
2302 CreditKind::Goodwill => "goodwill",
2303 CreditKind::Refund => "refund",
2304 CreditKind::Purchased => "purchased",
2305 }
2306 }
2307
2308 pub fn parse(text: &str) -> Option<CreditKind> {
2309 match text {
2310 "promotional" => Some(CreditKind::Promotional),
2311 "goodwill" => Some(CreditKind::Goodwill),
2312 "refund" => Some(CreditKind::Refund),
2313 "purchased" => Some(CreditKind::Purchased),
2314 _ => None,
2315 }
2316 }
2317
2318 /// As people read it: `Promotional`.
2319 pub fn label(self) -> &'static str {
2320 match self {
2321 CreditKind::Promotional => "Promotional",
2322 CreditKind::Goodwill => "Goodwill",
2323 CreditKind::Refund => "Refund",
2324 CreditKind::Purchased => "Purchased",
2325 }
2326 }
2327}
2328
2329/// `admin_credit`: credit g1t gives a workspace: promotional, goodwill or a
2330/// refund, with a note, and optionally an expiry. It is spent before
2331/// anything paid in advance, the soonest-expiring first. The workspace's
2332/// owners are emailed. Returns `Outcome<LedgerEntry>`.
2333#[derive(Debug, Serialize, Deserialize)]
2334pub struct AdminCreditArgs {
2335 pub workspace: String,
2336 pub amount_micros: i64,
2337 pub note: String,
2338 pub by: String,
2339 #[serde(default)]
2340 pub kind: CreditKind,
2341 /// RFC 3339; unused credit stops counting then. Never for a refund.
2342 #[serde(default)]
2343 pub expires_at: Option<String>,
2344 /// A refund: what it refunds, in a line, and the day of it
2345 /// (`YYYY-MM-DD`; today if absent).
2346 #[serde(default)]
2347 pub refund_for: Option<String>,
2348 #[serde(default)]
2349 pub refund_day: Option<String>,
2350}
2351
2352/// One credit g1t gave, with what of it was used: spent on usage, the
2353/// soonest-expiring grant first, before anything paid in advance.
2354#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
2355#[serde(rename_all = "camelCase")]
2356pub struct CreditGrant {
2357 /// `crd_…`, the grant's ledger reference.
2358 pub id: String,
2359 pub workspace: String,
2360 pub kind: CreditKind,
2361 pub amount_micros: i64,
2362 pub used_micros: i64,
2363 /// What can still be spent: nothing once it expired or was revoked.
2364 pub left_micros: i64,
2365 pub note: String,
2366 #[serde(default)]
2367 pub refund_for: Option<String>,
2368 #[serde(default)]
2369 pub refund_day: Option<String>,
2370 pub expires_at: Option<String>,
2371 pub created_by: String,
2372 pub created_at: String,
2373 /// `open`, `used`, `expired` or `revoked`.
2374 pub state: String,
2375 #[serde(default)]
2376 pub closed_at: Option<String>,
2377 #[serde(default)]
2378 pub closed_note: Option<String>,
2379 #[serde(default)]
2380 pub closed_by: Option<String>,
2381 /// What expiring or revoking took off the balance.
2382 #[serde(default)]
2383 pub closed_micros: i64,
2384 /// What it pays for: `all` usage, or `models` only (agent runs' model
2385 /// cost), which is spent first.
2386 #[serde(default)]
2387 pub scope: String,
2388 /// Where it came from: `staff`, `purchase` or `promo_code`.
2389 #[serde(default)]
2390 pub source: String,
2391}
2392
2393/// `credits` (`Outcome<Credits>`, `AccountArgs`): a workspace's credits from
2394/// g1t, newest first, for its members.
2395#[derive(Clone, Debug, Default, Serialize, Deserialize)]
2396#[serde(rename_all = "camelCase")]
2397pub struct Credits {
2398 pub grants: Vec<CreditGrant>,
2399 /// What is left to spend, in all.
2400 pub left_micros: i64,
2401}
2402
2403/// `admin_credits`: every credit g1t gave, newest first, filtered. Returns
2404/// `AdminCredits`.
2405#[derive(Debug, Default, Serialize, Deserialize)]
2406pub struct AdminCreditsArgs {
2407 #[serde(default)]
2408 pub workspace: Option<String>,
2409 #[serde(default)]
2410 pub kind: Option<CreditKind>,
2411 /// `YYYY-MM`: given that month.
2412 #[serde(default)]
2413 pub month: Option<String>,
2414 /// Given by this member of staff.
2415 #[serde(default)]
2416 pub by: Option<String>,
2417}
2418
2419/// One month's credits of one kind: given, used on usage that month, and
2420/// taken back unused (expired or revoked).
2421#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
2422#[serde(rename_all = "camelCase")]
2423pub struct CreditMonth {
2424 pub month: String,
2425 pub kind: CreditKind,
2426 pub given_micros: i64,
2427 pub grants: u32,
2428 pub used_micros: i64,
2429 pub expired_micros: i64,
2430 pub revoked_micros: i64,
2431}
2432
2433#[derive(Clone, Debug, Default, Serialize, Deserialize)]
2434#[serde(rename_all = "camelCase")]
2435pub struct AdminCredits {
2436 /// At most 200.
2437 pub grants: Vec<CreditGrant>,
2438 /// The last 12 months, newest first, whatever the month filter.
2439 pub months: Vec<CreditMonth>,
2440 /// Who has given credit, for the filter.
2441 pub staff: Vec<String>,
2442}
2443
2444/// `admin_revoke_credit`: what is left of a grant, taken off the balance,
2445/// with why. Returns `Outcome<CreditGrant>`.
2446#[derive(Debug, Serialize, Deserialize)]
2447pub struct AdminRevokeCreditArgs {
2448 pub id: String,
2449 pub note: String,
2450 pub by: String,
2451}
2452
2453/// `admin_reset_billing`: a test workspace's billing wiped, so it starts
2454/// again as a new customer. Only while billing runs on Stripe's test key;
2455/// never a comped workspace or one an enterprise pays for. `confirm` is the
2456/// workspace's slug typed out. Returns `Outcome<BillingReset>`.
2457#[derive(Debug, Serialize, Deserialize)]
2458pub struct AdminResetBillingArgs {
2459 pub workspace: String,
2460 pub confirm: String,
2461 pub note: String,
2462 pub by: String,
2463}
2464
2465/// What a reset removed.
2466#[derive(Clone, Debug, Serialize, Deserialize)]
2467#[serde(rename_all = "camelCase")]
2468pub struct BillingReset {
2469 pub workspace: String,
2470 pub rows: u32,
2471 /// Whether the costs analysis ran again after it, so the margin
2472 /// figures no longer hold the workspace's past usage.
2473 #[serde(default)]
2474 pub refreshed: bool,
2475}
2476
2477/// One change made in sudo.
2478#[derive(Clone, Debug, Serialize, Deserialize)]
2479#[serde(rename_all = "camelCase")]
2480pub struct AdminAction {
2481 pub id: String,
2482 pub account: String,
2483 pub action: String,
2484 pub detail: String,
2485 pub by: String,
2486 pub created_at: String,
2487}
2488
2489/// What a feature's plan costs and includes.
2490#[derive(Clone, Debug, Serialize, Deserialize)]
2491#[serde(rename_all = "camelCase")]
2492pub struct Plan {
2493 pub feature: Feature,
2494 pub title: String,
2495 /// Charged every month while the plan is on, in cents, excluding tax.
2496 pub monthly_cents: u32,
2497 /// The card processing fee on top each month, in cents (0 when the
2498 /// fee is off). Excluding tax, like the price.
2499 #[serde(default)]
2500 pub card_fee_cents: u32,
2501 /// What the monthly price includes, one line each, for people to read.
2502 pub includes: Vec<String>,
2503 /// How usage past the allowance is charged, for people to read.
2504 pub overage: String,
2505}
2506
2507#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
2508#[serde(rename_all = "snake_case")]
2509pub enum SubscriptionStatus {
2510 /// Paid up; the feature works.
2511 Active,
2512 /// Paid up to the end of the period, and ends then.
2513 Canceling,
2514 /// The last payment failed; the feature is off until it is paid.
2515 PastDue,
2516 /// Ended.
2517 Canceled,
2518}
2519
2520impl SubscriptionStatus {
2521 /// Whether the feature works in this state.
2522 pub fn on(self) -> bool {
2523 matches!(self, SubscriptionStatus::Active | SubscriptionStatus::Canceling)
2524 }
2525}
2526
2527/// A workspace's plan for one feature.
2528#[derive(Clone, Debug, Serialize, Deserialize)]
2529#[serde(rename_all = "camelCase")]
2530pub struct Subscription {
2531 pub feature: Feature,
2532 pub status: SubscriptionStatus,
2533 /// RFC 3339: when the period paid for ends, and the plan renews or
2534 /// ends.
2535 pub period_end: Option<String>,
2536 /// Username of whoever turned it on.
2537 pub started_by: String,
2538 /// RFC 3339.
2539 pub started_at: String,
2540}
2541
2542/// A feature as a workspace sees it: what it costs, and its plan if it has
2543/// one.
2544#[derive(Clone, Debug, Serialize, Deserialize)]
2545#[serde(rename_all = "camelCase")]
2546pub struct FeatureState {
2547 pub plan: Plan,
2548 pub subscription: Option<Subscription>,
2549 /// Whether the feature works for the workspace now.
2550 pub on: bool,
2551 /// On without a plan: comped terms, or given by g1t. Nothing to pay
2552 /// and nothing to turn off.
2553 #[serde(default)]
2554 pub included: bool,
2555}
2556
2557/// `features`: every paid feature and the workspace's plan for each.
2558/// Members only. Returns `Outcome<Vec<FeatureState>>`.
2559#[derive(Debug, Serialize, Deserialize)]
2560pub struct FeaturesArgs {
2561 pub workspace: String,
2562 pub viewer: Viewer,
2563}
2564
2565/// `subscribe`: starts the card page for a feature's monthly plan. Owners
2566/// only. Returns `Outcome<Checkout>`; the page's id comes back to
2567/// `return_url` as `session`, for `confirm_subscription`.
2568#[derive(Debug, Serialize, Deserialize)]
2569#[serde(rename_all = "camelCase")]
2570pub struct SubscribeArgs {
2571 pub actor: User,
2572 pub workspace: String,
2573 pub feature: Feature,
2574 pub return_url: String,
2575}
2576
2577/// `confirm_subscription`: turns the feature on once the processor says
2578/// the plan was paid for. Safe to call any number of times. Returns
2579/// `Outcome<FeatureState>`.
2580#[derive(Debug, Serialize, Deserialize)]
2581pub struct ConfirmSubscriptionArgs {
2582 pub workspace: String,
2583 pub viewer: Viewer,
2584 pub session: String,
2585}
2586
2587/// `admin_log`: a staff change another service made to a workspace, kept
2588/// in sudo's audit log with billing's own (`admin_audit`). For identity's
2589/// restores and purges of deleted workspaces. Returns `bool`.
2590#[derive(Debug, Serialize, Deserialize)]
2591pub struct AdminLogArgs {
2592 pub workspace: String,
2593 pub action: String,
2594 pub detail: String,
2595 /// The staff member's email.
2596 pub by: String,
2597}
2598
2599/// `close_workspace`: settles a workspace that is about to be deleted.
2600/// Owners only. Refused while it has an invoice that failed, while it
2601/// holds prepaid credit, or while it owes money it cannot be charged for
2602/// now; otherwise what it owes is invoiced to its card at once (no
2603/// minimum), its plan is cancelled at Stripe straight away, and its
2604/// account is marked closed, so the month-end close, autopay and limit
2605/// warnings pass it by. Its ledger, invoices and statements stay. With
2606/// `dry_run`, only says whether it could, changing nothing. Returns
2607/// `Outcome<bool>`.
2608#[derive(Debug, Serialize, Deserialize)]
2609#[serde(rename_all = "camelCase")]
2610pub struct CloseWorkspaceArgs {
2611 pub actor: User,
2612 pub workspace: String,
2613 #[serde(default)]
2614 pub dry_run: bool,
2615}
2616
2617/// `cancel_subscription` (`resume` false) ends a plan at the end of the
2618/// period paid for; with `resume` true, takes that back. Owners only.
2619/// Returns `Outcome<FeatureState>`.
2620#[derive(Debug, Serialize, Deserialize)]
2621pub struct CancelSubscriptionArgs {
2622 pub actor: User,
2623 pub workspace: String,
2624 pub feature: Feature,
2625 #[serde(default)]
2626 pub resume: bool,
2627}
2628
2629/// `has_feature`: whether a feature works for a workspace now, asked by the
2630/// service that provides it before doing paid work. Returns
2631/// `Outcome<bool>`: a failure, with the reason to show, when it does not.
2632/// True everywhere when no card processor is configured.
2633#[derive(Debug, Serialize, Deserialize)]
2634pub struct HasFeatureArgs {
2635 pub workspace: String,
2636 pub feature: Feature,
2637}
2638
2639/// `free_workspaces`: which of `workspaces` are free, that is on no paid
2640/// plan. Paid is the g1t plan, an enterprise's terms, or a discount of
2641/// 100% (g1t's own workspaces). Identity asks before a workspace is made
2642/// (a person owns at most one free workspace) and before anyone is added
2643/// to one (a free workspace cannot invite). Returns `Vec<String>`, the
2644/// free ones, lower-cased; none where payments are not set up.
2645#[derive(Debug, Serialize, Deserialize)]
2646pub struct FreeWorkspacesArgs {
2647 pub workspaces: Vec<String>,
2648}
2649
2650/// `charge_feature`: usage of a feature past its plan's allowance, charged
2651/// from the workspace's credit at cost plus the margin, whatever
2652/// `FREE_WHILE_BUILDING` says. Called by the service that provides it.
2653/// Charged once per `reference`. Returns `Outcome<bool>`: false if that
2654/// reference was charged before.
2655#[derive(Debug, Serialize, Deserialize)]
2656#[serde(rename_all = "camelCase")]
2657pub struct ChargeFeatureArgs {
2658 pub workspace: String,
2659 pub feature: Feature,
2660 /// What it cost g1t, in millionths of a dollar, before the margin.
2661 pub cost_micros: i64,
2662 pub description: String,
2663 /// `namespace/name`, when the usage was one repository's.
2664 pub repo: Option<String>,
2665 /// Unique to this charge, e.g. `deployments/acme/2026-10`.
2666 pub reference: String,
2667 /// For a build: how long it ran. The plan's included build time this
2668 /// month pays for what it can, and only the rest of `cost_micros` is
2669 /// charged.
2670 #[serde(default)]
2671 pub build_seconds: Option<u32>,
2672}
2673
2674// ---------------------------------------------------------------------
2675// Costs and margin: what Cloudflare charges g1t against what g1t
2676// charges (billing's costs.rs, margin.rs and pricing.rs). Staff only.
2677// ---------------------------------------------------------------------
2678
2679/// `admin_costs`: the Costs & margin page. Returns `CostsReport`.
2680#[derive(Debug, Default, Serialize, Deserialize)]
2681pub struct AdminCostsArgs {
2682 /// How many days back, 7 to 90; 30 when absent.
2683 #[serde(default)]
2684 pub days: Option<u32>,
2685}
2686
2687/// One of g1t's products on one day.
2688#[derive(Clone, Debug, Default, Serialize, Deserialize)]
2689#[serde(rename_all = "camelCase")]
2690pub struct CostDay {
2691 pub day: String,
2692 pub bucket: String,
2693 /// What Cloudflare charged g1t.
2694 pub cf_cost_micros: i64,
2695 /// What g1t's meters recorded it cost, at the price book's cost.
2696 pub own_cost_micros: i64,
2697 /// What customers were charged for it at price, before included
2698 /// usage, trials and pools paid for some.
2699 pub value_micros: i64,
2700 /// Of that, what workspaces paid.
2701 pub cash_micros: i64,
2702}
2703
2704/// One product over the range.
2705#[derive(Clone, Debug, Default, Serialize, Deserialize)]
2706#[serde(rename_all = "camelCase")]
2707pub struct ProductMargin {
2708 pub bucket: String,
2709 pub title: String,
2710 /// The cost the margin is taken from: Cloudflare's bill, or g1t's own
2711 /// figure for what Cloudflare does not bill (models).
2712 pub cost_micros: i64,
2713 pub cf_cost_micros: i64,
2714 pub own_cost_micros: i64,
2715 pub value_micros: i64,
2716 pub margin_micros: i64,
2717 pub margin_percent: Option<f64>,
2718 /// `cloudflare` or `ledger`.
2719 pub cost_source: String,
2720 /// Running g1t itself, paid for by the plan.
2721 pub overhead: bool,
2722}
2723
2724/// All of g1t over the range: money in against every cost, and against
2725/// the cost of what was sold (every cost less what g1t gave away).
2726#[derive(Clone, Debug, Default, Serialize, Deserialize)]
2727#[serde(rename_all = "camelCase")]
2728pub struct OverallMargin {
2729 /// What workspaces paid for usage, and for the plan.
2730 pub usage_micros: i64,
2731 pub plans_micros: i64,
2732 pub cost_micros: i64,
2733 pub margin_micros: i64,
2734 pub margin_percent: Option<f64>,
2735 /// Of `cost_micros`, what went on usage g1t gave away on purpose:
2736 /// comped workspaces, free periods, the trial and the open-source pool.
2737 #[serde(default)]
2738 pub given_micros: i64,
2739 /// Money in against `cost_micros - given_micros`.
2740 #[serde(default)]
2741 pub sold_margin_micros: i64,
2742 #[serde(default)]
2743 pub sold_margin_percent: Option<f64>,
2744 /// What was sold, apart: usage (`usage_micros` against what that usage
2745 /// cost, less what was given), running g1t (`plans_micros` against the
2746 /// platform's cost, less its given share) and what no mapping names.
2747 #[serde(default)]
2748 pub usage_cost_micros: i64,
2749 #[serde(default)]
2750 pub usage_margin_micros: i64,
2751 #[serde(default)]
2752 pub usage_margin_percent: Option<f64>,
2753 #[serde(default)]
2754 pub running_cost_micros: i64,
2755 #[serde(default)]
2756 pub unmapped_cost_micros: i64,
2757 /// `given_micros` by why: comped workspaces, free use (free periods,
2758 /// free allowances, overruns g1t covered), the trial, the open-source pool.
2759 #[serde(default)]
2760 pub given_comped_micros: i64,
2761 #[serde(default)]
2762 pub given_free_micros: i64,
2763 #[serde(default)]
2764 pub given_trial_micros: i64,
2765 #[serde(default)]
2766 pub given_pool_micros: i64,
2767 /// What discounts on an account's terms took below cost plus the
2768 /// margin: given, so a discounted sale is not margin lost.
2769 #[serde(default)]
2770 pub given_discount_micros: i64,
2771 /// Credits from g1t spent on usage, by kind: given, so usage paid for
2772 /// with them is never money in. Refunds are not here: they come off
2773 /// money in on the day they refund.
2774 #[serde(default)]
2775 pub given_credit_promotional_micros: i64,
2776 #[serde(default)]
2777 pub given_credit_goodwill_micros: i64,
2778 /// Credits over the range: given (every kind), spent on usage, and
2779 /// refunds' money given back.
2780 #[serde(default)]
2781 pub credits_given_micros: i64,
2782 #[serde(default)]
2783 pub credits_used_micros: i64,
2784 #[serde(default)]
2785 pub credits_refunded_micros: i64,
2786 /// `cost_micros` by who g1t pays: Cloudflare's bill (billed amounts,
2787 /// after the included allowances), and model providers (the ledger's
2788 /// cost of the tokens, which Cloudflare's bill does not show).
2789 /// What the plan's included usage paid for, at price (the ledger's
2790 /// `credit_micros`, comped workspaces left out): money in for usage,
2791 /// paid out of `plans_micros`.
2792 #[serde(default)]
2793 pub included_micros: i64,
2794 #[serde(default)]
2795 pub cloudflare_cost_micros: i64,
2796 #[serde(default)]
2797 pub models_cost_micros: i64,
2798 /// Tax collected with payments over the range, net of refunds: owed to
2799 /// the tax authorities, never in cash or revenue.
2800 #[serde(default)]
2801 pub tax_collected_micros: i64,
2802 /// Card processing fees passed on with card payments, net of refunds:
2803 /// they pay Stripe's fee, so they are not revenue either.
2804 #[serde(default)]
2805 pub card_fees_micros: i64,
2806}
2807
2808/// A count, cost or leak that does not add up.
2809#[derive(Clone, Debug, Serialize, Deserialize)]
2810#[serde(rename_all = "camelCase")]
2811pub struct CostDrift {
2812 pub bucket: String,
2813 pub title: String,
2814 /// `count` (units g1t counted against Cloudflare's), `cost` (the bill
2815 /// against the price book's cost of the same usage; for models, what AI
2816 /// Gateway priced g1t's provider traffic at against the ledger's model
2817 /// cost), `unpriced` (model usage AI Gateway put no price on, so its
2818 /// cost is not the providers'), or `leak`.
2819 pub kind: String,
2820 pub ours: f64,
2821 pub cloudflare: f64,
2822 pub delta_percent: Option<f64>,
2823 pub detail: String,
2824 pub found_at: String,
2825}
2826
2827/// A margin alert, open while its condition lasts.
2828#[derive(Clone, Debug, Serialize, Deserialize)]
2829#[serde(rename_all = "camelCase")]
2830pub struct MarginAlert {
2831 pub id: String,
2832 /// `margin`, `overall`, `leak`, `drift` or `workspace`.
2833 pub kind: String,
2834 /// The product, or the workspace.
2835 pub subject: String,
2836 pub detail: String,
2837 pub since: String,
2838 pub opened_at: String,
2839 pub emailed_at: Option<String>,
2840}
2841
2842/// A change to a price the reconciler measured.
2843#[derive(Clone, Debug, Serialize, Deserialize)]
2844#[serde(rename_all = "camelCase")]
2845pub struct PriceProposal {
2846 pub id: String,
2847 pub meter: String,
2848 pub title: String,
2849 pub unit: String,
2850 pub current_cost_micros: f64,
2851 pub proposed_cost_micros: f64,
2852 pub change_percent: f64,
2853 pub markup_percent: u32,
2854 pub reason: String,
2855 /// `keeper` or `reconciler`.
2856 pub source: String,
2857 /// Far off the current cost: look before approving.
2858 pub suspect: bool,
2859 /// `open`, `applied`, `approved`, `rejected` or `superseded`.
2860 pub status: String,
2861 pub created_at: String,
2862 pub decided_at: Option<String>,
2863 pub decided_by: Option<String>,
2864 pub note: Option<String>,
2865 /// When it takes or took effect, once approved or applied.
2866 pub effective_at: Option<String>,
2867}
2868
2869/// One version of one meter's price. Never changed once written.
2870#[derive(Clone, Debug, Serialize, Deserialize)]
2871#[serde(rename_all = "camelCase")]
2872pub struct PriceVersion {
2873 pub id: String,
2874 pub meter: String,
2875 pub version: u32,
2876 pub cost_micros: f64,
2877 pub markup_percent: u32,
2878 pub price_micros: f64,
2879 pub effective_at: String,
2880 pub reason: String,
2881 pub created_by: String,
2882 /// When the price book took it on; absent while it waits for its date.
2883 pub applied_at: Option<String>,
2884}
2885
2886/// What a workspace cost g1t over the range, Cloudflare's costs shared
2887/// out by g1t's own meters, against what it paid.
2888#[derive(Clone, Debug, Serialize, Deserialize)]
2889#[serde(rename_all = "camelCase")]
2890pub struct WorkspaceCost {
2891 pub workspace: String,
2892 pub cost_micros: i64,
2893 pub revenue_micros: i64,
2894 /// Of `cost_micros`, what g1t gave away.
2895 #[serde(default)]
2896 pub given_micros: i64,
2897 /// One of g1t's own (comped) workspaces.
2898 pub internal: bool,
2899}
2900
2901/// One Cloudflare meter over the range, and the product it is a cost of.
2902#[derive(Clone, Debug, Serialize, Deserialize)]
2903#[serde(rename_all = "camelCase")]
2904pub struct CostLineSummary {
2905 pub product: String,
2906 pub meter: String,
2907 pub raw_name: String,
2908 pub unit: String,
2909 pub source: String,
2910 pub quantity: f64,
2911 pub cost_micros: i64,
2912 /// Absent when no mapping claims it.
2913 pub bucket: Option<String>,
2914}
2915
2916/// A row of the mapping from Cloudflare's meters to g1t's products.
2917#[derive(Clone, Debug, Serialize, Deserialize)]
2918#[serde(rename_all = "camelCase")]
2919pub struct CostMapping {
2920 pub product: String,
2921 pub meter: String,
2922 pub bucket: String,
2923 pub price_meter: Option<String>,
2924 pub own_meter: Option<String>,
2925 pub scale_to_own: bool,
2926 pub drift_percent: f64,
2927 pub note: String,
2928 pub updated_at: String,
2929 pub updated_by: String,
2930}
2931
2932/// The guardrails on prices and the alerts.
2933#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
2934#[serde(rename_all = "camelCase")]
2935pub struct CostSettings {
2936 /// Apply small moves without staff.
2937 pub auto_apply: bool,
2938 /// The largest move applied without staff, either way, in percent.
2939 pub auto_apply_percent: f64,
2940 /// Days between telling customers of a rise and charging it.
2941 pub notice_days: u32,
2942 /// Below this margin, in percent, for `alert_days` days in a row, alert.
2943 pub margin_floor_percent: f64,
2944 pub alert_days: u32,
2945 /// Days with less cost than this say nothing about a margin.
2946 pub min_daily_cost_micros: i64,
2947 /// A workspace costing more than its revenue times this, over 30 days,
2948 /// and at least `anomaly_floor_micros`, is flagged.
2949 pub anomaly_factor: f64,
2950 pub anomaly_floor_micros: i64,
2951 /// Pass Stripe's card fee on as its own line on every card payment (the
2952 /// plan, Security and quality, prepaying, AI credit, auto-reload and
2953 /// invoices charged to a card), never on a bank transfer or an invoice
2954 /// sent to be paid (`card_fee_percent` and `card_fee_fixed` in the
2955 /// price book). On by default.
2956 #[serde(default = "yes")]
2957 pub card_fee: bool,
2958}
2959
2960impl Default for CostSettings {
2961 fn default() -> Self {
2962 CostSettings {
2963 auto_apply: true,
2964 auto_apply_percent: 25.0,
2965 notice_days: 14,
2966 margin_floor_percent: 10.0,
2967 alert_days: 3,
2968 min_daily_cost_micros: 100_000,
2969 anomaly_factor: 1.0,
2970 anomaly_floor_micros: 1_000_000,
2971 card_fee: true,
2972 }
2973 }
2974}
2975
2976/// The Costs & margin page.
2977#[derive(Clone, Debug, Default, Serialize, Deserialize)]
2978#[serde(rename_all = "camelCase")]
2979pub struct CostsReport {
2980 /// A token to read Cloudflare's bill is set.
2981 pub configured: bool,
2982 /// When Cloudflare's bill was last read.
2983 pub fetched_at: Option<String>,
2984 /// The days shown, YYYY-MM-DD.
2985 pub since: String,
2986 pub until: String,
2987 pub days: Vec<CostDay>,
2988 pub products: Vec<ProductMargin>,
2989 pub overall: OverallMargin,
2990 pub drift: Vec<CostDrift>,
2991 pub alerts: Vec<MarginAlert>,
2992 pub proposals: Vec<PriceProposal>,
2993 pub versions: Vec<PriceVersion>,
2994 pub top_workspaces: Vec<WorkspaceCost>,
2995 pub lines: Vec<CostLineSummary>,
2996 pub mappings: Vec<CostMapping>,
2997 pub settings: CostSettings,
2998 /// g1t's own spend against its two caps.
2999 #[serde(default)]
3000 pub caps: SpendCaps,
3001}
3002
3003/// What g1t itself pays for, against its caps (billing's `budget`): the
3004/// daily breaker on all of it, and each comped account's monthly budget.
3005/// One of Cloudflare's subscriptions, at what it comes to a month.
3006#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
3007#[serde(rename_all = "camelCase")]
3008pub struct FixedCost {
3009 pub name: String,
3010 pub monthly_micros: i64,
3011}
3012
3013/// At cost, never at price. What sudo's Costs page and its red bar show.
3014#[derive(Clone, Debug, Default, Serialize, Deserialize)]
3015#[serde(rename_all = "camelCase")]
3016pub struct SpendCaps {
3017 /// Today (UTC), YYYY-MM-DD, and this month, YYYY-MM.
3018 pub day: String,
3019 pub month: String,
3020 /// What g1t paid for itself today across every workspace: comped work,
3021 /// the trial and open-source pools, free workspaces' overruns, and
3022 /// anything charged without real money behind it.
3023 pub today_micros: i64,
3024 /// `PLATFORM_DAILY_SPEND_CAP_MICROS`. Zero: no breaker.
3025 pub daily_cap_micros: i64,
3026 /// The breaker is open: new hosted-model agent runs that g1t would pay
3027 /// for wait until tomorrow (UTC) or until staff lift it.
3028 pub tripped: bool,
3029 pub tripped_at: Option<String>,
3030 /// Staff lifted it for the rest of the day.
3031 pub lifted_by: Option<String>,
3032 pub lifted_at: Option<String>,
3033 pub lift_note: Option<String>,
3034 /// This month so far, by what paid: `comped`, `trial`, `oss`, `given`,
3035 /// `unpaid`.
3036 pub month_buckets: Vec<SpendBucket>,
3037 /// Each comped account's monthly budget.
3038 pub comped: Vec<CompedBudget>,
3039 /// Free workspaces' share of this month's reconciled costs (git,
3040 /// storage, platform), through yesterday.
3041 pub free_tier_micros: i64,
3042 /// Cloudflare's subscriptions a month: as read from Cloudflare each
3043 /// day, else `CLOUDFLARE_FIXED_MONTHLY_MICROS`, an estimate.
3044 pub fixed_monthly_micros: i64,
3045 /// `cloudflare` or `estimate`.
3046 #[serde(default)]
3047 pub fixed_source: String,
3048 #[serde(default)]
3049 pub fixed_read_at: Option<String>,
3050 /// Each subscription, when read from Cloudflare.
3051 #[serde(default)]
3052 pub fixed_items: Vec<FixedCost>,
3053 /// Money in this month, through the last reconciled day.
3054 pub revenue_micros: i64,
3055}
3056
3057#[derive(Clone, Debug, Default, Serialize, Deserialize)]
3058#[serde(rename_all = "camelCase")]
3059pub struct SpendBucket {
3060 pub bucket: String,
3061 pub title: String,
3062 pub micros: i64,
3063}
3064
3065/// A comped account's monthly budget: what its work cost g1t this month.
3066#[derive(Clone, Debug, Default, Serialize, Deserialize)]
3067#[serde(rename_all = "camelCase")]
3068pub struct CompedBudget {
3069 pub account: String,
3070 pub name: String,
3071 pub used_micros: i64,
3072 /// Zero: no budget.
3073 pub ceiling_micros: i64,
3074 /// The ceiling is `COMPED_MONTHLY_CEILING_MICROS`, not the account's own.
3075 pub default_ceiling: bool,
3076 /// 50, 75, 90, 100, or 0.
3077 pub level: u32,
3078}
3079
3080/// `admin_spend_caps`: g1t's own spend against its caps. Returns `SpendCaps`.
3081#[derive(Debug, Default, Serialize, Deserialize)]
3082pub struct AdminSpendCapsArgs {}
3083
3084/// `admin_lift_breaker`: lets hosted-model runs start again for the rest
3085/// of today (UTC), with why. Recorded in the audit log. Returns
3086/// `Outcome<SpendCaps>`.
3087#[derive(Debug, Serialize, Deserialize)]
3088pub struct AdminLiftBreakerArgs {
3089 pub note: String,
3090 pub by: String,
3091}
3092
3093/// `admin_cost_alerts`: the open margin alerts, for sudo's banner.
3094/// Returns `Vec<MarginAlert>`.
3095#[derive(Debug, Default, Serialize, Deserialize)]
3096pub struct AdminCostAlertsArgs {}
3097
3098/// `admin_decide_proposal`: approve or reject a price proposal. An
3099/// approved rise takes effect after the notice period. Returns
3100/// `Outcome<PriceProposal>`.
3101#[derive(Debug, Serialize, Deserialize)]
3102pub struct AdminDecideProposalArgs {
3103 pub id: String,
3104 /// `approve` or `reject`.
3105 pub decision: String,
3106 #[serde(default)]
3107 pub note: String,
3108 pub by: String,
3109}
3110
3111/// `admin_set_cost_settings`. Returns `Outcome<CostSettings>`.
3112#[derive(Debug, Serialize, Deserialize)]
3113pub struct AdminSetCostSettingsArgs {
3114 pub settings: CostSettings,
3115 pub by: String,
3116}
3117
3118/// `admin_set_cost_mapping`: adds, changes or (with `remove`) removes a
3119/// mapping row. Returns `Outcome<CostMapping>`.
3120#[derive(Debug, Serialize, Deserialize)]
3121pub struct AdminSetCostMappingArgs {
3122 pub product: String,
3123 pub meter: String,
3124 #[serde(default)]
3125 pub bucket: String,
3126 #[serde(default)]
3127 pub price_meter: Option<String>,
3128 #[serde(default)]
3129 pub own_meter: Option<String>,
3130 #[serde(default)]
3131 pub scale_to_own: bool,
3132 #[serde(default)]
3133 pub drift_percent: Option<f64>,
3134 #[serde(default)]
3135 pub note: String,
3136 #[serde(default)]
3137 pub remove: bool,
3138 pub by: String,
3139}
3140
3141/// `admin_run_costs`: reads Cloudflare's bill and reconciles now, as the
3142/// daily run does. Returns `Outcome<CostsRun>`.
3143#[derive(Debug, Default, Serialize, Deserialize)]
3144pub struct AdminRunCostsArgs {
3145 #[serde(default)]
3146 pub by: String,
3147}
3148
3149#[derive(Clone, Debug, Default, Serialize, Deserialize)]
3150#[serde(rename_all = "camelCase")]
3151pub struct CostsRun {
3152 pub lines: u32,
3153 pub days: u32,
3154 pub proposals: u32,
3155 pub alerts: u32,
3156 /// What could not be read, in words.
3157 pub problems: Vec<String>,
3158}
3159
3160// --- The Usage page ----------------------------------------------------------
3161
3162/// The product families the Usage page groups meters into, in order, with
3163/// their names.
3164pub const PRODUCTS: [(&str, &str); 8] = [
3165 ("agent", "Agent"),
3166 ("sandboxes", "Sandboxes"),
3167 ("gateway", "AI Gateway"),
3168 ("deployments", "Deployments"),
3169 ("git_storage", "Git & storage"),
3170 ("packages", "Packages"),
3171 ("security", "Security & quality"),
3172 ("search", "Search"),
3173];
3174
3175/// `usage_report`: a workspace's usage over a range of days, at price, by
3176/// product, meter, project and day. The figures are the ledger's: the same
3177/// lines the statement and invoices read, so every page agrees. Members
3178/// only. Returns `Outcome<UsageReport>`.
3179#[derive(Debug, Serialize, Deserialize)]
3180#[serde(rename_all = "camelCase")]
3181pub struct UsageReportArgs {
3182 pub workspace: String,
3183 pub viewer: Viewer,
3184 /// The first day, `YYYY-MM-DD` (UTC).
3185 pub from: String,
3186 /// The last day, `YYYY-MM-DD`, included.
3187 pub until: String,
3188 /// Only these product families (`agent`, `sandboxes`…); all when empty.
3189 #[serde(default)]
3190 pub products: Vec<String>,
3191 /// Only these projects (repositories, `owner/name`); all when empty.
3192 #[serde(default)]
3193 pub projects: Vec<String>,
3194}
3195
3196/// What usage came to over a range, and what paid for it. `price_micros`
3197/// less `discount_micros`, `included_micros` and `credits_micros` is
3198/// `charged_micros`.
3199#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
3200#[serde(rename_all = "camelCase")]
3201pub struct UsageTotals {
3202 /// Usage at price, metered usage not yet charged (`pending_micros`)
3203 /// included.
3204 pub price_micros: i64,
3205 /// What the account's discount took off.
3206 pub discount_micros: i64,
3207 /// What the plan's included usage, the trial and g1t's pools paid.
3208 pub included_micros: i64,
3209 /// What credit paid: AI credit, credit from g1t.
3210 pub credits_micros: i64,
3211 /// What is left for the workspace to pay.
3212 pub charged_micros: i64,
3213 /// Metered this month and charged when it closes (storage, git
3214 /// operations, scans, embeddings, domains), at price.
3215 pub pending_micros: i64,
3216 /// What it cost g1t, before any markup.
3217 pub cost_micros: i64,
3218}
3219
3220/// One day's usage of one product, at price.
3221#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
3222#[serde(rename_all = "camelCase")]
3223pub struct UsageDay {
3224 /// `YYYY-MM-DD`.
3225 pub day: String,
3226 pub product: String,
3227 pub micros: i64,
3228}
3229
3230/// How much of an allowance is used, in the meter's unit.
3231#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
3232#[serde(rename_all = "camelCase")]
3233pub struct Allowance {
3234 pub used: f64,
3235 pub of: f64,
3236 /// `bytes`, `operations`, `dollars`…
3237 pub unit: String,
3238}
3239
3240/// One project's part of a meter.
3241#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
3242#[serde(rename_all = "camelCase")]
3243pub struct ProjectUsage {
3244 /// `owner/name`, or empty for usage that is not one project's.
3245 pub project: String,
3246 pub micros: i64,
3247 pub quantity: f64,
3248}
3249
3250/// One meter over the range.
3251#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
3252#[serde(rename_all = "camelCase")]
3253pub struct MeterLine {
3254 /// `agent_models`, `agent_rate`, `sandbox`, `builds`…
3255 pub key: String,
3256 pub label: String,
3257 pub product: String,
3258 /// What `quantity` counts: `tokens`, `seconds`, `bytes`, `operations`,
3259 /// `entries`.
3260 pub unit: String,
3261 pub quantity: f64,
3262 /// At price.
3263 pub micros: i64,
3264 /// Of `micros`, metered this month and charged when it closes.
3265 #[serde(default)]
3266 pub pending_micros: i64,
3267 /// Every day of the range, oldest first, at price: the sparkline.
3268 pub daily: Vec<i64>,
3269 #[serde(default)]
3270 pub allowance: Option<Allowance>,
3271 pub by_project: Vec<ProjectUsage>,
3272}
3273
3274/// A part of a product, such as the agent's runs, reviews and plans.
3275#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
3276#[serde(rename_all = "camelCase")]
3277pub struct FeatureUsage {
3278 pub key: String,
3279 pub label: String,
3280 pub micros: i64,
3281 pub count: u32,
3282}
3283
3284/// One product family over the range.
3285#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
3286#[serde(rename_all = "camelCase")]
3287pub struct ProductUsage {
3288 pub key: String,
3289 pub label: String,
3290 pub micros: i64,
3291 pub meters: Vec<MeterLine>,
3292 /// For the agent: by what it was doing (runs, reviews, plans, checks).
3293 #[serde(default)]
3294 pub features: Vec<FeatureUsage>,
3295}
3296
3297#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
3298#[serde(rename_all = "camelCase")]
3299pub struct UsageReport {
3300 pub from: String,
3301 pub until: String,
3302 pub totals: UsageTotals,
3303 /// Each day and product with usage, oldest first.
3304 pub days: Vec<UsageDay>,
3305 /// Every product family, in order, even with nothing used.
3306 pub products: Vec<ProductUsage>,
3307 /// Every project with usage in the range, for the filter.
3308 pub projects: Vec<String>,
3309 /// The plan's included usage this month, when the workspace has it.
3310 #[serde(default)]
3311 pub included: Option<Allowance>,
3312 /// The account's discount, in percent, when it has one.
3313 #[serde(default)]
3314 pub discount_percent: Option<u32>,
3315 /// AI credit left now, and credit from g1t for everything.
3316 pub ai_credit_micros: i64,
3317 pub credit_micros: i64,
3318 /// The trial credit left, for a workspace on its trial.
3319 #[serde(default)]
3320 pub trial_micros: Option<i64>,
3321 pub plan: PlanKind,
3322 /// Nothing is charged while g1t is being built out.
3323 pub free: bool,
3324}
3325
3326// --- AI credit -----------------------------------------------------------------
3327
3328/// Auto-reload: when AI credit falls below `threshold_micros`, the saved
3329/// card is charged to bring it back to `target_micros`, at most
3330/// `monthly_max_micros` in a calendar month. Off by default. A failed
3331/// charge turns it off and tells the owners.
3332#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
3333#[serde(rename_all = "camelCase")]
3334pub struct AiReload {
3335 pub enabled: bool,
3336 pub threshold_micros: i64,
3337 pub target_micros: i64,
3338 pub monthly_max_micros: i64,
3339 /// Reloaded this month so far.
3340 #[serde(default)]
3341 pub reloaded_micros: i64,
3342 /// When it last failed and was turned off, and why.
3343 #[serde(default)]
3344 pub failed_at: Option<String>,
3345 #[serde(default)]
3346 pub error: Option<String>,
3347}
3348
3349/// The card fee passed on when AI credit is bought by card.
3350#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
3351#[serde(rename_all = "camelCase")]
3352pub struct CardFee {
3353 pub on: bool,
3354 /// Per dollar charged, in millionths: 29,000 is 2.9%.
3355 pub percent_micros: f64,
3356 pub fixed_cents: u32,
3357}
3358
3359/// `ai_credit` (`AccountArgs`): a workspace's prepaid AI credit, what it
3360/// pays for and how it is bought. Members only. Returns `Outcome<AiCredit>`.
3361#[derive(Clone, Debug, Serialize, Deserialize)]
3362#[serde(rename_all = "camelCase")]
3363pub struct AiCredit {
3364 /// What is left to spend on Agent and AI Gateway usage.
3365 pub balance_micros: i64,
3366 /// Of it, bought (paid) and given (promotional).
3367 pub purchased_micros: i64,
3368 pub given_micros: i64,
3369 /// Its grants, newest first.
3370 pub grants: Vec<CreditGrant>,
3371 /// A 100% discount: AI usage is free, shown at its price then the
3372 /// discount. Nothing to buy.
3373 pub free_via_discount: bool,
3374 /// Invoiced terms (an enterprise): models are billed after use, so no
3375 /// credit is needed.
3376 pub postpaid: bool,
3377 /// Whether new runs on g1t's models are refused now for want of credit.
3378 pub blocked: bool,
3379 /// Whether the workspace may buy it: on the plan, not free.
3380 pub can_buy: bool,
3381 pub presets_cents: Vec<u32>,
3382 pub min_cents: u32,
3383 pub max_cents: u32,
3384 pub card_fee: CardFee,
3385 pub reload: AiReload,
3386 /// The agent rate per million tokens, now, at price.
3387 pub agent_rate_micros: f64,
3388 /// The markup on models' provider price, in percent.
3389 pub model_markup_percent: u32,
3390 /// The markup on AI Gateway's provider price, in percent.
3391 pub gateway_markup_percent: u32,
3392 /// The AI credit given once on starting the plan.
3393 pub upgrade_credit_micros: i64,
3394 /// How long bought credit lasts, in days.
3395 pub expires_days: u32,
3396}
3397
3398/// `buy_ai_credit`: Stripe's page to buy AI credit, one payment by card,
3399/// with the card fee as its own line. Owners only. Returns
3400/// `Outcome<Checkout>`; the page's id comes back to `return_url` as
3401/// `ai_credit`, for `confirm_ai_credit`.
3402#[derive(Debug, Serialize, Deserialize)]
3403#[serde(rename_all = "camelCase")]
3404pub struct BuyAiCreditArgs {
3405 pub actor: User,
3406 pub workspace: String,
3407 /// The credit, in cents; the card fee is added on top.
3408 #[serde(alias = "amount_cents")]
3409 pub amount_cents: u32,
3410 #[serde(alias = "return_url")]
3411 pub return_url: String,
3412}
3413
3414/// `confirm_ai_credit`: credits a purchase once Stripe says it was paid,
3415/// once. Safe to repeat; the webhook does the same. Returns
3416/// `Outcome<AiCredit>`.
3417#[derive(Debug, Serialize, Deserialize)]
3418pub struct ConfirmAiCreditArgs {
3419 pub workspace: String,
3420 pub viewer: Viewer,
3421 pub session: String,
3422}
3423
3424/// `set_ai_reload`: auto-reload's settings. Owners only. Returns
3425/// `Outcome<AiCredit>`.
3426#[derive(Debug, Serialize, Deserialize)]
3427#[serde(rename_all = "camelCase")]
3428pub struct SetAiReloadArgs {
3429 pub actor: User,
3430 pub workspace: String,
3431 pub enabled: bool,
3432 #[serde(alias = "threshold_micros")]
3433 pub threshold_micros: i64,
3434 #[serde(alias = "target_micros")]
3435 pub target_micros: i64,
3436 #[serde(alias = "monthly_max_micros")]
3437 pub monthly_max_micros: i64,
3438}
3439
3440// --- Budgets ------------------------------------------------------------------
3441
3442/// `set_budget`: the monthly budget on usage after included usage: the
3443/// owners' spend limit, its alerts, whether usage pauses at 100%, and an
3444/// optional webhook. Owners only. Returns `Outcome<Limit>`.
3445#[derive(Debug, Serialize, Deserialize)]
3446#[serde(rename_all = "camelCase")]
3447pub struct SetBudgetArgs {
3448 pub actor: User,
3449 pub workspace: String,
3450 /// The amount; None keeps the automatic one.
3451 #[serde(default, alias = "amount_micros")]
3452 pub amount_micros: Option<i64>,
3453 /// Some of 50, 75, 90 and 100.
3454 #[serde(default)]
3455 pub alerts: Vec<u32>,
3456 #[serde(default = "yes", alias = "pause_at_limit")]
3457 pub pause_at_limit: bool,
3458 /// An HTTPS address, or None for no webhook.
3459 #[serde(default)]
3460 pub webhook: Option<String>,
3461 /// Leave the spend limit as it is and change only the alerts, the
3462 /// pause and the webhook.
3463 #[serde(default, alias = "keep_limit")]
3464 pub keep_limit: bool,
3465}
3466
3467// --- Billing details -----------------------------------------------------------
3468
3469/// A postal address, as Stripe keeps it.
3470#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
3471#[serde(rename_all = "camelCase")]
3472pub struct PostalAddress {
3473 #[serde(default)]
3474 pub line1: String,
3475 #[serde(default)]
3476 pub line2: String,
3477 #[serde(default)]
3478 pub city: String,
3479 #[serde(default)]
3480 pub state: String,
3481 #[serde(default)]
3482 pub postal_code: String,
3483 /// Two letters, `US`.
3484 #[serde(default)]
3485 pub country: String,
3486}
3487
3488/// The default way the workspace pays, as far as it is safe to show.
3489#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
3490#[serde(rename_all = "camelCase")]
3491pub struct PaymentMethod {
3492 /// `card`, or another kind Stripe has.
3493 pub kind: String,
3494 #[serde(default)]
3495 pub brand: Option<String>,
3496 #[serde(default)]
3497 pub last4: Option<String>,
3498 #[serde(default)]
3499 pub exp_month: Option<u32>,
3500 #[serde(default)]
3501 pub exp_year: Option<u32>,
3502}
3503
3504/// One of the customer's invoices at Stripe: the plan, activations, AI
3505/// credit and month-end usage.
3506#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
3507#[serde(rename_all = "camelCase")]
3508pub struct StripeInvoice {
3509 pub id: String,
3510 #[serde(default)]
3511 pub number: Option<String>,
3512 /// `paid`, `open`, `void`, `uncollectible` or `draft`.
3513 pub status: String,
3514 pub total_cents: i64,
3515 pub currency: String,
3516 /// RFC 3339.
3517 pub created_at: String,
3518 #[serde(default)]
3519 pub description: Option<String>,
3520 #[serde(default)]
3521 pub hosted_url: Option<String>,
3522 #[serde(default)]
3523 pub pdf_url: Option<String>,
3524}
3525
3526/// What the next invoice will be, from g1t's own ledger.
3527#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
3528#[serde(rename_all = "camelCase")]
3529pub struct UpcomingInvoice {
3530 /// When the month closes, RFC 3339.
3531 pub closes_at: String,
3532 /// The plan and activations, at their monthly price.
3533 pub subscriptions_micros: i64,
3534 /// Usage still owed, after included usage, credit and any discount.
3535 pub usage_micros: i64,
3536 pub total_micros: i64,
3537}
3538
3539/// `billing_details` (`AccountArgs`): who the invoices are for, the default
3540/// payment method, and the invoices, from the Stripe customer. Members see
3541/// it; owners change it. Returns `Outcome<BillingDetails>`.
3542#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
3543#[serde(rename_all = "camelCase")]
3544pub struct BillingDetails {
3545 /// Whether the workspace has a Stripe customer yet.
3546 pub customer: bool,
3547 pub email: Option<String>,
3548 pub name: Option<String>,
3549 pub address: Option<PostalAddress>,
3550 /// `eu_vat`, `us_ein`…, and its value.
3551 pub tax_id_type: Option<String>,
3552 pub tax_id: Option<String>,
3553 /// Printed on invoices.
3554 pub po_number: Option<String>,
3555 /// The invoices' language, such as `en` or `fr`.
3556 pub language: Option<String>,
3557 pub payment_method: Option<PaymentMethod>,
3558 pub invoices: Vec<StripeInvoice>,
3559 pub upcoming: UpcomingInvoice,
3560 /// Stripe could not be read: what is shown is what g1t keeps.
3561 #[serde(default)]
3562 pub unavailable: Option<String>,
3563 /// Whether Stripe Tax can place the customer from the address: tax
3564 /// is worked out from it, and without it nothing is charged.
3565 #[serde(default)]
3566 pub tax_location: bool,
3567 /// Set when g1t did not charge for want of an address (RFC 3339).
3568 #[serde(default)]
3569 pub tax_address_needed_at: Option<String>,
3570 /// Stripe's check of the tax ID: `pending`, `verified`, `unverified` or
3571 /// `unavailable`.
3572 #[serde(default)]
3573 pub tax_id_status: Option<String>,
3574 /// `none`, `exempt` or `reverse`, as staff set it at Stripe; g1t never
3575 /// changes it.
3576 #[serde(default)]
3577 pub tax_exempt: Option<String>,
3578}
3579
3580/// `set_billing_details`: saves the invoice details on the Stripe customer.
3581/// Owners only. Absent fields are left as they are; an empty string clears
3582/// one. Returns `Outcome<BillingDetails>`.
3583#[derive(Debug, Serialize, Deserialize)]
3584#[serde(rename_all = "camelCase")]
3585pub struct SetBillingDetailsArgs {
3586 pub actor: User,
3587 pub workspace: String,
3588 #[serde(default)]
3589 pub email: Option<String>,
3590 #[serde(default)]
3591 pub name: Option<String>,
3592 #[serde(default)]
3593 pub address: Option<PostalAddress>,
3594 #[serde(default, alias = "tax_id_type")]
3595 pub tax_id_type: Option<String>,
3596 #[serde(default, alias = "tax_id")]
3597 pub tax_id: Option<String>,
3598 #[serde(default, alias = "po_number")]
3599 pub po_number: Option<String>,
3600 #[serde(default)]
3601 pub language: Option<String>,
3602}
3603
3604#[cfg(test)]
3605mod tests {
3606 use super::*;
3607
3608 #[test]
3609 fn an_account_carries_no_run_fee() {
3610 let account = Account {
3611 workspace: "acme".into(),
3612 balance_micros: 0,
3613 status: Status { enabled: true, live: false, free: false },
3614 margin_percent: 20,
3615 card: None,
3616 };
3617 let json = serde_json::to_value(account).unwrap();
3618 let mut keys: Vec<&str> = json.as_object().unwrap().keys().map(String::as_str).collect();
3619 keys.sort_unstable();
3620 assert_eq!(keys, ["balanceMicros", "card", "marginPercent", "status", "workspace"]);
3621 }
3622
3623 #[test]
3624 fn a_price_change_says_when_the_markup_moved() {
3625 let change = PriceChange {
3626 meter: "sandbox_second".into(),
3627 old_cost_micros: 21.0,
3628 new_cost_micros: 21.0,
3629 markup_percent: 20,
3630 old_markup_percent: Some(138),
3631 reason: "Sandbox time is now charged at cost plus 20% from the first second".into(),
3632 created_at: "2026-10-05T00:00:00Z".into(),
3633 effective_at: None,
3634 };
3635 assert_eq!(serde_json::to_value(&change).unwrap()["oldMarkupPercent"], 138);
3636 let cost_only = PriceChange { old_markup_percent: None, ..change };
3637 assert!(serde_json::to_value(&cost_only).unwrap().get("oldMarkupPercent").is_none());
3638 }
3639
3640 #[test]
3641 fn features_are_named_as_the_site_sends_them() {
3642 assert_eq!(
3643 serde_json::to_value(Feature::Deployments).unwrap(),
3644 serde_json::json!("deployments")
3645 );
3646 assert_eq!(Feature::parse("deployments"), Some(Feature::Deployments));
3647 assert_eq!(serde_json::to_value(Feature::Plan).unwrap(), serde_json::json!("plan"));
3648 assert_eq!(Feature::parse("plan"), Some(Feature::Plan));
3649 // Older readers named the plan Team.
3650 assert_eq!(Feature::parse("team"), Some(Feature::Plan));
3651 assert_eq!(serde_json::from_value::<Feature>(serde_json::json!("team")).unwrap(), Feature::Plan);
3652 assert_eq!(Feature::ALL, [Feature::Plan, Feature::Security]);
3653 assert_eq!(Feature::parse("security"), Some(Feature::Security));
3654 assert_eq!(serde_json::to_value(Feature::Security).unwrap(), serde_json::json!("security"));
3655 assert!(SubscriptionStatus::Canceling.on());
3656 assert!(!SubscriptionStatus::PastDue.on());
3657 }
3658
3659 #[test]
3660 fn a_reservation_is_asked_for_and_answered_in_camel_case() {
3661 let asked: ReserveArgs = serde_json::from_value(serde_json::json!({
3662 "workspace": "acme",
3663 "repo": { "namespace": "acme", "name": "web" },
3664 "public": true,
3665 "kind": "check",
3666 "estimateMicros": 2_000_000,
3667 }))
3668 .unwrap();
3669 assert_eq!(asked.kind, ComputeKind::Check);
3670 assert!(asked.kind.open_source_pool());
3671 assert!(!ComputeKind::Agent.open_source_pool());
3672 // Rust callers that write snake_case are read too.
3673 let snake: ReserveArgs = serde_json::from_value(serde_json::json!({
3674 "workspace": "acme",
3675 "repo": { "namespace": "acme", "name": "web" },
3676 "public": false,
3677 "kind": "agent",
3678 "estimate_micros": 1,
3679 }))
3680 .unwrap();
3681 assert_eq!(snake.estimate_micros, 1);
3682 let answer = Reservation { id: "rsv_1".into(), paid_by: PaidBy::OnDemand, held_micros: 5, expires_at: String::new() };
3683 assert_eq!(serde_json::to_value(&answer).unwrap()["paidBy"], "on_demand");
3684 assert_eq!(serde_json::to_value(PlanKind::Internal).unwrap(), "internal");
3685 assert!(!PlanKind::Free.on_demand() && PlanKind::Enterprise.on_demand());
3686 }
3687
3688 #[test]
3689 fn a_refusal_carries_its_own_code() {
3690 let refused: crate::Outcome<Reservation> =
3691 crate::Outcome::fail(crate::FailureCode::OssPoolEmpty, "The open-source pool is spent.");
3692 let json = serde_json::to_value(&refused).unwrap();
3693 assert_eq!(json["error"]["code"], "oss_pool_empty");
3694 assert_eq!(crate::FailureCode::NotPaid.http_status(), 402);
3695 assert_eq!(crate::FailureCode::Paused.http_status(), 409);
3696 }
3697
3698 #[test]
3699 fn who_pays_is_read_as_the_runner_sends_it() {
3700 let run: StartRunArgs = serde_json::from_value(serde_json::json!({
3701 "workspace": "acme",
3702 "repo": { "namespace": "acme", "name": "web" },
3703 "number": 7,
3704 "task": "implement",
3705 "model": "Claude Sonnet 5.5",
3706 "billedTo": "workspace",
3707 }))
3708 .unwrap();
3709 assert_eq!(run.billed_to, "workspace");
3710 }
3711}