pr_01m47d15m3e54sn21z27rpy5n9/services/billing/src/lib.rs

1,068 lines42,284 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.

Agents as a team: lifecycle, merge queue, billing and a new shell1//! The billing service: what agents cost, charged to the workspace they
2//! worked for.
3//!
4//! A workspace buys credit with a card. Before the runner starts an agent
5//! it asks here, and is refused if the workspace has none. When the
6//! agent's sandbox finishes it reports what the model cost, and that plus
7//! g1t's margin comes off the balance. Every change is a ledger entry, and
8//! a balance is always the sum of its ledger.
9//!
Paid features: a workspace turns on Deployments with a monthly plan10//! Paid features (deployments) are bought separately, as monthly plans;
11//! see `features`. They are never free.
12//!
Agents as a team: lifecycle, merge queue, billing and a new shell13//! Without a card processor configured the service says so and charges
14//! nothing, so that g1t still runs where billing has not been set up.
15//!
16//! Reached only through service bindings; see `g1t_contracts::billing` for
17//! the methods and their arguments.
18
Billing accounts, terms and enterprises; g1t is no longer free19mod accounts;
Stripe webhooks, enterprise invoices, and sudo for both20mod webhooks;
Paid features: a workspace turns on Deployments with a monthly plan21mod features;
Prices keep themselves current with what g1t pays22mod keeper;
Usage limits: unpaid usage can only go so far23mod limits;
Agents as a team: lifecycle, merge queue, billing and a new shell24mod stripe;
25
26use g1t_contracts::billing::*;
27use g1t_contracts::time::rfc3339;
28use g1t_contracts::{FailureCode, Outcome, Role, new_id};
Billing accounts, terms and enterprises; g1t is no longer free29use g1t_contracts::billing::TermsKind;
Agents as a team: lifecycle, merge queue, billing and a new shell30use g1t_kit::{args, now_ms, reply, rpc_method};
31use serde::Deserialize;
32use sha2::{Digest, Sha256};
33use worker::wasm_bindgen::JsValue;
Prices keep themselves current with what g1t pays34use worker::{Context, D1Database, Env, Request, Response, Result, ScheduleContext, ScheduledEvent, event};
Agents as a team: lifecycle, merge queue, billing and a new shell35
36use stripe::Stripe;
37
38const MIN_TOP_UP_CENTS: u32 = 500;
39const MAX_TOP_UP_CENTS: u32 = 50_000;
40const LEDGER_PAGE: u32 = 100;
41/// A run's reported cost is believed up to this much. A sandbox cannot
42/// spend more in the time it has, so anything above is a fault.
43const MAX_RUN_COST_USD: f64 = 100.0;
44
45/// What a run is charged: its cost plus the margin, rounded up to a whole
46/// millionth of a dollar.
47pub fn charge_micros(cost_usd: f64, margin_percent: u32) -> i64 {
48 let cost_micros = (cost_usd.clamp(0.0, MAX_RUN_COST_USD) * MICROS_PER_DOLLAR as f64).ceil();
49 (cost_micros * f64::from(100 + margin_percent) / 100.0).ceil() as i64
50}
51
52fn hash(token: &str) -> String {
53 hex::encode(Sha256::digest(token.as_bytes()))
54}
55
56fn optional(value: Option<&str>) -> JsValue {
57 value.map_or(JsValue::NULL, JsValue::from)
58}
59
60#[derive(Deserialize)]
61struct AccountRow {
62 balance_micros: i64,
63 customer_id: Option<String>,
64}
65
66#[derive(Deserialize)]
67struct LedgerRow {
68 id: String,
69 kind: EntryKind,
70 amount_micros: i64,
71 description: String,
72 repo: Option<String>,
73 number: Option<u32>,
74 task: Option<String>,
75 model: Option<String>,
76 created_by: Option<String>,
77 created_at: String,
Integrations: your own model provider, alerts that open issues, tickets agents read78 billed_to: Option<String>,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace79 #[serde(default)]
80 workspace: Option<String>,
Agents as a team: lifecycle, merge queue, billing and a new shell81}
82
83impl From<LedgerRow> for LedgerEntry {
84 fn from(row: LedgerRow) -> Self {
85 LedgerEntry {
86 id: row.id,
87 kind: row.kind,
88 amount_micros: row.amount_micros,
89 description: row.description,
90 repo: row.repo,
91 number: row.number,
92 task: row.task,
93 model: row.model,
Integrations: your own model provider, alerts that open issues, tickets agents read94 billed_to: row.billed_to.unwrap_or_else(|| "g1t".to_owned()),
Agents as a team: lifecycle, merge queue, billing and a new shell95 created_by: row.created_by,
96 created_at: row.created_at,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace97 workspace: row.workspace,
Agents as a team: lifecycle, merge queue, billing and a new shell98 }
99 }
100}
101
102#[derive(Deserialize)]
103struct RunRow {
104 workspace: String,
105 repo: String,
106 number: u32,
107 task: String,
108 model: String,
109 token_hash: String,
Integrations: your own model provider, alerts that open issues, tickets agents read110 billed_to: Option<String>,
111}
112
113impl RunRow {
114 fn own_provider(&self) -> bool {
115 self.billed_to.as_deref() == Some("workspace")
116 }
Agents as a team: lifecycle, merge queue, billing and a new shell117}
118
119#[derive(Deserialize)]
120struct CheckoutRow {
121 workspace: String,
122 created_by: String,
123}
124
125/// A row an `UPDATE … RETURNING` touched.
126#[derive(Deserialize)]
127struct Touched {
128 #[allow(dead_code)]
129 id: String,
130}
131
132struct Billing {
133 db: D1Database,
134 /// Absent when no card processor is configured.
135 stripe: Option<Stripe>,
136 margin_percent: u32,
Integrations: your own model provider, alerts that open issues, tickets agents read137 /// Charged for a run on the workspace's own model provider.
138 orchestration_fee_micros: i64,
Free while g1t is being built out; agents can check out their own forks139 /// While g1t is being built out, nothing is charged (`FREE_WHILE_BUILDING`).
140 free: bool,
A free allowance on g1t's models, so anyone can try its agents141 /// The free allowance on g1t's hosted models, when there is one.
142 trial: Option<TrialConfig>,
Paid features: a workspace turns on Deployments with a monthly plan143 /// The Deployments plan's monthly price (`DEPLOYMENTS_MONTHLY_CENTS`).
144 deployments_monthly_cents: u32,
Usage limits: unpaid usage can only go so far145 /// How far unpaid usage may go; see `limits`.
146 ceilings: limits::Ceilings,
Billing accounts, terms and enterprises; g1t is no longer free147 /// `PREPAID_ONLY`: the old rule, that agents need credit first.
148 prepaid_only: bool,
A free allowance on g1t's models, so anyone can try its agents149}
150
151/// `TRIAL_WORKSPACE_MICROS`, `TRIAL_TOTAL_MICROS` and `TRIAL_UNTIL`.
152struct TrialConfig {
153 per_workspace_micros: i64,
154 total_micros: i64,
155 /// RFC 3339, in UTC.
156 until: String,
157}
158
159#[derive(serde::Deserialize)]
160struct Sum {
161 micros: Option<i64>,
Agents as a team: lifecycle, merge queue, billing and a new shell162}
163
164impl Billing {
165 fn status(&self) -> Status {
166 Status {
167 enabled: self.stripe.is_some(),
168 live: self.stripe.as_ref().is_some_and(Stripe::live),
Free while g1t is being built out; agents can check out their own forks169 free: self.free,
Agents as a team: lifecycle, merge queue, billing and a new shell170 }
171 }
172
173 async fn row(&self, workspace: &str) -> Result<Option<AccountRow>> {
174 self.db
175 .prepare("SELECT balance_micros, customer_id FROM accounts WHERE workspace = ?")
176 .bind(&[workspace.into()])?
177 .first::<AccountRow>(None)
178 .await
179 }
180
181 async fn standing(&self, workspace: &str) -> Result<Account> {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace182 let row = self.row(workspace).await?;
183 let card = match (&self.stripe, row.as_ref().and_then(|row| row.customer_id.as_deref())) {
184 (Some(stripe), Some(customer)) => stripe.card(customer).await.ok().flatten().map(|card| Card {
185 brand: card.brand,
186 last4: card.last4,
187 exp_month: card.exp_month,
188 exp_year: card.exp_year,
189 }),
190 _ => None,
191 };
Agents as a team: lifecycle, merge queue, billing and a new shell192 Ok(Account {
193 workspace: workspace.to_owned(),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace194 balance_micros: row.map_or(0, |row| row.balance_micros),
Agents as a team: lifecycle, merge queue, billing and a new shell195 status: self.status(),
196 margin_percent: self.margin_percent,
Integrations: your own model provider, alerts that open issues, tickets agents read197 orchestration_fee_micros: self.orchestration_fee_micros,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace198 card,
Agents as a team: lifecycle, merge queue, billing and a new shell199 })
200 }
201
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace202 /// The workspace's customer at Stripe, made the first time one is needed.
203 pub(crate) async fn customer_for(&self, workspace: &str) -> Result<String> {
204 let Some(stripe) = &self.stripe else {
205 return Err(worker::Error::RustError("payments are not set up".into()));
206 };
207 if let Some(customer) = self.row(workspace).await?.and_then(|row| row.customer_id) {
208 return Ok(customer);
209 }
210 let customer = stripe.create_customer(workspace).await?;
211 self.db
212 .prepare(
213 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at) VALUES (?1, 0, ?2, ?3)
214 ON CONFLICT (workspace) DO UPDATE SET customer_id = ?2",
215 )
216 .bind(&[workspace.into(), customer.as_str().into(), rfc3339(now_ms()).into()])?
217 .run()
218 .await?;
219 Ok(customer)
220 }
221
222 /// Stripe's hosted billing page for the workspace. Owners only.
223 async fn billing_portal(&self, a: BillingPortalArgs) -> Result<Outcome<Checkout>> {
224 let workspace = a.workspace.to_lowercase();
225 if a.actor.role_in(&workspace) != Some(Role::Owner) {
226 return Ok(Outcome::fail(FailureCode::Forbidden, "Only an owner can manage the workspace's billing."));
227 }
228 let Some(stripe) = &self.stripe else {
229 return Ok(Outcome::fail(FailureCode::Conflict, "Payments are not set up on this g1t."));
230 };
231 let customer = match self.customer_for(&workspace).await {
232 Ok(customer) => customer,
233 Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe could not be reached: {error}"))),
234 };
235 match stripe.portal_session(&customer, &a.return_url).await {
236 Ok(url) => Ok(Outcome::Ok(Checkout { url })),
237 Err(error) if stripe::is_missing(&error) => {
238 // The customer was removed at Stripe: a new one next time.
239 self.forget_customer(&workspace).await?;
240 Ok(Outcome::fail(FailureCode::Conflict, "Stripe no longer had this workspace's customer. Try again."))
241 }
242 Err(error) => Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe's billing page could not be opened: {error}"))),
243 }
244 }
245
Agents as a team: lifecycle, merge queue, billing and a new shell246 /// Adds a ledger entry and moves the balance by the same amount, as
247 /// one write.
248 #[allow(clippy::too_many_arguments)]
249 async fn enter(
250 &self,
251 workspace: &str,
252 kind: EntryKind,
253 amount_micros: i64,
254 description: &str,
255 reference: &str,
256 run: Option<&RunRow>,
257 cost_micros: Option<i64>,
258 created_by: Option<&str>,
259 customer: Option<&str>,
260 ) -> Result<()> {
261 let now = now_ms();
262 let timestamp = rfc3339(now);
263 let kind = match kind {
264 EntryKind::TopUp => "top_up",
265 EntryKind::Usage => "usage",
266 };
267 self.db
268 .batch(vec![
269 self.db
270 .prepare(
271 "INSERT INTO ledger
272 (id, workspace, kind, amount_micros, description, repo, number, task,
Integrations: your own model provider, alerts that open issues, tickets agents read273 model, cost_micros, reference, created_by, created_at, billed_to)
274 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
Agents as a team: lifecycle, merge queue, billing and a new shell275 )
276 .bind(&[
277 new_id("led", now).into(),
278 workspace.into(),
279 kind.into(),
280 // D1 takes numbers as doubles, which hold every
281 // amount this service will see exactly.
282 (amount_micros as f64).into(),
283 description.into(),
284 optional(run.map(|run| run.repo.as_str())),
285 run.map_or(JsValue::NULL, |run| run.number.into()),
286 optional(run.map(|run| run.task.as_str())),
287 optional(run.map(|run| run.model.as_str())),
288 cost_micros.map_or(JsValue::NULL, |cost| (cost as f64).into()),
289 reference.into(),
290 optional(created_by),
291 timestamp.as_str().into(),
Integrations: your own model provider, alerts that open issues, tickets agents read292 run.map_or("g1t", |run| if run.own_provider() { "workspace" } else { "g1t" }).into(),
Agents as a team: lifecycle, merge queue, billing and a new shell293 ])?,
294 self.db
295 .prepare(
296 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at)
297 VALUES (?1, ?2, ?3, ?4)
298 ON CONFLICT (workspace) DO UPDATE SET
299 balance_micros = balance_micros + ?2,
300 customer_id = COALESCE(?3, customer_id)",
301 )
302 .bind(&[
303 workspace.into(),
304 (amount_micros as f64).into(),
305 optional(customer),
306 timestamp.as_str().into(),
307 ])?,
308 ])
309 .await?;
Billing accounts, terms and enterprises; g1t is no longer free310 // Money in clears a card declined at the limit.
311 if kind == "top_up" {
312 self.db
313 .prepare("UPDATE limits SET autopay_failed_at = NULL, autopay_error = NULL WHERE workspace = ?")
314 .bind(&[workspace.into()])?
315 .run()
316 .await?;
317 }
Agents as a team: lifecycle, merge queue, billing and a new shell318 Ok(())
319 }
320
321 async fn account(&self, a: AccountArgs) -> Result<Outcome<Account>> {
322 let workspace = a.workspace.to_lowercase();
323 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
324 return Ok(members_only());
325 }
326 Ok(Outcome::Ok(self.standing(&workspace).await?))
327 }
328
329 async fn ledger(&self, a: AccountArgs) -> Result<Outcome<Vec<LedgerEntry>>> {
330 let workspace = a.workspace.to_lowercase();
331 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
332 return Ok(members_only());
333 }
334 let rows = self
335 .db
336 .prepare("SELECT * FROM ledger WHERE workspace = ? ORDER BY id DESC LIMIT ?")
337 .bind(&[workspace.into(), LEDGER_PAGE.into()])?
338 .all()
339 .await?
340 .results::<LedgerRow>()?;
341 Ok(Outcome::Ok(
342 rows.into_iter().map(LedgerEntry::from).collect(),
343 ))
344 }
345
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request346 async fn usage(&self, a: UsageArgs) -> Result<Outcome<Usage>> {
347 let workspace = a.workspace.to_lowercase();
348 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
349 return Ok(members_only());
350 }
351 #[derive(serde::Deserialize)]
352 struct SliceRow {
353 key: Option<String>,
354 micros: Option<i64>,
355 runs: Option<u32>,
356 }
Usage while free is shown at cost; agents get rustfmt and clippy357 // While nothing is charged, what was used is what there is to show.
358 let measure = if self.free { "COALESCE(cost_micros, 0)" } else { "-amount_micros" };
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request359 let slices = |key: &str, limit: u32| {
360 format!(
Usage while free is shown at cost; agents get rustfmt and clippy361 "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 request362 WHERE workspace = ?1 AND kind = 'usage' AND created_at >= ?2
363 GROUP BY 1 ORDER BY micros DESC LIMIT {limit}"
364 )
365 };
366 let query = |sql: String| {
367 let db = &self.db;
368 let workspace = workspace.clone();
369 let since = a.since.clone();
370 async move {
371 let rows = db
372 .prepare(sql)
373 .bind(&[workspace.into(), since.into()])?
374 .all()
375 .await?
376 .results::<SliceRow>()?;
377 Ok::<Vec<UsageSlice>, worker::Error>(
378 rows.into_iter()
379 .map(|row| UsageSlice {
380 key: row.key.unwrap_or_else(|| "other".to_owned()),
381 micros: row.micros.unwrap_or_default(),
382 runs: row.runs.unwrap_or_default(),
383 })
384 .collect(),
385 )
386 }
387 };
388 #[derive(serde::Deserialize)]
389 struct Totals {
390 spent: Option<i64>,
391 cost: Option<i64>,
Integrations: your own model provider, alerts that open issues, tickets agents read392 provider: Option<i64>,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request393 runs: Option<u32>,
394 added: Option<i64>,
395 }
396 let totals = self
397 .db
398 .prepare(
399 "SELECT
400 -SUM(CASE WHEN kind = 'usage' THEN amount_micros END) AS spent,
Integrations: your own model provider, alerts that open issues, tickets agents read401 SUM(CASE WHEN kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' THEN cost_micros END) AS cost,
402 SUM(CASE WHEN kind = 'usage' AND billed_to = 'workspace' THEN cost_micros END) AS provider,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request403 SUM(CASE WHEN kind = 'usage' THEN 1 ELSE 0 END) AS runs,
404 SUM(CASE WHEN kind = 'top_up' THEN amount_micros END) AS added
405 FROM ledger WHERE workspace = ?1 AND created_at >= ?2",
406 )
407 .bind(&[workspace.as_str().into(), a.since.as_str().into()])?
408 .first::<Totals>(None)
409 .await?;
410 let totals = totals.unwrap_or(Totals {
411 spent: None,
412 cost: None,
Integrations: your own model provider, alerts that open issues, tickets agents read413 provider: None,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request414 runs: None,
415 added: None,
416 });
417 Ok(Outcome::Ok(Usage {
418 spent_micros: totals.spent.unwrap_or_default(),
419 cost_micros: totals.cost.unwrap_or_default(),
Integrations: your own model provider, alerts that open issues, tickets agents read420 provider_micros: totals.provider.unwrap_or_default(),
Usage while free is shown at cost; agents get rustfmt and clippy421 used_micros: totals.cost.unwrap_or_default() + totals.provider.unwrap_or_default(),
422 free: self.free,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request423 runs: totals.runs.unwrap_or_default(),
424 added_micros: totals.added.unwrap_or_default(),
425 by_day: query(slices("substr(created_at, 1, 10) || '/' || COALESCE(task, 'other')", 400)).await?,
426 by_task: query(slices("task", 20)).await?,
427 by_repo: query(slices("repo", 20)).await?,
428 by_pull: query(slices("repo || '#' || number", 10)).await?,
429 by_model: query(slices("model", 10)).await?,
430 since: a.since,
431 }))
432 }
433
Agents as a team: lifecycle, merge queue, billing and a new shell434 async fn checkout(&self, a: CheckoutArgs) -> Result<Outcome<Checkout>> {
435 let workspace = a.workspace.to_lowercase();
436 if a.actor.role_in(&workspace) != Some(Role::Owner) {
437 return Ok(Outcome::fail(
438 FailureCode::Forbidden,
439 "Only an owner can add credit to a workspace.",
440 ));
441 }
442 let Some(stripe) = &self.stripe else {
443 return Ok(Outcome::fail(
444 FailureCode::Conflict,
445 "Payments are not set up on this g1t yet.",
446 ));
447 };
448 if !(MIN_TOP_UP_CENTS..=MAX_TOP_UP_CENTS).contains(&a.amount_cents) {
449 return Ok(Outcome::fail(
450 FailureCode::Invalid,
451 format!(
452 "Add between ${} and ${} at a time.",
453 MIN_TOP_UP_CENTS / 100,
454 MAX_TOP_UP_CENTS / 100
455 ),
456 ));
457 }
458 let customer = self.row(&workspace).await?.and_then(|row| row.customer_id);
Project dependencies: addresses, preview stacks, Affects, and agents who know459 let session = match stripe
460 .start_checkout(&workspace, a.amount_cents, customer.as_deref(), &a.return_url)
461 .await
462 {
463 Ok(session) => session,
464 // A customer saved under another Stripe account: start afresh.
465 Err(error) if customer.is_some() && stripe::is_missing(&error) => {
466 self.forget_customer(&workspace).await?;
467 stripe.start_checkout(&workspace, a.amount_cents, None, &a.return_url).await?
468 }
469 Err(error) => return Err(error),
470 };
Agents as a team: lifecycle, merge queue, billing and a new shell471 let Some(url) = session.url else {
472 return Err(worker::Error::RustError(
473 "the card processor returned no payment page".into(),
474 ));
475 };
476 self.db
477 .prepare(
478 "INSERT INTO checkouts (id, workspace, amount_cents, created_by, created_at)
479 VALUES (?, ?, ?, ?, ?)",
480 )
481 .bind(&[
482 session.id.into(),
483 workspace.into(),
484 a.amount_cents.into(),
485 a.actor.username.into(),
486 rfc3339(now_ms()).into(),
487 ])?
488 .run()
489 .await?;
490 Ok(Outcome::Ok(Checkout { url }))
491 }
492
493 /// Credits a payment if the processor says it was made and it has not
494 /// been credited before. The amount credited is what the processor
495 /// says was paid, not what anyone here remembers asking for.
496 async fn confirm(&self, a: ConfirmArgs) -> Result<Outcome<Account>> {
497 let workspace = a.workspace.to_lowercase();
498 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
499 return Ok(members_only());
500 }
501 let (Some(stripe), Some(checkout)) = (
502 &self.stripe,
503 self.db
504 .prepare(
505 "SELECT workspace, created_by FROM checkouts
506 WHERE id = ? AND workspace = ? AND status = 'open'",
507 )
508 .bind(&[a.session.as_str().into(), workspace.as_str().into()])?
509 .first::<CheckoutRow>(None)
510 .await?,
511 ) else {
512 // Unknown, someone else's, or already credited: nothing to do.
513 return Ok(Outcome::Ok(self.standing(&workspace).await?));
514 };
515 let session = stripe.session(&a.session).await?;
516 let paid = session
517 .amount_total
518 .filter(|_| session.payment_status == "paid");
519 if let Some(cents) = paid {
520 // Only whoever flips it from open to paid enters the credit.
521 let claimed = self
522 .db
523 .prepare(
524 "UPDATE checkouts SET status = 'paid' WHERE id = ? AND status = 'open'
525 RETURNING id",
526 )
527 .bind(&[a.session.as_str().into()])?
528 .first::<Touched>(None)
529 .await?;
530 if claimed.is_some() {
531 self.enter(
532 &checkout.workspace,
533 EntryKind::TopUp,
534 i64::from(cents) * MICROS_PER_DOLLAR / 100,
535 "Credit added by card",
536 &session.id,
537 None,
538 None,
539 Some(&checkout.created_by),
540 session.customer.as_deref(),
541 )
542 .await?;
543 }
544 }
545 Ok(Outcome::Ok(self.standing(&workspace).await?))
546 }
547
Project dependencies: addresses, preview stacks, Affects, and agents who know548 /// Drops a saved customer the card processor no longer knows.
549 pub(crate) async fn forget_customer(&self, workspace: &str) -> Result<()> {
550 self.db
551 .prepare("UPDATE accounts SET customer_id = NULL WHERE workspace = ?")
552 .bind(&[workspace.into()])?
553 .run()
554 .await?;
555 Ok(())
556 }
557
Agents as a team: lifecycle, merge queue, billing and a new shell558 /// A refusal if the workspace has no credit to start an agent with.
559 async fn out_of_credit<T>(&self, workspace: &str) -> Result<Option<Outcome<T>>> {
Billing accounts, terms and enterprises; g1t is no longer free560 // Billing is postpaid: usage limits decide whether work starts
561 // (see `limits`), and credit is a prepayment that lowers what is
562 // owed. A balance no longer has to be positive to start.
563 if self.free || !self.prepaid_only {
Free while g1t is being built out; agents can check out their own forks564 return Ok(None);
565 }
Agents as a team: lifecycle, merge queue, billing and a new shell566 let balance = self
567 .row(workspace)
568 .await?
569 .map_or(0, |row| row.balance_micros);
570 Ok((balance <= 0).then(|| {
571 Outcome::fail(
572 FailureCode::PaymentRequired,
573 format!(
574 "The {workspace} workspace has no agent credit. An owner can add some under Billing on the workspace's page."
575 ),
576 )
577 }))
578 }
579
A free allowance on g1t's models, so anyone can try its agents580 /// A workspace's free allowance on g1t's hosted models: what its runs
581 /// there have cost against its share, and the pool everyone draws on.
Billing accounts, terms and enterprises; g1t is no longer free582 /// How much of a hosted model run's cost the workspace's free allowance
583 /// covers, if it is still open.
584 async fn trial_covers(&self, workspace: &str, cost_micros: i64) -> Result<i64> {
585 let trial = self.trial(TrialArgs { workspace: workspace.to_owned(), exempt: vec![] }).await?;
586 if !trial.open {
587 return Ok(0);
588 }
589 Ok(cost_micros.min((trial.limit_micros - trial.used_micros).max(0)))
590 }
591
A free allowance on g1t's models, so anyone can try its agents592 async fn trial(&self, a: TrialArgs) -> Result<Trial> {
593 let workspace = a.workspace.to_lowercase();
594 let Some(config) = &self.trial else {
595 return Ok(Trial {
596 open: false,
597 used_micros: 0,
598 limit_micros: 0,
599 ends_at: None,
600 reason: Some("off".to_owned()),
601 });
602 };
603 let used = self
604 .db
605 .prepare(
606 "SELECT SUM(cost_micros) AS micros FROM ledger
Billing accounts, terms and enterprises; g1t is no longer free607 WHERE kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' AND COALESCE(task, '') NOT IN ('sandbox', 'deployments') AND workspace = ?",
A free allowance on g1t's models, so anyone can try its agents608 )
609 .bind(&[workspace.as_str().into()])?
610 .first::<Sum>(None)
611 .await?
612 .and_then(|sum| sum.micros)
613 .unwrap_or_default();
614 // Everyone's, but for the workspaces open to hosted models anyway.
615 let exempt: Vec<String> = a.exempt.iter().map(|name| name.trim().to_lowercase()).collect();
616 let marks = vec!["?"; exempt.len().max(1)].join(", ");
617 let mut values: Vec<JsValue> = exempt.iter().map(|name| JsValue::from(name.as_str())).collect();
618 if values.is_empty() {
619 values.push(JsValue::from(""));
620 }
621 let pooled = self
622 .db
623 .prepare(format!(
624 "SELECT SUM(cost_micros) AS micros FROM ledger
Billing accounts, terms and enterprises; g1t is no longer free625 WHERE kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' AND COALESCE(task, '') NOT IN ('sandbox', 'deployments') AND workspace NOT IN ({marks})"
A free allowance on g1t's models, so anyone can try its agents626 ))
627 .bind(&values)?
628 .first::<Sum>(None)
629 .await?
630 .and_then(|sum| sum.micros)
631 .unwrap_or_default();
632 let reason = if rfc3339(now_ms()) >= config.until {
633 Some("ended")
634 } else if used >= config.per_workspace_micros {
635 Some("used")
636 } else if pooled >= config.total_micros {
637 Some("pool")
638 } else {
639 None
640 };
641 Ok(Trial {
642 open: reason.is_none(),
643 used_micros: used,
644 limit_micros: config.per_workspace_micros,
645 ends_at: Some(config.until.clone()),
646 reason: reason.map(str::to_owned),
647 })
648 }
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(
Prices keep themselves current with what g1t pays681 "INSERT INTO runs (id, workspace, repo, number, task, model, token_hash, created_at, billed_to, session_id)
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")),
Agents as a team: lifecycle, merge queue, billing and a new shell695 ])?
696 .run()
697 .await?;
698 Ok(Outcome::Ok(Some(RunTicket { run_id, token })))
699 }
700
701 async fn finish_run(&self, a: FinishRunArgs) -> Result<Outcome<bool>> {
702 let run = self
703 .db
704 .prepare(
Integrations: your own model provider, alerts that open issues, tickets agents read705 "SELECT workspace, repo, number, task, model, token_hash, billed_to FROM runs
Agents as a team: lifecycle, merge queue, billing and a new shell706 WHERE id = ? AND finished_at IS NULL",
707 )
708 .bind(&[a.run_id.as_str().into()])?
709 .first::<RunRow>(None)
710 .await?;
711 let Some(run) = run.filter(|run| run.token_hash == hash(&a.token)) else {
712 return Ok(Outcome::fail(FailureCode::NotFound, "Run not found."));
713 };
714 if !a.cost_usd.is_finite() || a.cost_usd < 0.0 {
715 return Ok(Outcome::fail(FailureCode::Invalid, "That is not a cost."));
716 }
717 // Only whoever closes the run charges for it.
718 let claimed = self
719 .db
720 .prepare(
721 "UPDATE runs SET finished_at = ? WHERE id = ? AND finished_at IS NULL RETURNING id",
722 )
723 .bind(&[rfc3339(now_ms()).into(), a.run_id.as_str().into()])?
724 .first::<Touched>(None)
725 .await?;
726 if claimed.is_none() {
727 return Ok(Outcome::Ok(false));
728 }
Integrations: your own model provider, alerts that open issues, tickets agents read729 // On the workspace's own provider, the model was paid for there:
730 // g1t charges its fee, and keeps the provider's cost to show.
Billing accounts, terms and enterprises; g1t is no longer free731 let base = if run.own_provider() {
Integrations: your own model provider, alerts that open issues, tickets agents read732 self.orchestration_fee_micros
733 } else {
Billing accounts, terms and enterprises; g1t is no longer free734 // The free allowance on g1t's models covers what it can.
735 let cost = charge_micros(a.cost_usd, 0);
736 let covered = self.trial_covers(&run.workspace, cost).await?;
737 charge_micros((cost - covered) as f64 / MICROS_PER_DOLLAR as f64, self.margin_percent)
Integrations: your own model provider, alerts that open issues, tickets agents read738 };
Billing accounts, terms and enterprises; g1t is no longer free739 let (charge, terms_note) = self.charged(&run.workspace, base).await?;
Integrations: your own model provider, alerts that open issues, tickets agents read740 let mut description = match run.task.as_str() {
Agents as a team: lifecycle, merge queue, billing and a new shell741 "plan" => format!("Planning for {}", run.repo),
742 "review" => format!("Review of {}#{}", run.repo, run.number),
743 "update" => format!("Catching up {}#{}", run.repo, run.number),
744 _ => format!("Work on {}#{}", run.repo, run.number),
745 };
Integrations: your own model provider, alerts that open issues, tickets agents read746 if run.own_provider() {
747 description.push_str(", on your own model provider");
748 }
Billing accounts, terms and enterprises; g1t is no longer free749 description.push_str(&terms_note);
Agents as a team: lifecycle, merge queue, billing and a new shell750 self.enter(
751 &run.workspace,
752 EntryKind::Usage,
753 -charge,
754 &description,
755 &a.run_id,
756 Some(&run),
757 Some(charge_micros(a.cost_usd, 0)),
758 None,
759 None,
760 )
761 .await?;
762 Ok(Outcome::Ok(true))
763 }
764}
765
Every sandbox is metered by the second766impl Billing {
767 /// Records how long a sandbox ran: its cost always, and a charge for
768 /// the seconds past the month's free minutes.
769 async fn record_sandbox(&self, a: RecordSandboxArgs) -> Result<Outcome<bool>> {
770 if self.stripe.is_none() || a.seconds == 0 {
771 return Ok(Outcome::Ok(false));
772 }
773 let workspace = a.workspace.to_lowercase();
774 let seen = self
775 .db
776 .prepare("SELECT id FROM ledger WHERE reference = ?")
777 .bind(&[a.reference.as_str().into()])?
778 .first::<Touched>(None)
779 .await?;
780 if seen.is_some() {
781 return Ok(Outcome::Ok(false));
782 }
783 let now = now_ms();
784 let timestamp = rfc3339(now);
785 let month = &timestamp[..7];
786 #[derive(Deserialize)]
787 struct Used {
788 seconds: i64,
789 }
790 let seconds = i64::from(a.seconds);
791 let after = self
792 .db
793 .prepare(
794 "INSERT INTO sandbox_months (workspace, month, seconds) VALUES (?1, ?2, ?3)
795 ON CONFLICT (workspace, month) DO UPDATE SET seconds = seconds + ?3
796 RETURNING seconds",
797 )
798 .bind(&[workspace.as_str().into(), month.into(), (seconds as f64).into()])?
799 .first::<Used>(None)
800 .await?
801 .map_or(seconds, |used| used.seconds);
802 let billable = sandbox_billable(after - seconds, seconds);
Prices keep themselves current with what g1t pays803 // From the price book, which follows what Cloudflare bills g1t.
804 let (cost_per_second, price_per_second) = self.price("sandbox_second").await?.unwrap_or((
805 sandbox_allowance::COST_MICROS_PER_SECOND as f64,
806 sandbox_allowance::MICROS_PER_SECOND as f64,
807 ));
Billing accounts, terms and enterprises; g1t is no longer free808 let (charge, terms_note) = self.charged(&workspace, (billable as f64 * price_per_second).ceil() as i64).await?;
Every sandbox is metered by the second809 let mut description = format!("{}: {} of sandbox time", a.description, duration(seconds));
810 if billable < seconds {
811 description.push_str(if billable == 0 {
812 ", within the month's free minutes"
813 } else {
814 ", partly within the month's free minutes"
815 });
816 }
Billing accounts, terms and enterprises; g1t is no longer free817 if billable > 0 {
818 description.push_str(&terms_note);
Every sandbox is metered by the second819 }
820 self.db
821 .batch(vec![
822 self.db
823 .prepare(
824 "INSERT INTO ledger
825 (id, workspace, kind, amount_micros, description, repo, task,
826 cost_micros, reference, created_at, billed_to)
827 VALUES (?, ?, 'usage', ?, ?, ?, 'sandbox', ?, ?, ?, 'g1t')",
828 )
829 .bind(&[
830 new_id("led", now).into(),
831 workspace.as_str().into(),
832 (-(charge as f64)).into(),
833 description.as_str().into(),
834 optional(a.repo.as_deref()),
Prices keep themselves current with what g1t pays835 (seconds as f64 * cost_per_second).ceil().into(),
Every sandbox is metered by the second836 a.reference.as_str().into(),
837 timestamp.as_str().into(),
838 ])?,
839 self.db
840 .prepare(
841 "INSERT INTO accounts (workspace, balance_micros, created_at)
842 VALUES (?1, ?2, ?3)
843 ON CONFLICT (workspace) DO UPDATE SET balance_micros = balance_micros + ?2",
844 )
845 .bind(&[
846 workspace.as_str().into(),
847 (-(charge as f64)).into(),
848 timestamp.as_str().into(),
849 ])?,
850 ])
851 .await?;
852 Ok(Outcome::Ok(true))
853 }
854}
855
856/// Of `seconds` used after `before` this month, how many are past the
857/// free minutes.
858fn sandbox_billable(before: i64, seconds: i64) -> i64 {
859 let free_left = (sandbox_allowance::FREE_SECONDS - before).max(0);
860 (seconds - free_left).max(0)
861}
862
863/// `1h 2m`, `3m 12s` or `40s`.
864fn duration(seconds: i64) -> String {
865 let (h, m, s) = (seconds / 3600, seconds % 3600 / 60, seconds % 60);
866 if h > 0 {
867 format!("{h}h {m}m")
868 } else if m > 0 {
869 format!("{m}m {s}s")
870 } else {
871 format!("{s}s")
872 }
873}
874
Billing accounts, terms and enterprises; g1t is no longer free875impl Billing {
876 /// What a workspace is charged for something that would be `base`:
877 /// nothing while g1t is free, or as its account's terms say. With a
878 /// note for the statement when it differs.
879 pub(crate) async fn charged(&self, workspace: &str, base: i64) -> Result<(i64, String)> {
880 if self.free {
881 return Ok((0, " (free while g1t is being built out)".to_owned()));
882 }
883 let terms = self.terms_of(workspace).await?;
884 let charge = terms.apply(base);
885 let note = match terms.kind {
886 TermsKind::Comped => " (comped)".to_owned(),
887 TermsKind::Custom if terms.discount_percent > 0 && base > 0 => format!(" ({}% off)", terms.discount_percent),
888 _ => String::new(),
889 };
890 Ok((charge, note))
891 }
892}
893
Agents as a team: lifecycle, merge queue, billing and a new shell894fn members_only<T>() -> Outcome<T> {
895 Outcome::fail(
896 FailureCode::Forbidden,
897 "Only members can see a workspace's billing.",
898 )
899}
900
Prices keep themselves current with what g1t pays901impl Billing {
902 fn from_env(env: &Env) -> Result<Self> {
903 Ok(Billing {
904 db: env.d1("DB")?,
905 stripe: env
906 .secret("STRIPE_SECRET_KEY")
907 .ok()
908 .map(|key| key.to_string())
909 .filter(|key| !key.is_empty())
910 .map(Stripe::new),
911 margin_percent: env
912 .var("MARGIN_PERCENT")
913 .ok()
914 .and_then(|percent| percent.to_string().parse().ok())
915 .unwrap_or(20),
916 orchestration_fee_micros: env
917 .var("ORCHESTRATION_FEE_MICROS")
918 .ok()
919 .and_then(|fee| fee.to_string().parse().ok())
920 .unwrap_or(100_000),
921 free: env.var("FREE_WHILE_BUILDING").is_ok_and(|v| v.to_string() == "true"),
922 ceilings: limits::Ceilings::from_env(&env),
Billing accounts, terms and enterprises; g1t is no longer free923 prepaid_only: env.var("PREPAID_ONLY").is_ok_and(|v| v.to_string() == "true"),
Prices keep themselves current with what g1t pays924 deployments_monthly_cents: env
925 .var("DEPLOYMENTS_MONTHLY_CENTS")
926 .ok()
927 .and_then(|cents| cents.to_string().parse().ok())
928 .unwrap_or(500),
929 trial: {
930 let number = |name: &str| env.var(name).ok().and_then(|v| v.to_string().parse::<i64>().ok());
931 match (
932 number("TRIAL_WORKSPACE_MICROS"),
933 number("TRIAL_TOTAL_MICROS"),
934 env.var("TRIAL_UNTIL").ok().map(|v| v.to_string()),
935 ) {
936 (Some(per_workspace_micros), Some(total_micros), Some(until))
937 if per_workspace_micros > 0 && !until.is_empty() =>
938 {
939 Some(TrialConfig {
940 per_workspace_micros,
941 total_micros,
942 until,
943 })
944 }
945 _ => None,
946 }
947 },
948 })
949 }
950}
951
952#[event(scheduled)]
953async fn scheduled(event: ScheduledEvent, env: Env, _ctx: ScheduleContext) {
954 let Ok(billing) = Billing::from_env(&env) else {
955 return;
956 };
957 let keeper = keeper::Keeper::from_env(&env);
958 if let Err(error) = billing.settle_runs(&keeper).await {
959 worker::console_error!("settling runs failed: {error}");
960 }
Billing accounts, terms and enterprises; g1t is no longer free961 if let Err(error) = billing.autopay().await {
962 worker::console_error!("paying at the limit failed: {error}");
963 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace964 if let Err(error) = billing.close_months().await {
965 worker::console_error!("closing the month failed: {error}");
966 }
Stripe webhooks, enterprise invoices, and sudo for both967 if let Err(error) = billing.invoice_enterprises().await {
968 worker::console_error!("invoicing enterprises failed: {error}");
969 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace970 if let Ok(identity) = env.service("IDENTITY") {
971 if let Err(error) = billing.warn_limits(&identity).await {
972 worker::console_error!("warning owners failed: {error}");
973 }
974 }
The keeper reads Cloudflare as it really answers975 // Once a day, and at once if the costs were never checked: check every
976 // cost against what Cloudflare billed.
977 if event.cron() == keeper::DAILY || billing.never_checked().await.unwrap_or(false) {
Prices keep themselves current with what g1t pays978 if let Err(error) = billing.reconcile(&keeper).await {
979 worker::console_error!("checking costs against Cloudflare failed: {error}");
980 }
981 }
982}
983
Agents as a team: lifecycle, merge queue, billing and a new shell984#[event(fetch)]
985async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> {
986 let Some(method) = rpc_method(&request) else {
987 return Response::error("Not found", 404);
988 };
989 let body: serde_json::Value = request.json().await?;
Prices keep themselves current with what g1t pays990 let billing = Billing::from_env(&env)?;
Agents as a team: lifecycle, merge queue, billing and a new shell991 match method.as_str() {
992 "status" => reply(&billing.status()),
993 "account" => reply(&billing.account(args(body)?).await?),
994 "ledger" => reply(&billing.ledger(args(body)?).await?),
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request995 "usage" => reply(&billing.usage(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell996 "checkout" => reply(&billing.checkout(args(body)?).await?),
997 "confirm" => reply(&billing.confirm(args(body)?).await?),
998 "can_start" => reply(&billing.can_start(args(body)?).await?),
A free allowance on g1t's models, so anyone can try its agents999 "trial" => reply(&billing.trial(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1000 "start_run" => reply(&billing.start_run(args(body)?).await?),
1001 "finish_run" => reply(&billing.finish_run(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan1002 "features" => reply(&billing.features(args(body)?).await?),
1003 "subscribe" => reply(&billing.subscribe(args(body)?).await?),
1004 "confirm_subscription" => reply(&billing.confirm_subscription(args(body)?).await?),
1005 "cancel_subscription" => reply(&billing.cancel_subscription(args(body)?).await?),
1006 "has_feature" => reply(&billing.has_feature(args(body)?).await?),
1007 "charge_feature" => reply(&billing.charge_feature(args(body)?).await?),
Every sandbox is metered by the second1008 "record_sandbox" => reply(&billing.record_sandbox(args(body)?).await?),
Usage limits: unpaid usage can only go so far1009 "limit" => reply(&billing.limit(args(body)?).await?),
1010 "check_limit" => reply(&billing.check_limit(args(body)?).await?),
1011 "set_spend_limit" => reply(&billing.set_spend_limit(args(body)?).await?),
Prices keep themselves current with what g1t pays1012 "prices" => reply(&billing.prices().await?),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1013 "billing_portal" => reply(&billing.billing_portal(args(body)?).await?),
1014 "admin_billing_link" => reply(&billing.admin_billing_link(args(body)?).await?),
Stripe webhooks, enterprise invoices, and sudo for both1015 "admin_stripe" => reply(&billing.admin_stripe(args(body)?).await?),
1016 "admin_enterprise_billing" => reply(&billing.admin_enterprise_billing(args(body)?).await?),
1017 "admin_invoice_enterprise" => reply(&billing.admin_invoice_enterprise(args(body)?).await?),
1018 "stripe_webhook" => reply(&billing.stripe_webhook(args(body)?).await?),
Prices keep themselves current with what g1t pays1019 "note_pending" => reply(&billing.note_pending(args(body)?).await?),
Billing accounts, terms and enterprises; g1t is no longer free1020 "admin_accounts" => reply(&billing.admin_accounts(args(body)?).await?),
1021 "admin_account" => reply(&billing.admin_account(args(body)?).await?),
1022 "admin_set_terms" => reply(&billing.admin_set_terms(args(body)?).await?),
1023 "admin_create_enterprise" => reply(&billing.admin_create_enterprise(args(body)?).await?),
1024 "admin_attach" => reply(&billing.admin_attach(args(body)?).await?),
1025 "admin_credit" => reply(&billing.admin_credit(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1026 _ => Response::error("Unknown method", 404),
1027 }
1028}
1029
1030#[cfg(test)]
1031mod tests {
1032 use super::*;
1033
1034 #[test]
1035 fn a_run_is_charged_its_cost_plus_the_margin() {
1036 // $0.05 at 20% is six cents.
1037 assert_eq!(charge_micros(0.05, 20), 60_000);
1038 assert_eq!(charge_micros(1.0, 20), 1_200_000);
1039 assert_eq!(charge_micros(0.05, 0), 50_000);
1040 }
1041
1042 #[test]
1043 fn fractions_of_a_millionth_round_up_and_nothing_costs_less_than_nothing() {
1044 assert_eq!(charge_micros(0.000_000_4, 20), 2);
1045 assert_eq!(charge_micros(0.0, 20), 0);
1046 assert_eq!(charge_micros(-3.0, 20), 0);
1047 }
1048
1049 #[test]
Every sandbox is metered by the second1050 fn sandbox_seconds_are_charged_only_past_the_free_minutes() {
1051 let free = sandbox_allowance::FREE_SECONDS;
1052 assert_eq!(sandbox_billable(0, 600), 0);
1053 assert_eq!(sandbox_billable(free - 100, 600), 500);
1054 assert_eq!(sandbox_billable(free + 5, 600), 600);
1055 }
1056
1057 #[test]
1058 fn durations_read_plainly() {
1059 assert_eq!(duration(40), "40s");
1060 assert_eq!(duration(192), "3m 12s");
1061 assert_eq!(duration(3720), "1h 2m");
1062 }
1063
1064 #[test]
Agents as a team: lifecycle, merge queue, billing and a new shell1065 fn an_absurd_cost_is_capped() {
1066 assert_eq!(charge_micros(1e9, 20), 120 * MICROS_PER_DOLLAR);
1067 }
1068}