g1t/services/billing/src/lib.rs

1,275 lines55,463 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1//! The billing service: what g1t's compute costs, charged to the workspace
2//! it ran for at what g1t pays plus 20%.
Agents as a team: lifecycle, merge queue, billing and a new shell3//!
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look4//! One paid plan, "g1t" (see `features`): $20 a month per workspace, never
5//! per person, with $10 of usage included, deployments, and more private
6//! storage. The forge is free for everyone; compute needs the plan or a
7//! card check (see `compute` and `cards`). Before anything that costs money
8//! starts, the service that starts it reserves its estimate here; when it
9//! is done, what it cost goes on the ledger plus the margin, drawn first
10//! from what the plan includes, a trial or g1t's pools (see `credits`).
11//! Every change is a ledger entry, and a balance is always the sum of its
12//! ledger.
Paid features: a workspace turns on Deployments with a monthly plan13//!
Agents as a team: lifecycle, merge queue, billing and a new shell14//! Without a card processor configured the service says so and charges
15//! nothing, so that g1t still runs where billing has not been set up.
16//!
17//! Reached only through service bindings; see `g1t_contracts::billing` for
18//! the methods and their arguments.
19
Billing accounts, terms and enterprises; g1t is no longer free20mod accounts;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays21mod budget;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look22mod cards;
23mod closing;
24mod compute;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily25mod costs;
26mod margin;
27mod pricing;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put28mod credits;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look29mod overages;
30mod requests;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put31mod storage;
Two limits, real invoices, trust that grows by itself, sales signals32mod invoices;
33mod sales;
The statement is a month at a time, a line per kind of charge34mod statement;
Stripe webhooks, enterprise invoices, and sudo for both35mod webhooks;
Paid features: a workspace turns on Deployments with a monthly plan36mod features;
Prices keep themselves current with what g1t pays37mod keeper;
Usage limits: unpaid usage can only go so far38mod limits;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains39mod rename;
sudo: reset a test workspace's billing so it starts again as a new customer; refused on a live Stripe key, for comped workspaces and for an enterprise's40mod reset;
Audit logs are kept by plan: a week on free, 90 days on the plan, and what staff set for an account in sudo41mod retention;
Agents as a team: lifecycle, merge queue, billing and a new shell42mod stripe;
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept43mod stripe_sync;
Mission control shows model usage, yours and the workspace's: tokens, cost, active days, cache share, each day, and the mix44mod tokens;
Agents as a team: lifecycle, merge queue, billing and a new shell45
46use g1t_contracts::billing::*;
47use g1t_contracts::time::rfc3339;
48use g1t_contracts::{FailureCode, Outcome, Role, new_id};
Billing accounts, terms and enterprises; g1t is no longer free49use g1t_contracts::billing::TermsKind;
Agents as a team: lifecycle, merge queue, billing and a new shell50use g1t_kit::{args, now_ms, reply, rpc_method};
51use serde::Deserialize;
52use sha2::{Digest, Sha256};
53use worker::wasm_bindgen::JsValue;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains54use worker::{Context, D1Database, Env, MessageBatch, MessageExt, Request, Response, Result, ScheduleContext, ScheduledEvent, event};
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index55use futures_util::future::{try_join, try_join5};
Agents as a team: lifecycle, merge queue, billing and a new shell56
57use stripe::Stripe;
58
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look59/// Prepaying: $25 at the least; by card up to $10,000 at a time, and by
60/// bank transfer from $1,000 to $100,000.
61const MIN_TOP_UP_CENTS: u32 = 2_500;
62const MAX_TOP_UP_CENTS: u32 = 1_000_000;
63const MIN_BANK_TRANSFER_CENTS: u32 = 100_000;
64const MAX_BANK_TRANSFER_CENTS: u32 = 10_000_000;
Agents as a team: lifecycle, merge queue, billing and a new shell65const LEDGER_PAGE: u32 = 100;
66/// A run's reported cost is believed up to this much. A sandbox cannot
67/// spend more in the time it has, so anything above is a fault.
68const MAX_RUN_COST_USD: f64 = 100.0;
69
70/// What a run is charged: its cost plus the margin, rounded up to a whole
71/// millionth of a dollar.
72pub fn charge_micros(cost_usd: f64, margin_percent: u32) -> i64 {
73 let cost_micros = (cost_usd.clamp(0.0, MAX_RUN_COST_USD) * MICROS_PER_DOLLAR as f64).ceil();
74 (cost_micros * f64::from(100 + margin_percent) / 100.0).ceil() as i64
75}
76
77fn hash(token: &str) -> String {
78 hex::encode(Sha256::digest(token.as_bytes()))
79}
80
81fn optional(value: Option<&str>) -> JsValue {
82 value.map_or(JsValue::NULL, JsValue::from)
83}
84
85#[derive(Deserialize)]
86struct AccountRow {
87 balance_micros: i64,
88 customer_id: Option<String>,
89}
90
91#[derive(Deserialize)]
92struct LedgerRow {
93 id: String,
94 kind: EntryKind,
95 amount_micros: i64,
96 description: String,
97 repo: Option<String>,
98 number: Option<u32>,
99 task: Option<String>,
100 model: Option<String>,
101 created_by: Option<String>,
102 created_at: String,
Integrations: your own model provider, alerts that open issues, tickets agents read103 billed_to: Option<String>,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace104 #[serde(default)]
105 workspace: Option<String>,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put106 #[serde(default)]
107 credit_micros: Option<i64>,
108 #[serde(default)]
109 trial_micros: Option<i64>,
110 #[serde(default)]
111 oss_micros: Option<i64>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look112 #[serde(default)]
113 given_micros: Option<i64>,
Agents as a team: lifecycle, merge queue, billing and a new shell114}
115
116impl From<LedgerRow> for LedgerEntry {
117 fn from(row: LedgerRow) -> Self {
118 LedgerEntry {
119 id: row.id,
120 kind: row.kind,
121 amount_micros: row.amount_micros,
122 description: row.description,
123 repo: row.repo,
124 number: row.number,
125 task: row.task,
126 model: row.model,
Integrations: your own model provider, alerts that open issues, tickets agents read127 billed_to: row.billed_to.unwrap_or_else(|| "g1t".to_owned()),
Agents as a team: lifecycle, merge queue, billing and a new shell128 created_by: row.created_by,
129 created_at: row.created_at,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace130 workspace: row.workspace,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put131 credit_micros: row.credit_micros.unwrap_or(0),
132 trial_micros: row.trial_micros.unwrap_or(0),
133 oss_micros: row.oss_micros.unwrap_or(0),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look134 given_micros: row.given_micros.unwrap_or(0),
Agents as a team: lifecycle, merge queue, billing and a new shell135 }
136 }
137}
138
139#[derive(Deserialize)]
140struct RunRow {
141 workspace: String,
142 repo: String,
143 number: u32,
144 task: String,
145 model: String,
146 token_hash: String,
Integrations: your own model provider, alerts that open issues, tickets agents read147 billed_to: Option<String>,
148}
149
150impl RunRow {
151 fn own_provider(&self) -> bool {
152 self.billed_to.as_deref() == Some("workspace")
153 }
Agents as a team: lifecycle, merge queue, billing and a new shell154}
155
156#[derive(Deserialize)]
157struct CheckoutRow {
158 workspace: String,
159 created_by: String,
160}
161
162/// A row an `UPDATE … RETURNING` touched.
163#[derive(Deserialize)]
164struct Touched {
165 #[allow(dead_code)]
166 id: String,
167}
168
169struct Billing {
170 db: D1Database,
171 /// Absent when no card processor is configured.
172 stripe: Option<Stripe>,
Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard173 /// The destination's signing secret from Stripe (`STRIPE_WEBHOOK_SECRET`);
174 /// without it no event is believed.
175 webhook_secret: Option<String>,
Agents as a team: lifecycle, merge queue, billing and a new shell176 margin_percent: u32,
Free while g1t is being built out; agents can check out their own forks177 /// While g1t is being built out, nothing is charged (`FREE_WHILE_BUILDING`).
178 free: bool,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put179 /// Whether new workspaces get trial credit (`TRIAL_WORKSPACE_MICROS`
180 /// and `TRIAL_MONTHLY_POOL_MICROS` both above zero).
181 trials_on: bool,
182 /// The plans' and pools' numbers; see `credits`.
183 plans: credits::Config,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look184 /// The repos service: which repositories are public, what private ones
185 /// hold, and their git operations. Absent where it is not bound.
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put186 repos: Option<worker::Fetcher>,
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member187 /// The packages service: what each workspace's packages hold.
188 packages: Option<worker::Fetcher>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look189 /// The identity service, which emails owners. Absent where it is not
190 /// bound.
191 identity: Option<worker::Fetcher>,
Usage limits: unpaid usage can only go so far192 /// How far unpaid usage may go; see `limits`.
193 ceilings: limits::Ceilings,
Billing accounts, terms and enterprises; g1t is no longer free194 /// `PREPAID_ONLY`: the old rule, that agents need credit first.
195 prepaid_only: bool,
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays196 /// The caps on what g1t pays for itself; see `budget`.
197 caps: budget::Caps,
198 /// The worker's bindings, for emailing staff (`EMAIL`).
199 env: Env,
A free allowance on g1t's models, so anyone can try its agents200}
201
Agents as a team: lifecycle, merge queue, billing and a new shell202impl Billing {
203 fn status(&self) -> Status {
204 Status {
205 enabled: self.stripe.is_some(),
206 live: self.stripe.as_ref().is_some_and(Stripe::live),
Free while g1t is being built out; agents can check out their own forks207 free: self.free,
Agents as a team: lifecycle, merge queue, billing and a new shell208 }
209 }
210
211 async fn row(&self, workspace: &str) -> Result<Option<AccountRow>> {
212 self.db
213 .prepare("SELECT balance_micros, customer_id FROM accounts WHERE workspace = ?")
214 .bind(&[workspace.into()])?
215 .first::<AccountRow>(None)
216 .await
217 }
218
219 async fn standing(&self, workspace: &str) -> Result<Account> {
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept220 // The card as last synced (stripe_sync.rs), not asked of Stripe.
221 let (row, card) = try_join(self.row(workspace), self.saved_card(workspace)).await?;
Agents as a team: lifecycle, merge queue, billing and a new shell222 Ok(Account {
223 workspace: workspace.to_owned(),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace224 balance_micros: row.map_or(0, |row| row.balance_micros),
Agents as a team: lifecycle, merge queue, billing and a new shell225 status: self.status(),
226 margin_percent: self.margin_percent,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace227 card,
Agents as a team: lifecycle, merge queue, billing and a new shell228 })
229 }
230
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace231 /// The workspace's customer at Stripe, made the first time one is needed.
232 pub(crate) async fn customer_for(&self, workspace: &str) -> Result<String> {
233 let Some(stripe) = &self.stripe else {
234 return Err(worker::Error::RustError("payments are not set up".into()));
235 };
236 if let Some(customer) = self.row(workspace).await?.and_then(|row| row.customer_id) {
237 return Ok(customer);
238 }
239 let customer = stripe.create_customer(workspace).await?;
240 self.db
241 .prepare(
242 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at) VALUES (?1, 0, ?2, ?3)
243 ON CONFLICT (workspace) DO UPDATE SET customer_id = ?2",
244 )
245 .bind(&[workspace.into(), customer.as_str().into(), rfc3339(now_ms()).into()])?
246 .run()
247 .await?;
248 Ok(customer)
249 }
250
251 /// Stripe's hosted billing page for the workspace. Owners only.
252 async fn billing_portal(&self, a: BillingPortalArgs) -> Result<Outcome<Checkout>> {
253 let workspace = a.workspace.to_lowercase();
254 if a.actor.role_in(&workspace) != Some(Role::Owner) {
255 return Ok(Outcome::fail(FailureCode::Forbidden, "Only an owner can manage the workspace's billing."));
256 }
257 let Some(stripe) = &self.stripe else {
258 return Ok(Outcome::fail(FailureCode::Conflict, "Payments are not set up on this g1t."));
259 };
260 let customer = match self.customer_for(&workspace).await {
261 Ok(customer) => customer,
262 Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe could not be reached: {error}"))),
263 };
264 match stripe.portal_session(&customer, &a.return_url).await {
265 Ok(url) => Ok(Outcome::Ok(Checkout { url })),
266 Err(error) if stripe::is_missing(&error) => {
267 // The customer was removed at Stripe: a new one next time.
268 self.forget_customer(&workspace).await?;
269 Ok(Outcome::fail(FailureCode::Conflict, "Stripe no longer had this workspace's customer. Try again."))
270 }
271 Err(error) => Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe's billing page could not be opened: {error}"))),
272 }
273 }
274
Agents as a team: lifecycle, merge queue, billing and a new shell275 /// Adds a ledger entry and moves the balance by the same amount, as
276 /// one write.
277 #[allow(clippy::too_many_arguments)]
278 async fn enter(
279 &self,
280 workspace: &str,
281 kind: EntryKind,
282 amount_micros: i64,
283 description: &str,
284 reference: &str,
285 run: Option<&RunRow>,
286 cost_micros: Option<i64>,
287 created_by: Option<&str>,
288 customer: Option<&str>,
289 ) -> Result<()> {
290 let now = now_ms();
291 let timestamp = rfc3339(now);
292 let kind = match kind {
293 EntryKind::TopUp => "top_up",
294 EntryKind::Usage => "usage",
295 };
296 self.db
297 .batch(vec![
298 self.db
299 .prepare(
300 "INSERT INTO ledger
301 (id, workspace, kind, amount_micros, description, repo, number, task,
Integrations: your own model provider, alerts that open issues, tickets agents read302 model, cost_micros, reference, created_by, created_at, billed_to)
303 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
Agents as a team: lifecycle, merge queue, billing and a new shell304 )
305 .bind(&[
306 new_id("led", now).into(),
307 workspace.into(),
308 kind.into(),
309 // D1 takes numbers as doubles, which hold every
310 // amount this service will see exactly.
311 (amount_micros as f64).into(),
312 description.into(),
313 optional(run.map(|run| run.repo.as_str())),
314 run.map_or(JsValue::NULL, |run| run.number.into()),
315 optional(run.map(|run| run.task.as_str())),
316 optional(run.map(|run| run.model.as_str())),
317 cost_micros.map_or(JsValue::NULL, |cost| (cost as f64).into()),
318 reference.into(),
319 optional(created_by),
320 timestamp.as_str().into(),
Integrations: your own model provider, alerts that open issues, tickets agents read321 run.map_or("g1t", |run| if run.own_provider() { "workspace" } else { "g1t" }).into(),
Agents as a team: lifecycle, merge queue, billing and a new shell322 ])?,
323 self.db
324 .prepare(
325 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at)
326 VALUES (?1, ?2, ?3, ?4)
327 ON CONFLICT (workspace) DO UPDATE SET
328 balance_micros = balance_micros + ?2,
329 customer_id = COALESCE(?3, customer_id)",
330 )
331 .bind(&[
332 workspace.into(),
333 (amount_micros as f64).into(),
334 optional(customer),
335 timestamp.as_str().into(),
336 ])?,
337 ])
338 .await?;
Billing accounts, terms and enterprises; g1t is no longer free339 // Money in clears a card declined at the limit.
340 if kind == "top_up" {
341 self.db
342 .prepare("UPDATE limits SET autopay_failed_at = NULL, autopay_error = NULL WHERE workspace = ?")
343 .bind(&[workspace.into()])?
344 .run()
345 .await?;
346 }
Agents as a team: lifecycle, merge queue, billing and a new shell347 Ok(())
348 }
349
350 async fn account(&self, a: AccountArgs) -> Result<Outcome<Account>> {
351 let workspace = a.workspace.to_lowercase();
352 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
353 return Ok(members_only());
354 }
355 Ok(Outcome::Ok(self.standing(&workspace).await?))
356 }
357
358 async fn ledger(&self, a: AccountArgs) -> Result<Outcome<Vec<LedgerEntry>>> {
359 let workspace = a.workspace.to_lowercase();
360 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
361 return Ok(members_only());
362 }
363 let rows = self
364 .db
365 .prepare("SELECT * FROM ledger WHERE workspace = ? ORDER BY id DESC LIMIT ?")
366 .bind(&[workspace.into(), LEDGER_PAGE.into()])?
367 .all()
368 .await?
369 .results::<LedgerRow>()?;
370 Ok(Outcome::Ok(
371 rows.into_iter().map(LedgerEntry::from).collect(),
372 ))
373 }
374
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request375 async fn usage(&self, a: UsageArgs) -> Result<Outcome<Usage>> {
376 let workspace = a.workspace.to_lowercase();
377 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
378 return Ok(members_only());
379 }
380 #[derive(serde::Deserialize)]
381 struct SliceRow {
382 key: Option<String>,
383 micros: Option<i64>,
384 runs: Option<u32>,
385 }
A comped workspace's usage chart and breakdowns show what runs used at cost, as the free tier's do386 // While nothing is charged (g1t is free, or the workspace is
387 // comped), what was used is what there is to show.
388 #[derive(serde::Deserialize)]
389 struct Comped {
390 n: i64,
391 }
392 let comped = self
393 .db
394 .prepare("SELECT COUNT(*) AS n FROM billing_accounts WHERE kind = 'workspace' AND terms_kind = 'comped' AND substr(id, 4) = ?1")
395 .bind(&[workspace.as_str().into()])?
396 .first::<Comped>(None)
397 .await?
398 .is_some_and(|row| row.n > 0);
399 let measure = if self.free || comped { "COALESCE(cost_micros, 0)" } else { "-amount_micros" };
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request400 let slices = |key: &str, limit: u32| {
401 format!(
Usage while free is shown at cost; agents get rustfmt and clippy402 "SELECT {key} AS key, SUM({measure}) AS micros, COUNT(*) AS runs FROM ledger
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request403 WHERE workspace = ?1 AND kind = 'usage' AND created_at >= ?2
404 GROUP BY 1 ORDER BY micros DESC LIMIT {limit}"
405 )
406 };
407 let query = |sql: String| {
408 let db = &self.db;
409 let workspace = workspace.clone();
410 let since = a.since.clone();
411 async move {
412 let rows = db
413 .prepare(sql)
414 .bind(&[workspace.into(), since.into()])?
415 .all()
416 .await?
417 .results::<SliceRow>()?;
418 Ok::<Vec<UsageSlice>, worker::Error>(
419 rows.into_iter()
420 .map(|row| UsageSlice {
421 key: row.key.unwrap_or_else(|| "other".to_owned()),
422 micros: row.micros.unwrap_or_default(),
423 runs: row.runs.unwrap_or_default(),
424 })
425 .collect(),
426 )
427 }
428 };
429 #[derive(serde::Deserialize)]
430 struct Totals {
431 spent: Option<i64>,
Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged432 g1t_cost: Option<i64>,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request433 cost: Option<i64>,
Integrations: your own model provider, alerts that open issues, tickets agents read434 provider: Option<i64>,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request435 runs: Option<u32>,
436 added: Option<i64>,
437 }
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index438 let totals = async {
439 self.db
440 .prepare(
441 "SELECT
442 -SUM(CASE WHEN kind = 'usage' THEN amount_micros END) AS spent,
Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged443 SUM(CASE WHEN kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' THEN cost_micros END) AS g1t_cost,
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index444 SUM(CASE WHEN kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' THEN cost_micros END) AS cost,
445 SUM(CASE WHEN kind = 'usage' AND billed_to = 'workspace' THEN cost_micros END) AS provider,
446 SUM(CASE WHEN kind = 'usage' THEN 1 ELSE 0 END) AS runs,
447 SUM(CASE WHEN kind = 'top_up' THEN amount_micros END) AS added
448 FROM ledger WHERE workspace = ?1 AND created_at >= ?2",
449 )
450 .bind(&[workspace.as_str().into(), a.since.as_str().into()])?
451 .first::<Totals>(None)
452 .await
453 };
454 // The totals and the five slices read the same rows independently,
455 // so they go to D1 at once: one round trip of waiting, not six.
456 let (totals, (by_day, by_task, by_repo, by_pull, by_model)) = try_join(
457 totals,
458 try_join5(
459 query(slices("substr(created_at, 1, 10) || '/' || COALESCE(task, 'other')", 400)),
460 query(slices("task", 20)),
461 query(slices("repo", 20)),
462 query(slices("repo || '#' || number", 10)),
463 query(slices("model", 10)),
464 ),
465 )
466 .await?;
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request467 let totals = totals.unwrap_or(Totals {
468 spent: None,
Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged469 g1t_cost: None,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request470 cost: None,
Integrations: your own model provider, alerts that open issues, tickets agents read471 provider: None,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request472 runs: None,
473 added: None,
474 });
475 Ok(Outcome::Ok(Usage {
476 spent_micros: totals.spent.unwrap_or_default(),
Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged477 // At price, what g1t's usage came to, less what was charged: the
478 // part the included usage, the trial, a pool, or a free period paid.
479 covered_micros: (crate::credits::with_margin(totals.g1t_cost.unwrap_or_default(), self.margin_percent)
480 - totals.spent.unwrap_or_default())
481 .max(0),
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request482 cost_micros: totals.cost.unwrap_or_default(),
Integrations: your own model provider, alerts that open issues, tickets agents read483 provider_micros: totals.provider.unwrap_or_default(),
Usage while free is shown at cost; agents get rustfmt and clippy484 used_micros: totals.cost.unwrap_or_default() + totals.provider.unwrap_or_default(),
485 free: self.free,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request486 runs: totals.runs.unwrap_or_default(),
487 added_micros: totals.added.unwrap_or_default(),
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index488 by_day,
489 by_task,
490 by_repo,
491 by_pull,
492 by_model,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request493 since: a.since,
494 }))
495 }
496
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look497 /// `checkout`: prepays usage, by card or (from $1,000) bank transfer.
Agents as a team: lifecycle, merge queue, billing and a new shell498 async fn checkout(&self, a: CheckoutArgs) -> Result<Outcome<Checkout>> {
499 let workspace = a.workspace.to_lowercase();
500 if a.actor.role_in(&workspace) != Some(Role::Owner) {
501 return Ok(Outcome::fail(
502 FailureCode::Forbidden,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look503 "Only an owner can prepay for a workspace.",
Agents as a team: lifecycle, merge queue, billing and a new shell504 ));
505 }
506 let Some(stripe) = &self.stripe else {
507 return Ok(Outcome::fail(
508 FailureCode::Conflict,
509 "Payments are not set up on this g1t yet.",
510 ));
511 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look512 let bank_transfer = a.method.as_deref() == Some("bank_transfer");
513 if let Err(why) = prepay_amount(a.amount_cents, bank_transfer) {
514 return Ok(Outcome::fail(FailureCode::Invalid, why));
Agents as a team: lifecycle, merge queue, billing and a new shell515 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look516 // A bank transfer needs a customer for its account details.
517 let customer = if bank_transfer {
518 match self.customer_for(&workspace).await {
519 Ok(customer) => Some(customer),
520 Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe could not be reached: {error}"))),
521 }
522 } else {
523 self.row(&workspace).await?.and_then(|row| row.customer_id)
524 };
Project dependencies: addresses, preview stacks, Affects, and agents who know525 let session = match stripe
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look526 .start_checkout(&workspace, a.amount_cents, customer.as_deref(), &a.return_url, bank_transfer)
Project dependencies: addresses, preview stacks, Affects, and agents who know527 .await
528 {
529 Ok(session) => session,
530 // A customer saved under another Stripe account: start afresh.
531 Err(error) if customer.is_some() && stripe::is_missing(&error) => {
532 self.forget_customer(&workspace).await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look533 let customer = if bank_transfer { Some(self.customer_for(&workspace).await?) } else { None };
534 stripe.start_checkout(&workspace, a.amount_cents, customer.as_deref(), &a.return_url, bank_transfer).await?
Project dependencies: addresses, preview stacks, Affects, and agents who know535 }
536 Err(error) => return Err(error),
537 };
Agents as a team: lifecycle, merge queue, billing and a new shell538 let Some(url) = session.url else {
539 return Err(worker::Error::RustError(
540 "the card processor returned no payment page".into(),
541 ));
542 };
543 self.db
544 .prepare(
545 "INSERT INTO checkouts (id, workspace, amount_cents, created_by, created_at)
546 VALUES (?, ?, ?, ?, ?)",
547 )
548 .bind(&[
549 session.id.into(),
550 workspace.into(),
551 a.amount_cents.into(),
552 a.actor.username.into(),
553 rfc3339(now_ms()).into(),
554 ])?
555 .run()
556 .await?;
557 Ok(Outcome::Ok(Checkout { url }))
558 }
559
560 /// Credits a payment if the processor says it was made and it has not
561 /// been credited before. The amount credited is what the processor
562 /// says was paid, not what anyone here remembers asking for.
563 async fn confirm(&self, a: ConfirmArgs) -> Result<Outcome<Account>> {
564 let workspace = a.workspace.to_lowercase();
565 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
566 return Ok(members_only());
567 }
568 let (Some(stripe), Some(checkout)) = (
569 &self.stripe,
570 self.db
571 .prepare(
572 "SELECT workspace, created_by FROM checkouts
573 WHERE id = ? AND workspace = ? AND status = 'open'",
574 )
575 .bind(&[a.session.as_str().into(), workspace.as_str().into()])?
576 .first::<CheckoutRow>(None)
577 .await?,
578 ) else {
579 // Unknown, someone else's, or already credited: nothing to do.
580 return Ok(Outcome::Ok(self.standing(&workspace).await?));
581 };
582 let session = stripe.session(&a.session).await?;
583 let paid = session
584 .amount_total
585 .filter(|_| session.payment_status == "paid");
586 if let Some(cents) = paid {
587 // Only whoever flips it from open to paid enters the credit.
588 let claimed = self
589 .db
590 .prepare(
591 "UPDATE checkouts SET status = 'paid' WHERE id = ? AND status = 'open'
592 RETURNING id",
593 )
594 .bind(&[a.session.as_str().into()])?
595 .first::<Touched>(None)
596 .await?;
597 if claimed.is_some() {
598 self.enter(
599 &checkout.workspace,
600 EntryKind::TopUp,
601 i64::from(cents) * MICROS_PER_DOLLAR / 100,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look602 "Paid in advance",
Agents as a team: lifecycle, merge queue, billing and a new shell603 &session.id,
604 None,
605 None,
606 Some(&checkout.created_by),
607 session.customer.as_deref(),
608 )
609 .await?;
610 }
611 }
612 Ok(Outcome::Ok(self.standing(&workspace).await?))
613 }
614
Project dependencies: addresses, preview stacks, Affects, and agents who know615 /// Drops a saved customer the card processor no longer knows.
616 pub(crate) async fn forget_customer(&self, workspace: &str) -> Result<()> {
617 self.db
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept618 .prepare(
619 "UPDATE accounts SET customer_id = NULL, card_brand = NULL, card_last4 = NULL, card_exp_month = NULL,
620 card_exp_year = NULL, card_synced_at = NULL WHERE workspace = ?",
621 )
Project dependencies: addresses, preview stacks, Affects, and agents who know622 .bind(&[workspace.into()])?
623 .run()
624 .await?;
625 Ok(())
626 }
627
Agents as a team: lifecycle, merge queue, billing and a new shell628 /// A refusal if the workspace has no credit to start an agent with.
629 async fn out_of_credit<T>(&self, workspace: &str) -> Result<Option<Outcome<T>>> {
Billing accounts, terms and enterprises; g1t is no longer free630 // Billing is postpaid: usage limits decide whether work starts
631 // (see `limits`), and credit is a prepayment that lowers what is
632 // owed. A balance no longer has to be positive to start.
633 if self.free || !self.prepaid_only {
Free while g1t is being built out; agents can check out their own forks634 return Ok(None);
635 }
Agents as a team: lifecycle, merge queue, billing and a new shell636 let balance = self
637 .row(workspace)
638 .await?
639 .map_or(0, |row| row.balance_micros);
640 Ok((balance <= 0).then(|| {
641 Outcome::fail(
642 FailureCode::PaymentRequired,
643 format!(
644 "The {workspace} workspace has no agent credit. An owner can add some under Billing on the workspace's page."
645 ),
646 )
647 }))
Billing accounts, terms and enterprises; g1t is no longer free648 }
649
Agents as a team: lifecycle, merge queue, billing and a new shell650 async fn can_start(&self, a: CanStartArgs) -> Result<Outcome<bool>> {
651 if self.stripe.is_none() {
652 return Ok(Outcome::Ok(true));
653 }
Usage limits: unpaid usage can only go so far654 if let Some(stopped) = self.stopped(&a.workspace).await? {
655 return Ok(stopped);
656 }
Agents as a team: lifecycle, merge queue, billing and a new shell657 Ok(self
658 .out_of_credit(&a.workspace.to_lowercase())
659 .await?
660 .unwrap_or(Outcome::Ok(true)))
661 }
662
663 async fn start_run(&self, a: StartRunArgs) -> Result<Outcome<Option<RunTicket>>> {
664 if self.stripe.is_none() {
665 return Ok(Outcome::Ok(None));
666 }
667 let workspace = a.workspace.to_lowercase();
Usage limits: unpaid usage can only go so far668 if let Some(stopped) = self.stopped(&workspace).await? {
669 return Ok(stopped);
670 }
Agents as a team: lifecycle, merge queue, billing and a new shell671 if let Some(refused) = self.out_of_credit(&workspace).await? {
672 return Ok(refused);
673 }
674 let now = now_ms();
675 let run_id = new_id("run", now);
676 let mut bytes = [0u8; 32];
677 getrandom::getrandom(&mut bytes).expect("no source of randomness");
678 let token = hex::encode(bytes);
679 self.db
680 .prepare(
Auto model routing: the cheapest tier that can do each piece of work, a retry goes up a tier, and each run records its tier681 "INSERT INTO runs (id, workspace, repo, number, task, model, token_hash, created_at, billed_to, session_id, tier)
682 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
Agents as a team: lifecycle, merge queue, billing and a new shell683 )
684 .bind(&[
685 run_id.as_str().into(),
686 workspace.into(),
687 format!("{}/{}", a.repo.namespace, a.repo.name).into(),
688 a.number.into(),
689 a.task.into(),
690 a.model.into(),
691 hash(&token).into(),
692 rfc3339(now).into(),
Integrations: your own model provider, alerts that open issues, tickets agents read693 if a.billed_to == "workspace" { "workspace" } else { "g1t" }.into(),
Prices keep themselves current with what g1t pays694 optional(a.session.as_deref().filter(|_| a.billed_to != "workspace")),
Auto model routing: the cheapest tier that can do each piece of work, a retry goes up a tier, and each run records its tier695 optional(
696 a.tier
697 .as_deref()
698 .filter(|tier| a.billed_to != "workspace" && matches!(*tier, "small" | "large")),
699 ),
Agents as a team: lifecycle, merge queue, billing and a new shell700 ])?
701 .run()
702 .await?;
703 Ok(Outcome::Ok(Some(RunTicket { run_id, token })))
704 }
705
706 async fn finish_run(&self, a: FinishRunArgs) -> Result<Outcome<bool>> {
707 let run = self
708 .db
709 .prepare(
Integrations: your own model provider, alerts that open issues, tickets agents read710 "SELECT workspace, repo, number, task, model, token_hash, billed_to FROM runs
Agents as a team: lifecycle, merge queue, billing and a new shell711 WHERE id = ? AND finished_at IS NULL",
712 )
713 .bind(&[a.run_id.as_str().into()])?
714 .first::<RunRow>(None)
715 .await?;
716 let Some(run) = run.filter(|run| run.token_hash == hash(&a.token)) else {
717 return Ok(Outcome::fail(FailureCode::NotFound, "Run not found."));
718 };
719 if !a.cost_usd.is_finite() || a.cost_usd < 0.0 {
720 return Ok(Outcome::fail(FailureCode::Invalid, "That is not a cost."));
721 }
722 // Only whoever closes the run charges for it.
723 let claimed = self
724 .db
725 .prepare(
726 "UPDATE runs SET finished_at = ? WHERE id = ? AND finished_at IS NULL RETURNING id",
727 )
728 .bind(&[rfc3339(now_ms()).into(), a.run_id.as_str().into()])?
729 .first::<Touched>(None)
730 .await?;
731 if claimed.is_none() {
732 return Ok(Outcome::Ok(false));
733 }
Prices are what g1t pays plus 20%, from the first second734 // On the workspace's own provider, the model was paid for there,
735 // and the run's sandbox time is recorded on its own: nothing more
736 // to charge.
737 if run.own_provider() {
738 return Ok(Outcome::Ok(true));
739 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look740 // Its cost plus the margin, on the account's terms; then the plan's
741 // included usage and the trial credit pay what they can, and g1t
742 // covers a free workspace's overrun (see `credits`). Agents are
743 // never the open-source pool's.
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put744 let base = charge_micros(a.cost_usd, self.margin_percent);
Billing accounts, terms and enterprises; g1t is no longer free745 let (charge, terms_note) = self.charged(&run.workspace, base).await?;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put746 let month = credits::month_of(&rfc3339(now_ms()));
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look747 let eligible = credits::eligible_for(Some(ComputeKind::Agent), None);
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put748 let drawn = self.draw(&run.workspace, charge, &month, &eligible).await?;
Integrations: your own model provider, alerts that open issues, tickets agents read749 let mut description = match run.task.as_str() {
Agents as a team: lifecycle, merge queue, billing and a new shell750 "plan" => format!("Planning for {}", run.repo),
751 "review" => format!("Review of {}#{}", run.repo, run.number),
752 "update" => format!("Catching up {}#{}", run.repo, run.number),
753 _ => format!("Work on {}#{}", run.repo, run.number),
754 };
Billing accounts, terms and enterprises; g1t is no longer free755 description.push_str(&terms_note);
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put756 description.push_str(&drawn.note());
Agents as a team: lifecycle, merge queue, billing and a new shell757 self.enter(
758 &run.workspace,
759 EntryKind::Usage,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put760 -(charge - drawn.total()),
Agents as a team: lifecycle, merge queue, billing and a new shell761 &description,
762 &a.run_id,
763 Some(&run),
764 Some(charge_micros(a.cost_usd, 0)),
765 None,
766 None,
767 )
768 .await?;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put769 self.record_drawn(&a.run_id, &drawn).await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays770 self.count_spend(&run.workspace, charge_micros(a.cost_usd, 0), charge - drawn.total(), &drawn).await;
Agents as a team: lifecycle, merge queue, billing and a new shell771 Ok(Outcome::Ok(true))
772 }
773}
774
Every sandbox is metered by the second775impl Billing {
Prices are what g1t pays plus 20%, from the first second776 /// Records how long a sandbox ran, with its cost and its charge: every
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look777 /// second, from the first, at the price book's price; on its own CPU
778 /// when it reports it. Settles its reservation, if it names one.
Every sandbox is metered by the second779 async fn record_sandbox(&self, a: RecordSandboxArgs) -> Result<Outcome<bool>> {
Fast pages, required checks on the branch, self-hosted runners, honest incidents780 // Self-hosted time is recorded wherever g1t runs, for its minutes;
781 // anything else only where there is a bill to put it on.
782 if (self.stripe.is_none() && !a.self_hosted) || a.seconds == 0 {
Every sandbox is metered by the second783 return Ok(Outcome::Ok(false));
784 }
785 let workspace = a.workspace.to_lowercase();
786 let seen = self
787 .db
788 .prepare("SELECT id FROM ledger WHERE reference = ?")
789 .bind(&[a.reference.as_str().into()])?
790 .first::<Touched>(None)
791 .await?;
792 if seen.is_some() {
793 return Ok(Outcome::Ok(false));
794 }
795 let now = now_ms();
796 let timestamp = rfc3339(now);
797 let seconds = i64::from(a.seconds);
Fast pages, required checks on the branch, self-hosted runners, honest incidents798 // On the workspace's own machine: its minutes go on usage, at $0,
799 // and whatever was reserved for it is given back.
800 if a.self_hosted {
801 let description = format!("{}: {} of self-hosted runner time, $0", a.description, duration(seconds));
802 self.db
803 .prepare(
804 "INSERT INTO ledger
805 (id, workspace, kind, amount_micros, description, repo, task,
806 cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros)
807 VALUES (?, ?, 'usage', 0, ?, ?, 'self_hosted', 0, ?, ?, 'workspace', 0, 0, 0, 0)",
808 )
809 .bind(&[
810 new_id("led", now).into(),
811 workspace.as_str().into(),
812 description.as_str().into(),
813 optional(a.repo.as_deref()),
814 a.reference.as_str().into(),
815 timestamp.as_str().into(),
816 ])?
817 .run()
818 .await?;
819 if let Some(reservation) = &a.reservation_id {
820 self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: 0 }).await?;
821 }
822 return Ok(Outcome::Ok(true));
823 }
Prices are what g1t pays plus 20%, from the first second824 // From the price book, which follows what Cloudflare bills g1t. A
825 // sandbox is the same container as a build, so without a row it is
826 // a build second's cost plus the margin.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look827 let (cost_per_second, _) = self.price("sandbox_second").await?.unwrap_or_else(|| {
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas828 let cost = deployment_costs::MICROS_PER_BUILD_SECOND as f64;
Prices are what g1t pays plus 20%, from the first second829 (cost, Price::price_for(cost, self.margin_percent))
830 });
Fast pages, required checks on the branch, self-hosted runners, honest incidents831 // A larger machine (`runs-on: g1t-4core`): its memory and disk
832 // cost more each second, and without its own CPU it is priced at
833 // its vCPUs as busy as the standard machine's.
834 let instance = a.instance.as_deref().and_then(g1t_contracts::actions::instance_named);
835 let base_scale = instance.map_or(1.0, |i| keeper::base_scale(i.memory_gib, i.disk_gb));
836 let price_scale = instance.map_or(1.0, |i| i.price_scale);
837 let vcpus = instance.map_or(4.0, |i| i.vcpu.max(4.0));
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look838 // Its own CPU when the sandbox reports it; otherwise the average.
839 let parts = match a.cpu_seconds.filter(|cpu| cpu.is_finite() && *cpu >= 0.0) {
840 Some(cpu) => match (self.price("sandbox_base_second").await?, self.price("sandbox_cpu_second").await?) {
Fast pages, required checks on the branch, self-hosted runners, honest incidents841 (Some((base, _)), Some((vcpu, _))) => {
842 Some((keeper::run_cost(seconds, cpu.min(seconds as f64 * vcpus), base * base_scale, vcpu), cpu))
843 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look844 _ => None,
845 },
846 None => None,
847 };
Fast pages, required checks on the branch, self-hosted runners, honest incidents848 let cost = parts.map_or(seconds as f64 * cost_per_second * price_scale, |(cost, _)| cost).ceil() as i64;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look849 let (charge, terms_note) = self.charged(&workspace, credits::with_margin(cost, self.margin_percent)).await?;
850 let eligible = credits::eligible_for(a.kind, a.repo.as_deref());
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put851 let drawn = self.draw(&workspace, charge, &credits::month_of(&timestamp), &eligible).await?;
852 let charge = charge - drawn.total();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look853 let cpu_note = parts.map_or(String::new(), |(_, cpu)| format!(", {cpu:.0} vCPU-seconds"));
854 let description = format!("{}: {} of sandbox time{cpu_note}{terms_note}{}", a.description, duration(seconds), drawn.note());
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily855 // The price versions it was charged at (pricing.rs).
856 let meters: &[&str] = if parts.is_some() { &["sandbox_base_second", "sandbox_cpu_second"] } else { &["sandbox_second"] };
857 let mut versions = Vec::new();
858 for meter in meters {
859 versions.extend(self.version_now(meter).await?);
860 }
861 let price_version = versions.join(",");
Every sandbox is metered by the second862 self.db
863 .batch(vec![
864 self.db
865 .prepare(
866 "INSERT INTO ledger
867 (id, workspace, kind, amount_micros, description, repo, task,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily868 cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros, price_version)
869 VALUES (?, ?, 'usage', ?, ?, ?, 'sandbox', ?, ?, ?, 'g1t', ?, ?, ?, ?, ?)",
Every sandbox is metered by the second870 )
871 .bind(&[
872 new_id("led", now).into(),
873 workspace.as_str().into(),
874 (-(charge as f64)).into(),
875 description.as_str().into(),
876 optional(a.repo.as_deref()),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look877 (cost as f64).into(),
Every sandbox is metered by the second878 a.reference.as_str().into(),
879 timestamp.as_str().into(),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put880 (drawn.credit as f64).into(),
881 (drawn.trial as f64).into(),
882 (drawn.oss as f64).into(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look883 (drawn.given as f64).into(),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily884 optional(Some(price_version.as_str()).filter(|v| !v.is_empty())),
Every sandbox is metered by the second885 ])?,
886 self.db
887 .prepare(
888 "INSERT INTO accounts (workspace, balance_micros, created_at)
889 VALUES (?1, ?2, ?3)
890 ON CONFLICT (workspace) DO UPDATE SET balance_micros = balance_micros + ?2",
891 )
892 .bind(&[
893 workspace.as_str().into(),
894 (-(charge as f64)).into(),
895 timestamp.as_str().into(),
896 ])?,
897 ])
898 .await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays899 self.count_spend(&workspace, cost, charge, &drawn).await;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look900 if let Some(reservation) = &a.reservation_id {
901 self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: cost }).await?;
902 }
Every sandbox is metered by the second903 Ok(Outcome::Ok(true))
904 }
905}
906
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look907/// Whether an amount may be prepaid: $25 at the least by card, and from
908/// $1,000 by bank transfer.
909pub(crate) fn prepay_amount(cents: u32, bank_transfer: bool) -> std::result::Result<(), String> {
910 let (min, max) = if bank_transfer { (MIN_BANK_TRANSFER_CENTS, MAX_BANK_TRANSFER_CENTS) } else { (MIN_TOP_UP_CENTS, MAX_TOP_UP_CENTS) };
911 if (min..=max).contains(&cents) {
912 return Ok(());
913 }
914 Err(if bank_transfer {
915 format!("Prepay between ${} and ${} by bank transfer.", min / 100, group(max / 100))
916 } else {
917 format!("Prepay between ${} and ${} by card; from $1,000, a bank transfer works too.", min / 100, group(max / 100))
918 })
919}
920
921/// `10,000` for 10000.
922fn group(n: u32) -> String {
923 let digits = n.to_string();
924 let mut out = String::new();
925 for (i, c) in digits.chars().enumerate() {
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept926 if i > 0 && (digits.len() - i).is_multiple_of(3) {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look927 out.push(',');
928 }
929 out.push(c);
930 }
931 out
932}
933
934#[cfg(test)]
Prices are what g1t pays plus 20%, from the first second935/// What `seconds` of sandbox time are charged at `price_per_second`, in
936/// millionths of a dollar: every second, rounded up to the next millionth.
937fn sandbox_charge(seconds: i64, price_per_second: f64) -> i64 {
938 (seconds as f64 * price_per_second).ceil() as i64
Every sandbox is metered by the second939}
940
941/// `1h 2m`, `3m 12s` or `40s`.
942fn duration(seconds: i64) -> String {
943 let (h, m, s) = (seconds / 3600, seconds % 3600 / 60, seconds % 60);
944 if h > 0 {
945 format!("{h}h {m}m")
946 } else if m > 0 {
947 format!("{m}m {s}s")
948 } else {
949 format!("{s}s")
950 }
951}
952
Billing accounts, terms and enterprises; g1t is no longer free953impl Billing {
954 /// What a workspace is charged for something that would be `base`:
955 /// nothing while g1t is free, or as its account's terms say. With a
956 /// note for the statement when it differs.
957 pub(crate) async fn charged(&self, workspace: &str, base: i64) -> Result<(i64, String)> {
958 if self.free {
959 return Ok((0, " (free while g1t is being built out)".to_owned()));
960 }
961 let terms = self.terms_of(workspace).await?;
962 let charge = terms.apply(base);
963 let note = match terms.kind {
964 TermsKind::Comped => " (comped)".to_owned(),
965 TermsKind::Custom if terms.discount_percent > 0 && base > 0 => format!(" ({}% off)", terms.discount_percent),
966 _ => String::new(),
967 };
968 Ok((charge, note))
969 }
970}
971
Agents as a team: lifecycle, merge queue, billing and a new shell972fn members_only<T>() -> Outcome<T> {
973 Outcome::fail(
974 FailureCode::Forbidden,
975 "Only members can see a workspace's billing.",
976 )
977}
978
Prices keep themselves current with what g1t pays979impl Billing {
980 fn from_env(env: &Env) -> Result<Self> {
981 Ok(Billing {
982 db: env.d1("DB")?,
983 stripe: env
984 .secret("STRIPE_SECRET_KEY")
985 .ok()
986 .map(|key| key.to_string())
987 .filter(|key| !key.is_empty())
988 .map(Stripe::new),
Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard989 webhook_secret: env
990 .secret("STRIPE_WEBHOOK_SECRET")
991 .ok()
992 .map(|secret| secret.to_string().trim().to_owned())
993 .filter(|secret| !secret.is_empty()),
Prices keep themselves current with what g1t pays994 margin_percent: env
995 .var("MARGIN_PERCENT")
996 .ok()
997 .and_then(|percent| percent.to_string().parse().ok())
998 .unwrap_or(20),
999 free: env.var("FREE_WHILE_BUILDING").is_ok_and(|v| v.to_string() == "true"),
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1000 ceilings: limits::Ceilings::from_env(env),
Billing accounts, terms and enterprises; g1t is no longer free1001 prepaid_only: env.var("PREPAID_ONLY").is_ok_and(|v| v.to_string() == "true"),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1002 trials_on: {
1003 let plans = credits::Config::from_env(env);
1004 plans.trial_workspace_micros > 0 && plans.trial_monthly_pool_micros > 0
Prices keep themselves current with what g1t pays1005 },
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1006 plans: credits::Config::from_env(env),
1007 repos: env.service("REPOS").ok(),
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member1008 packages: env.service("PACKAGES").ok(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1009 identity: env.service("IDENTITY").ok(),
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays1010 caps: budget::Caps::from_env(env),
1011 env: env.clone(),
Prices keep themselves current with what g1t pays1012 })
1013 }
1014}
1015
1016#[event(scheduled)]
1017async fn scheduled(event: ScheduledEvent, env: Env, _ctx: ScheduleContext) {
1018 let Ok(billing) = Billing::from_env(&env) else {
1019 return;
1020 };
1021 let keeper = keeper::Keeper::from_env(&env);
1022 if let Err(error) = billing.settle_runs(&keeper).await {
1023 worker::console_error!("settling runs failed: {error}");
1024 }
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1025 // Stripe events billing never received, handled now.
1026 match billing.replay_events().await {
1027 Ok(done) => worker::console_log!("stripe replay: {done}"),
1028 Err(error) => worker::console_error!("replaying Stripe events failed: {error}"),
1029 }
Billing accounts, terms and enterprises; g1t is no longer free1030 if let Err(error) = billing.autopay().await {
1031 worker::console_error!("paying at the limit failed: {error}");
1032 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1033 // Last month's metered usage (scans, embeddings, storage) goes on the
1034 // ledger before the month is closed and invoiced.
1035 if let Err(error) = billing.charge_pending().await {
1036 worker::console_error!("charging last month's metered usage failed: {error}");
1037 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1038 if let Err(error) = billing.close_months().await {
1039 worker::console_error!("closing the month failed: {error}");
1040 }
Stripe webhooks, enterprise invoices, and sudo for both1041 if let Err(error) = billing.invoice_enterprises().await {
1042 worker::console_error!("invoicing enterprises failed: {error}");
1043 }
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays1044 // Comped budgets' alerts, and a tripped breaker staff were not told of.
1045 if let Err(error) = billing.watch_spend().await {
1046 worker::console_error!("watching g1t's own spend failed: {error}");
1047 }
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1048 if let Ok(identity) = env.service("IDENTITY")
1049 && let Err(error) = billing.warn_limits(&identity).await {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1050 worker::console_error!("warning owners failed: {error}");
1051 }
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1052 // Once a day: Stripe's endpoint kept listening to billing's events and
1053 // enabled, and saved cards and plans not read in a while read again.
1054 if event.cron() == keeper::DAILY {
Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard1055 match billing.keep_endpoint("billing").await {
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1056 Ok(done) => worker::console_log!("stripe endpoint: {done}"),
1057 Err(error) => worker::console_error!("keeping Stripe's endpoint failed: {error}"),
1058 }
1059 match billing.refresh_from_stripe().await {
1060 Ok(done) => worker::console_log!("stripe refresh: {done}"),
1061 Err(error) => worker::console_error!("refreshing from Stripe failed: {error}"),
1062 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1063 }
The keeper reads Cloudflare as it really answers1064 // Once a day, and at once if the costs were never checked: check every
1065 // cost against what Cloudflare billed.
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1066 if (event.cron() == keeper::DAILY || billing.never_checked().await.unwrap_or(false))
1067 && let Err(error) = billing.reconcile(&keeper).await {
Prices keep themselves current with what g1t pays1068 worker::console_error!("checking costs against Cloudflare failed: {error}");
1069 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1070 // Once a day: what Cloudflare charged, reconciled against what g1t
1071 // counted and charged; prices whose day has come; margin alerts
1072 // (margin.rs). After the keeper, so its proposals are in.
1073 if event.cron() == keeper::DAILY {
1074 match billing.costs_daily(&env, &keeper).await {
1075 Ok(run) => worker::console_log!("costs: {} lines, {} days, {} proposals, {} alerts", run.lines, run.days, run.proposals, run.alerts),
1076 Err(error) => worker::console_error!("reconciling costs failed: {error}"),
1077 }
1078 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1079 // Once a day: what each workspace's private repositories hold, its git
1080 // operations, Deployments plans from before the g1t plan set to end,
1081 // and old reservations cleared.
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1082 if event.cron() == keeper::DAILY {
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member1083 if let Err(error) = billing.measure_packages().await {
1084 worker::console_error!("measuring package storage failed: {error}");
1085 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1086 if let Err(error) = billing.measure_storage().await {
1087 worker::console_error!("measuring storage failed: {error}");
1088 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1089 if let Err(error) = billing.measure_git().await {
1090 worker::console_error!("measuring git operations failed: {error}");
1091 }
1092 if let Err(error) = billing.retire_deployments_plans().await {
1093 worker::console_error!("ending Deployments plans failed: {error}");
1094 }
1095 if let Err(error) = billing.sweep_reservations().await {
1096 worker::console_error!("clearing reservations failed: {error}");
1097 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1098 }
Prices keep themselves current with what g1t pays1099}
1100
Agents and memory, checks and conflicts, profiles, slug renames, custom domains1101/// Events from the bus, on billing's own queue: only a workspace's rename
1102/// matters here (see `rename`).
1103#[event(queue)]
1104async fn queue(batch: MessageBatch<g1t_contracts::events::Event>, env: Env, _ctx: Context) -> Result<()> {
1105 let billing = Billing::from_env(&env)?;
1106 let identity = env.service("IDENTITY").ok();
1107 for message in batch.messages()? {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1108 // A repository transferred: its share of the open-source pool this
1109 // month follows it. What it was charged stays with the workspace
1110 // it was charged to; usage from now on is charged to the new one.
1111 if g1t_kit::transfer::on_event(&env, &billing.db, message.body(), closing::TRANSFERRED).await? {
1112 message.ack();
1113 continue;
1114 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains1115 billing.on_event(identity.as_ref(), message.body()).await?;
1116 message.ack();
1117 }
1118 Ok(())
1119}
1120
Agents as a team: lifecycle, merge queue, billing and a new shell1121#[event(fetch)]
1122async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> {
1123 let Some(method) = rpc_method(&request) else {
1124 return Response::error("Not found", 404);
1125 };
Fast pages, required checks on the branch, self-hosted runners, honest incidents1126 // A replica near the caller when it asks for one (crates/kit/src/d1.rs);
1127 // what other services call (can_start, start_run) asks for none.
1128 let (db, served) = g1t_kit::d1::open(&env, "DB", &request)?;
Agents as a team: lifecycle, merge queue, billing and a new shell1129 let body: serde_json::Value = request.json().await?;
Fast pages, required checks on the branch, self-hosted runners, honest incidents1130 let mut billing = Billing::from_env(&env)?;
1131 billing.db = db;
1132 let answered = match method.as_str() {
Agents as a team: lifecycle, merge queue, billing and a new shell1133 "status" => reply(&billing.status()),
1134 "account" => reply(&billing.account(args(body)?).await?),
1135 "ledger" => reply(&billing.ledger(args(body)?).await?),
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request1136 "usage" => reply(&billing.usage(args(body)?).await?),
Mission control shows model usage, yours and the workspace's: tokens, cost, active days, cache share, each day, and the mix1137 "record_tokens" => reply(&billing.record_tokens(args(body)?).await?),
1138 "token_usage" => reply(&billing.token_usage(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1139 "checkout" => reply(&billing.checkout(args(body)?).await?),
1140 "confirm" => reply(&billing.confirm(args(body)?).await?),
1141 "can_start" => reply(&billing.can_start(args(body)?).await?),
A free allowance on g1t's models, so anyone can try its agents1142 "trial" => reply(&billing.trial(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1143 "start_run" => reply(&billing.start_run(args(body)?).await?),
1144 "finish_run" => reply(&billing.finish_run(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan1145 "features" => reply(&billing.features(args(body)?).await?),
1146 "subscribe" => reply(&billing.subscribe(args(body)?).await?),
1147 "confirm_subscription" => reply(&billing.confirm_subscription(args(body)?).await?),
1148 "cancel_subscription" => reply(&billing.cancel_subscription(args(body)?).await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1149 "close_workspace" => reply(&billing.close_workspace(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan1150 "has_feature" => reply(&billing.has_feature(args(body)?).await?),
1151 "charge_feature" => reply(&billing.charge_feature(args(body)?).await?),
Every sandbox is metered by the second1152 "record_sandbox" => reply(&billing.record_sandbox(args(body)?).await?),
Usage limits: unpaid usage can only go so far1153 "limit" => reply(&billing.limit(args(body)?).await?),
1154 "check_limit" => reply(&billing.check_limit(args(body)?).await?),
1155 "set_spend_limit" => reply(&billing.set_spend_limit(args(body)?).await?),
Prices keep themselves current with what g1t pays1156 "prices" => reply(&billing.prices().await?),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1157 "billing_portal" => reply(&billing.billing_portal(args(body)?).await?),
1158 "admin_billing_link" => reply(&billing.admin_billing_link(args(body)?).await?),
Stripe webhooks, enterprise invoices, and sudo for both1159 "admin_stripe" => reply(&billing.admin_stripe(args(body)?).await?),
1160 "admin_enterprise_billing" => reply(&billing.admin_enterprise_billing(args(body)?).await?),
1161 "admin_invoice_enterprise" => reply(&billing.admin_invoice_enterprise(args(body)?).await?),
1162 "stripe_webhook" => reply(&billing.stripe_webhook(args(body)?).await?),
Two limits, real invoices, trust that grows by itself, sales signals1163 "invoices" => reply(&billing.invoices(args(body)?).await?),
The statement is a month at a time, a line per kind of charge1164 "statement" => reply(&billing.statement(args(body)?).await?),
1165 "statement_entries" => reply(&billing.statement_entries(args(body)?).await?),
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1166 "usage_meters" => reply(&billing.usage_meters(args(body)?).await?),
Two limits, real invoices, trust that grows by itself, sales signals1167 "admin_workspace_invoices" => {
1168 let a: AdminWorkspaceInvoicesArgs = args(body)?;
1169 reply(&billing.workspace_invoices(&a.workspace.to_lowercase()).await?)
1170 }
1171 "admin_signals" => reply(&billing.admin_signals(args(body)?).await?),
1172 "admin_overview" => reply(&billing.admin_overview(args(body)?).await?),
1173 "admin_sales" => reply(&billing.admin_sales(args(body)?).await?),
1174 "admin_set_sales" => reply(&billing.admin_set_sales(args(body)?).await?),
1175 "admin_add_note" => reply(&billing.admin_add_note(args(body)?).await?),
Billing lists every invoice and every staff change; signals carry follow-ups1176 "admin_invoices" => reply(&billing.admin_invoices(args(body)?).await?),
1177 "admin_audit" => reply(&billing.admin_audit(args(body)?).await?),
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member1178 // A staff change made in another service, for sudo's audit log:
1179 // identity's restores and purges of deleted workspaces.
1180 "admin_log" => {
1181 let a: AdminLogArgs = args(body)?;
1182 billing
1183 .audit(&accounts::own_account(&a.workspace), &a.action, &a.detail, &a.by)
1184 .await?;
1185 reply(&true)
1186 }
Prices keep themselves current with what g1t pays1187 "note_pending" => reply(&billing.note_pending(args(body)?).await?),
Billing accounts, terms and enterprises; g1t is no longer free1188 "admin_accounts" => reply(&billing.admin_accounts(args(body)?).await?),
1189 "admin_account" => reply(&billing.admin_account(args(body)?).await?),
1190 "admin_set_terms" => reply(&billing.admin_set_terms(args(body)?).await?),
1191 "admin_create_enterprise" => reply(&billing.admin_create_enterprise(args(body)?).await?),
1192 "admin_attach" => reply(&billing.admin_attach(args(body)?).await?),
1193 "admin_credit" => reply(&billing.admin_credit(args(body)?).await?),
sudo: reset a test workspace's billing so it starts again as a new customer; refused on a live Stripe key, for comped workspaces and for an enterprise's1194 "admin_reset_billing" => reply(&billing.admin_reset_billing(args(body)?).await?),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1195 "admin_set_allowances" => reply(&billing.admin_set_allowances(args(body)?).await?),
1196 "entitlements" => reply(&billing.entitlements(args(body)?).await?),
Audit logs are kept by plan: a week on free, 90 days on the plan, and what staff set for an account in sudo1197 "audit_retention" => reply(&billing.audit_retention(args(body)?).await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1198 "reserve" => reply(&billing.reserve(args(body)?).await?),
1199 "settle" => reply(&billing.settle_reservation(args(body)?).await?),
1200 "card_check" => reply(&billing.card_check(args(body)?).await?),
1201 "confirm_card_check" => reply(&billing.confirm_card_check(args(body)?).await?),
1202 "request_limit" => reply(&billing.request_limit(args(body)?).await?),
1203 "limit_requests" => reply(&billing.limit_requests(args(body)?).await?),
1204 "confirm_spike" => reply(&billing.confirm_spike(args(body)?).await?),
1205 "set_caps" => reply(&billing.set_caps(args(body)?).await?),
1206 "admin_limit_requests" => reply(&billing.admin_limit_requests(args(body)?).await?),
1207 "admin_decide_limit_request" => reply(&billing.admin_decide_limit_request(args(body)?).await?),
1208 "admin_overages" => reply(&billing.admin_overages(args(body)?).await?),
1209 "admin_goodwill" => reply(&billing.admin_goodwill(args(body)?).await?),
1210 "admin_velocity" => reply(&billing.admin_velocity(args(body)?).await?),
1211 "admin_record_payment" => reply(&billing.admin_record_payment(args(body)?).await?),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1212 "admin_costs" => reply(&billing.admin_costs(args(body)?, keeper::Keeper::from_env(&env).can_read_bill()).await?),
1213 "admin_cost_alerts" => reply(&billing.admin_cost_alerts(args(body)?).await?),
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays1214 "admin_spend_caps" => reply(&billing.spend_caps().await?),
1215 "admin_lift_breaker" => reply(&billing.admin_lift_breaker(args(body)?).await?),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1216 "admin_decide_proposal" => reply(&billing.admin_decide_proposal(args(body)?).await?),
1217 "admin_set_cost_settings" => reply(&billing.admin_set_cost_settings(args(body)?).await?),
1218 "admin_set_cost_mapping" => reply(&billing.admin_set_cost_mapping(args(body)?).await?),
1219 "admin_run_costs" => reply(&billing.admin_run_costs(&env, args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1220 _ => Response::error("Unknown method", 404),
Fast pages, required checks on the branch, self-hosted runners, honest incidents1221 };
1222 served.finish(answered)
Agents as a team: lifecycle, merge queue, billing and a new shell1223}
1224
1225#[cfg(test)]
1226mod tests {
1227 use super::*;
1228
1229 #[test]
1230 fn a_run_is_charged_its_cost_plus_the_margin() {
1231 // $0.05 at 20% is six cents.
1232 assert_eq!(charge_micros(0.05, 20), 60_000);
1233 assert_eq!(charge_micros(1.0, 20), 1_200_000);
1234 assert_eq!(charge_micros(0.05, 0), 50_000);
1235 }
1236
1237 #[test]
1238 fn fractions_of_a_millionth_round_up_and_nothing_costs_less_than_nothing() {
1239 assert_eq!(charge_micros(0.000_000_4, 20), 2);
1240 assert_eq!(charge_micros(0.0, 20), 0);
1241 assert_eq!(charge_micros(-3.0, 20), 0);
1242 }
1243
1244 #[test]
Prices are what g1t pays plus 20%, from the first second1245 fn sandbox_time_is_charged_from_the_first_second() {
1246 // 21 millionths a second at cost, plus 20%.
1247 let price = Price::price_for(21.0, 20);
1248 assert_eq!(sandbox_charge(1, price), 26);
1249 assert_eq!(sandbox_charge(60, price), 1_512);
1250 assert_eq!(sandbox_charge(0, price), 0);
Every sandbox is metered by the second1251 }
1252
1253 #[test]
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1254 fn prepaying_starts_at_twenty_five_dollars_and_bank_transfers_at_a_thousand() {
1255 assert!(prepay_amount(2_500, false).is_ok());
1256 assert!(prepay_amount(2_499, false).is_err());
1257 assert!(prepay_amount(10_000, false).is_ok());
1258 assert!(prepay_amount(1_000_000, false).is_ok());
1259 assert_eq!(prepay_amount(1_000_001, false).unwrap_err(), "Prepay between $25 and $10,000 by card; from $1,000, a bank transfer works too.");
1260 assert!(prepay_amount(99_999, true).is_err());
1261 assert!(prepay_amount(100_000, true).is_ok());
1262 }
1263
1264 #[test]
Every sandbox is metered by the second1265 fn durations_read_plainly() {
1266 assert_eq!(duration(40), "40s");
1267 assert_eq!(duration(192), "3m 12s");
1268 assert_eq!(duration(3720), "1h 2m");
1269 }
1270
1271 #[test]
Agents as a team: lifecycle, merge queue, billing and a new shell1272 fn an_absurd_cost_is_capped() {
1273 assert_eq!(charge_micros(1e9, 20), 120 * MICROS_PER_DOLLAR);
1274 }
1275}