g1t/crates/contracts/src/billing.rs

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