g1t/crates/contracts/src/billing.rs

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