g1t/crates/contracts/src/billing.rs

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