g1t/crates/contracts/src/billing.rs

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