flagon-io/g1t

public

Git for AI scale: a forge for thousands of agents working on the same code at once.

g1t/services/billing/src/lib.rs

1,096 lines43,631 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;
Two limits, real invoices, trust that grows by itself, sales signals20mod invoices;
21mod sales;
Stripe webhooks, enterprise invoices, and sudo for both22mod webhooks;
Paid features: a workspace turns on Deployments with a monthly plan23mod features;
Prices keep themselves current with what g1t pays24mod keeper;
Usage limits: unpaid usage can only go so far25mod limits;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains26mod rename;
Agents as a team: lifecycle, merge queue, billing and a new shell27mod stripe;
28
29use g1t_contracts::billing::*;
30use g1t_contracts::time::rfc3339;
31use g1t_contracts::{FailureCode, Outcome, Role, new_id};
Billing accounts, terms and enterprises; g1t is no longer free32use g1t_contracts::billing::TermsKind;
Agents as a team: lifecycle, merge queue, billing and a new shell33use g1t_kit::{args, now_ms, reply, rpc_method};
34use serde::Deserialize;
35use sha2::{Digest, Sha256};
36use worker::wasm_bindgen::JsValue;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains37use worker::{Context, D1Database, Env, MessageBatch, MessageExt, Request, Response, Result, ScheduleContext, ScheduledEvent, event};
Agents as a team: lifecycle, merge queue, billing and a new shell38
39use stripe::Stripe;
40
41const MIN_TOP_UP_CENTS: u32 = 500;
42const MAX_TOP_UP_CENTS: u32 = 50_000;
43const LEDGER_PAGE: u32 = 100;
44/// A run's reported cost is believed up to this much. A sandbox cannot
45/// spend more in the time it has, so anything above is a fault.
46const MAX_RUN_COST_USD: f64 = 100.0;
47
48/// What a run is charged: its cost plus the margin, rounded up to a whole
49/// millionth of a dollar.
50pub fn charge_micros(cost_usd: f64, margin_percent: u32) -> i64 {
51 let cost_micros = (cost_usd.clamp(0.0, MAX_RUN_COST_USD) * MICROS_PER_DOLLAR as f64).ceil();
52 (cost_micros * f64::from(100 + margin_percent) / 100.0).ceil() as i64
53}
54
55fn hash(token: &str) -> String {
56 hex::encode(Sha256::digest(token.as_bytes()))
57}
58
59fn optional(value: Option<&str>) -> JsValue {
60 value.map_or(JsValue::NULL, JsValue::from)
61}
62
63#[derive(Deserialize)]
64struct AccountRow {
65 balance_micros: i64,
66 customer_id: Option<String>,
67}
68
69#[derive(Deserialize)]
70struct LedgerRow {
71 id: String,
72 kind: EntryKind,
73 amount_micros: i64,
74 description: String,
75 repo: Option<String>,
76 number: Option<u32>,
77 task: Option<String>,
78 model: Option<String>,
79 created_by: Option<String>,
80 created_at: String,
Integrations: your own model provider, alerts that open issues, tickets agents read81 billed_to: Option<String>,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace82 #[serde(default)]
83 workspace: Option<String>,
Agents as a team: lifecycle, merge queue, billing and a new shell84}
85
86impl From<LedgerRow> for LedgerEntry {
87 fn from(row: LedgerRow) -> Self {
88 LedgerEntry {
89 id: row.id,
90 kind: row.kind,
91 amount_micros: row.amount_micros,
92 description: row.description,
93 repo: row.repo,
94 number: row.number,
95 task: row.task,
96 model: row.model,
Integrations: your own model provider, alerts that open issues, tickets agents read97 billed_to: row.billed_to.unwrap_or_else(|| "g1t".to_owned()),
Agents as a team: lifecycle, merge queue, billing and a new shell98 created_by: row.created_by,
99 created_at: row.created_at,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace100 workspace: row.workspace,
Agents as a team: lifecycle, merge queue, billing and a new shell101 }
102 }
103}
104
105#[derive(Deserialize)]
106struct RunRow {
107 workspace: String,
108 repo: String,
109 number: u32,
110 task: String,
111 model: String,
112 token_hash: String,
Integrations: your own model provider, alerts that open issues, tickets agents read113 billed_to: Option<String>,
114}
115
116impl RunRow {
117 fn own_provider(&self) -> bool {
118 self.billed_to.as_deref() == Some("workspace")
119 }
Agents as a team: lifecycle, merge queue, billing and a new shell120}
121
122#[derive(Deserialize)]
123struct CheckoutRow {
124 workspace: String,
125 created_by: String,
126}
127
128/// A row an `UPDATE … RETURNING` touched.
129#[derive(Deserialize)]
130struct Touched {
131 #[allow(dead_code)]
132 id: String,
133}
134
135struct Billing {
136 db: D1Database,
137 /// Absent when no card processor is configured.
138 stripe: Option<Stripe>,
139 margin_percent: u32,
Integrations: your own model provider, alerts that open issues, tickets agents read140 /// Charged for a run on the workspace's own model provider.
141 orchestration_fee_micros: i64,
Free while g1t is being built out; agents can check out their own forks142 /// While g1t is being built out, nothing is charged (`FREE_WHILE_BUILDING`).
143 free: bool,
A free allowance on g1t's models, so anyone can try its agents144 /// The free allowance on g1t's hosted models, when there is one.
145 trial: Option<TrialConfig>,
Paid features: a workspace turns on Deployments with a monthly plan146 /// The Deployments plan's monthly price (`DEPLOYMENTS_MONTHLY_CENTS`).
147 deployments_monthly_cents: u32,
Usage limits: unpaid usage can only go so far148 /// How far unpaid usage may go; see `limits`.
149 ceilings: limits::Ceilings,
Billing accounts, terms and enterprises; g1t is no longer free150 /// `PREPAID_ONLY`: the old rule, that agents need credit first.
151 prepaid_only: bool,
A free allowance on g1t's models, so anyone can try its agents152}
153
154/// `TRIAL_WORKSPACE_MICROS`, `TRIAL_TOTAL_MICROS` and `TRIAL_UNTIL`.
155struct TrialConfig {
156 per_workspace_micros: i64,
157 total_micros: i64,
158 /// RFC 3339, in UTC.
159 until: String,
160}
161
162#[derive(serde::Deserialize)]
163struct Sum {
164 micros: Option<i64>,
Agents as a team: lifecycle, merge queue, billing and a new shell165}
166
167impl Billing {
168 fn status(&self) -> Status {
169 Status {
170 enabled: self.stripe.is_some(),
171 live: self.stripe.as_ref().is_some_and(Stripe::live),
Free while g1t is being built out; agents can check out their own forks172 free: self.free,
Agents as a team: lifecycle, merge queue, billing and a new shell173 }
174 }
175
176 async fn row(&self, workspace: &str) -> Result<Option<AccountRow>> {
177 self.db
178 .prepare("SELECT balance_micros, customer_id FROM accounts WHERE workspace = ?")
179 .bind(&[workspace.into()])?
180 .first::<AccountRow>(None)
181 .await
182 }
183
184 async fn standing(&self, workspace: &str) -> Result<Account> {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace185 let row = self.row(workspace).await?;
186 let card = match (&self.stripe, row.as_ref().and_then(|row| row.customer_id.as_deref())) {
187 (Some(stripe), Some(customer)) => stripe.card(customer).await.ok().flatten().map(|card| Card {
188 brand: card.brand,
189 last4: card.last4,
190 exp_month: card.exp_month,
191 exp_year: card.exp_year,
192 }),
193 _ => None,
194 };
Agents as a team: lifecycle, merge queue, billing and a new shell195 Ok(Account {
196 workspace: workspace.to_owned(),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace197 balance_micros: row.map_or(0, |row| row.balance_micros),
Agents as a team: lifecycle, merge queue, billing and a new shell198 status: self.status(),
199 margin_percent: self.margin_percent,
Integrations: your own model provider, alerts that open issues, tickets agents read200 orchestration_fee_micros: self.orchestration_fee_micros,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace201 card,
Agents as a team: lifecycle, merge queue, billing and a new shell202 })
203 }
204
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace205 /// The workspace's customer at Stripe, made the first time one is needed.
206 pub(crate) async fn customer_for(&self, workspace: &str) -> Result<String> {
207 let Some(stripe) = &self.stripe else {
208 return Err(worker::Error::RustError("payments are not set up".into()));
209 };
210 if let Some(customer) = self.row(workspace).await?.and_then(|row| row.customer_id) {
211 return Ok(customer);
212 }
213 let customer = stripe.create_customer(workspace).await?;
214 self.db
215 .prepare(
216 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at) VALUES (?1, 0, ?2, ?3)
217 ON CONFLICT (workspace) DO UPDATE SET customer_id = ?2",
218 )
219 .bind(&[workspace.into(), customer.as_str().into(), rfc3339(now_ms()).into()])?
220 .run()
221 .await?;
222 Ok(customer)
223 }
224
225 /// Stripe's hosted billing page for the workspace. Owners only.
226 async fn billing_portal(&self, a: BillingPortalArgs) -> Result<Outcome<Checkout>> {
227 let workspace = a.workspace.to_lowercase();
228 if a.actor.role_in(&workspace) != Some(Role::Owner) {
229 return Ok(Outcome::fail(FailureCode::Forbidden, "Only an owner can manage the workspace's billing."));
230 }
231 let Some(stripe) = &self.stripe else {
232 return Ok(Outcome::fail(FailureCode::Conflict, "Payments are not set up on this g1t."));
233 };
234 let customer = match self.customer_for(&workspace).await {
235 Ok(customer) => customer,
236 Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe could not be reached: {error}"))),
237 };
238 match stripe.portal_session(&customer, &a.return_url).await {
239 Ok(url) => Ok(Outcome::Ok(Checkout { url })),
240 Err(error) if stripe::is_missing(&error) => {
241 // The customer was removed at Stripe: a new one next time.
242 self.forget_customer(&workspace).await?;
243 Ok(Outcome::fail(FailureCode::Conflict, "Stripe no longer had this workspace's customer. Try again."))
244 }
245 Err(error) => Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe's billing page could not be opened: {error}"))),
246 }
247 }
248
Agents as a team: lifecycle, merge queue, billing and a new shell249 /// Adds a ledger entry and moves the balance by the same amount, as
250 /// one write.
251 #[allow(clippy::too_many_arguments)]
252 async fn enter(
253 &self,
254 workspace: &str,
255 kind: EntryKind,
256 amount_micros: i64,
257 description: &str,
258 reference: &str,
259 run: Option<&RunRow>,
260 cost_micros: Option<i64>,
261 created_by: Option<&str>,
262 customer: Option<&str>,
263 ) -> Result<()> {
264 let now = now_ms();
265 let timestamp = rfc3339(now);
266 let kind = match kind {
267 EntryKind::TopUp => "top_up",
268 EntryKind::Usage => "usage",
269 };
270 self.db
271 .batch(vec![
272 self.db
273 .prepare(
274 "INSERT INTO ledger
275 (id, workspace, kind, amount_micros, description, repo, number, task,
Integrations: your own model provider, alerts that open issues, tickets agents read276 model, cost_micros, reference, created_by, created_at, billed_to)
277 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
Agents as a team: lifecycle, merge queue, billing and a new shell278 )
279 .bind(&[
280 new_id("led", now).into(),
281 workspace.into(),
282 kind.into(),
283 // D1 takes numbers as doubles, which hold every
284 // amount this service will see exactly.
285 (amount_micros as f64).into(),
286 description.into(),
287 optional(run.map(|run| run.repo.as_str())),
288 run.map_or(JsValue::NULL, |run| run.number.into()),
289 optional(run.map(|run| run.task.as_str())),
290 optional(run.map(|run| run.model.as_str())),
291 cost_micros.map_or(JsValue::NULL, |cost| (cost as f64).into()),
292 reference.into(),
293 optional(created_by),
294 timestamp.as_str().into(),
Integrations: your own model provider, alerts that open issues, tickets agents read295 run.map_or("g1t", |run| if run.own_provider() { "workspace" } else { "g1t" }).into(),
Agents as a team: lifecycle, merge queue, billing and a new shell296 ])?,
297 self.db
298 .prepare(
299 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at)
300 VALUES (?1, ?2, ?3, ?4)
301 ON CONFLICT (workspace) DO UPDATE SET
302 balance_micros = balance_micros + ?2,
303 customer_id = COALESCE(?3, customer_id)",
304 )
305 .bind(&[
306 workspace.into(),
307 (amount_micros as f64).into(),
308 optional(customer),
309 timestamp.as_str().into(),
310 ])?,
311 ])
312 .await?;
Billing accounts, terms and enterprises; g1t is no longer free313 // Money in clears a card declined at the limit.
314 if kind == "top_up" {
315 self.db
316 .prepare("UPDATE limits SET autopay_failed_at = NULL, autopay_error = NULL WHERE workspace = ?")
317 .bind(&[workspace.into()])?
318 .run()
319 .await?;
320 }
Agents as a team: lifecycle, merge queue, billing and a new shell321 Ok(())
322 }
323
324 async fn account(&self, a: AccountArgs) -> Result<Outcome<Account>> {
325 let workspace = a.workspace.to_lowercase();
326 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
327 return Ok(members_only());
328 }
329 Ok(Outcome::Ok(self.standing(&workspace).await?))
330 }
331
332 async fn ledger(&self, a: AccountArgs) -> Result<Outcome<Vec<LedgerEntry>>> {
333 let workspace = a.workspace.to_lowercase();
334 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
335 return Ok(members_only());
336 }
337 let rows = self
338 .db
339 .prepare("SELECT * FROM ledger WHERE workspace = ? ORDER BY id DESC LIMIT ?")
340 .bind(&[workspace.into(), LEDGER_PAGE.into()])?
341 .all()
342 .await?
343 .results::<LedgerRow>()?;
344 Ok(Outcome::Ok(
345 rows.into_iter().map(LedgerEntry::from).collect(),
346 ))
347 }
348
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request349 async fn usage(&self, a: UsageArgs) -> Result<Outcome<Usage>> {
350 let workspace = a.workspace.to_lowercase();
351 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
352 return Ok(members_only());
353 }
354 #[derive(serde::Deserialize)]
355 struct SliceRow {
356 key: Option<String>,
357 micros: Option<i64>,
358 runs: Option<u32>,
359 }
Usage while free is shown at cost; agents get rustfmt and clippy360 // While nothing is charged, what was used is what there is to show.
361 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 request362 let slices = |key: &str, limit: u32| {
363 format!(
Usage while free is shown at cost; agents get rustfmt and clippy364 "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 request365 WHERE workspace = ?1 AND kind = 'usage' AND created_at >= ?2
366 GROUP BY 1 ORDER BY micros DESC LIMIT {limit}"
367 )
368 };
369 let query = |sql: String| {
370 let db = &self.db;
371 let workspace = workspace.clone();
372 let since = a.since.clone();
373 async move {
374 let rows = db
375 .prepare(sql)
376 .bind(&[workspace.into(), since.into()])?
377 .all()
378 .await?
379 .results::<SliceRow>()?;
380 Ok::<Vec<UsageSlice>, worker::Error>(
381 rows.into_iter()
382 .map(|row| UsageSlice {
383 key: row.key.unwrap_or_else(|| "other".to_owned()),
384 micros: row.micros.unwrap_or_default(),
385 runs: row.runs.unwrap_or_default(),
386 })
387 .collect(),
388 )
389 }
390 };
391 #[derive(serde::Deserialize)]
392 struct Totals {
393 spent: Option<i64>,
394 cost: Option<i64>,
Integrations: your own model provider, alerts that open issues, tickets agents read395 provider: Option<i64>,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request396 runs: Option<u32>,
397 added: Option<i64>,
398 }
399 let totals = self
400 .db
401 .prepare(
402 "SELECT
403 -SUM(CASE WHEN kind = 'usage' THEN amount_micros END) AS spent,
Integrations: your own model provider, alerts that open issues, tickets agents read404 SUM(CASE WHEN kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' THEN cost_micros END) AS cost,
405 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 request406 SUM(CASE WHEN kind = 'usage' THEN 1 ELSE 0 END) AS runs,
407 SUM(CASE WHEN kind = 'top_up' THEN amount_micros END) AS added
408 FROM ledger WHERE workspace = ?1 AND created_at >= ?2",
409 )
410 .bind(&[workspace.as_str().into(), a.since.as_str().into()])?
411 .first::<Totals>(None)
412 .await?;
413 let totals = totals.unwrap_or(Totals {
414 spent: None,
415 cost: None,
Integrations: your own model provider, alerts that open issues, tickets agents read416 provider: None,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request417 runs: None,
418 added: None,
419 });
420 Ok(Outcome::Ok(Usage {
421 spent_micros: totals.spent.unwrap_or_default(),
422 cost_micros: totals.cost.unwrap_or_default(),
Integrations: your own model provider, alerts that open issues, tickets agents read423 provider_micros: totals.provider.unwrap_or_default(),
Usage while free is shown at cost; agents get rustfmt and clippy424 used_micros: totals.cost.unwrap_or_default() + totals.provider.unwrap_or_default(),
425 free: self.free,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request426 runs: totals.runs.unwrap_or_default(),
427 added_micros: totals.added.unwrap_or_default(),
428 by_day: query(slices("substr(created_at, 1, 10) || '/' || COALESCE(task, 'other')", 400)).await?,
429 by_task: query(slices("task", 20)).await?,
430 by_repo: query(slices("repo", 20)).await?,
431 by_pull: query(slices("repo || '#' || number", 10)).await?,
432 by_model: query(slices("model", 10)).await?,
433 since: a.since,
434 }))
435 }
436
Agents as a team: lifecycle, merge queue, billing and a new shell437 async fn checkout(&self, a: CheckoutArgs) -> Result<Outcome<Checkout>> {
438 let workspace = a.workspace.to_lowercase();
439 if a.actor.role_in(&workspace) != Some(Role::Owner) {
440 return Ok(Outcome::fail(
441 FailureCode::Forbidden,
442 "Only an owner can add credit to a workspace.",
443 ));
444 }
445 let Some(stripe) = &self.stripe else {
446 return Ok(Outcome::fail(
447 FailureCode::Conflict,
448 "Payments are not set up on this g1t yet.",
449 ));
450 };
451 if !(MIN_TOP_UP_CENTS..=MAX_TOP_UP_CENTS).contains(&a.amount_cents) {
452 return Ok(Outcome::fail(
453 FailureCode::Invalid,
454 format!(
455 "Add between ${} and ${} at a time.",
456 MIN_TOP_UP_CENTS / 100,
457 MAX_TOP_UP_CENTS / 100
458 ),
459 ));
460 }
461 let customer = self.row(&workspace).await?.and_then(|row| row.customer_id);
Project dependencies: addresses, preview stacks, Affects, and agents who know462 let session = match stripe
463 .start_checkout(&workspace, a.amount_cents, customer.as_deref(), &a.return_url)
464 .await
465 {
466 Ok(session) => session,
467 // A customer saved under another Stripe account: start afresh.
468 Err(error) if customer.is_some() && stripe::is_missing(&error) => {
469 self.forget_customer(&workspace).await?;
470 stripe.start_checkout(&workspace, a.amount_cents, None, &a.return_url).await?
471 }
472 Err(error) => return Err(error),
473 };
Agents as a team: lifecycle, merge queue, billing and a new shell474 let Some(url) = session.url else {
475 return Err(worker::Error::RustError(
476 "the card processor returned no payment page".into(),
477 ));
478 };
479 self.db
480 .prepare(
481 "INSERT INTO checkouts (id, workspace, amount_cents, created_by, created_at)
482 VALUES (?, ?, ?, ?, ?)",
483 )
484 .bind(&[
485 session.id.into(),
486 workspace.into(),
487 a.amount_cents.into(),
488 a.actor.username.into(),
489 rfc3339(now_ms()).into(),
490 ])?
491 .run()
492 .await?;
493 Ok(Outcome::Ok(Checkout { url }))
494 }
495
496 /// Credits a payment if the processor says it was made and it has not
497 /// been credited before. The amount credited is what the processor
498 /// says was paid, not what anyone here remembers asking for.
499 async fn confirm(&self, a: ConfirmArgs) -> Result<Outcome<Account>> {
500 let workspace = a.workspace.to_lowercase();
501 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
502 return Ok(members_only());
503 }
504 let (Some(stripe), Some(checkout)) = (
505 &self.stripe,
506 self.db
507 .prepare(
508 "SELECT workspace, created_by FROM checkouts
509 WHERE id = ? AND workspace = ? AND status = 'open'",
510 )
511 .bind(&[a.session.as_str().into(), workspace.as_str().into()])?
512 .first::<CheckoutRow>(None)
513 .await?,
514 ) else {
515 // Unknown, someone else's, or already credited: nothing to do.
516 return Ok(Outcome::Ok(self.standing(&workspace).await?));
517 };
518 let session = stripe.session(&a.session).await?;
519 let paid = session
520 .amount_total
521 .filter(|_| session.payment_status == "paid");
522 if let Some(cents) = paid {
523 // Only whoever flips it from open to paid enters the credit.
524 let claimed = self
525 .db
526 .prepare(
527 "UPDATE checkouts SET status = 'paid' WHERE id = ? AND status = 'open'
528 RETURNING id",
529 )
530 .bind(&[a.session.as_str().into()])?
531 .first::<Touched>(None)
532 .await?;
533 if claimed.is_some() {
534 self.enter(
535 &checkout.workspace,
536 EntryKind::TopUp,
537 i64::from(cents) * MICROS_PER_DOLLAR / 100,
538 "Credit added by card",
539 &session.id,
540 None,
541 None,
542 Some(&checkout.created_by),
543 session.customer.as_deref(),
544 )
545 .await?;
546 }
547 }
548 Ok(Outcome::Ok(self.standing(&workspace).await?))
549 }
550
Project dependencies: addresses, preview stacks, Affects, and agents who know551 /// Drops a saved customer the card processor no longer knows.
552 pub(crate) async fn forget_customer(&self, workspace: &str) -> Result<()> {
553 self.db
554 .prepare("UPDATE accounts SET customer_id = NULL WHERE workspace = ?")
555 .bind(&[workspace.into()])?
556 .run()
557 .await?;
558 Ok(())
559 }
560
Agents as a team: lifecycle, merge queue, billing and a new shell561 /// A refusal if the workspace has no credit to start an agent with.
562 async fn out_of_credit<T>(&self, workspace: &str) -> Result<Option<Outcome<T>>> {
Billing accounts, terms and enterprises; g1t is no longer free563 // Billing is postpaid: usage limits decide whether work starts
564 // (see `limits`), and credit is a prepayment that lowers what is
565 // owed. A balance no longer has to be positive to start.
566 if self.free || !self.prepaid_only {
Free while g1t is being built out; agents can check out their own forks567 return Ok(None);
568 }
Agents as a team: lifecycle, merge queue, billing and a new shell569 let balance = self
570 .row(workspace)
571 .await?
572 .map_or(0, |row| row.balance_micros);
573 Ok((balance <= 0).then(|| {
574 Outcome::fail(
575 FailureCode::PaymentRequired,
576 format!(
577 "The {workspace} workspace has no agent credit. An owner can add some under Billing on the workspace's page."
578 ),
579 )
580 }))
581 }
582
A free allowance on g1t's models, so anyone can try its agents583 /// A workspace's free allowance on g1t's hosted models: what its runs
584 /// there have cost against its share, and the pool everyone draws on.
Billing accounts, terms and enterprises; g1t is no longer free585 /// How much of a hosted model run's cost the workspace's free allowance
586 /// covers, if it is still open.
587 async fn trial_covers(&self, workspace: &str, cost_micros: i64) -> Result<i64> {
588 let trial = self.trial(TrialArgs { workspace: workspace.to_owned(), exempt: vec![] }).await?;
589 if !trial.open {
590 return Ok(0);
591 }
592 Ok(cost_micros.min((trial.limit_micros - trial.used_micros).max(0)))
593 }
594
A free allowance on g1t's models, so anyone can try its agents595 async fn trial(&self, a: TrialArgs) -> Result<Trial> {
596 let workspace = a.workspace.to_lowercase();
597 let Some(config) = &self.trial else {
598 return Ok(Trial {
599 open: false,
600 used_micros: 0,
601 limit_micros: 0,
602 ends_at: None,
603 reason: Some("off".to_owned()),
604 });
605 };
606 let used = self
607 .db
608 .prepare(
609 "SELECT SUM(cost_micros) AS micros FROM ledger
Billing accounts, terms and enterprises; g1t is no longer free610 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 agents611 )
612 .bind(&[workspace.as_str().into()])?
613 .first::<Sum>(None)
614 .await?
615 .and_then(|sum| sum.micros)
616 .unwrap_or_default();
617 // Everyone's, but for the workspaces open to hosted models anyway.
618 let exempt: Vec<String> = a.exempt.iter().map(|name| name.trim().to_lowercase()).collect();
619 let marks = vec!["?"; exempt.len().max(1)].join(", ");
620 let mut values: Vec<JsValue> = exempt.iter().map(|name| JsValue::from(name.as_str())).collect();
621 if values.is_empty() {
622 values.push(JsValue::from(""));
623 }
624 let pooled = self
625 .db
626 .prepare(format!(
627 "SELECT SUM(cost_micros) AS micros FROM ledger
Billing accounts, terms and enterprises; g1t is no longer free628 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 agents629 ))
630 .bind(&values)?
631 .first::<Sum>(None)
632 .await?
633 .and_then(|sum| sum.micros)
634 .unwrap_or_default();
635 let reason = if rfc3339(now_ms()) >= config.until {
636 Some("ended")
637 } else if used >= config.per_workspace_micros {
638 Some("used")
639 } else if pooled >= config.total_micros {
640 Some("pool")
641 } else {
642 None
643 };
644 Ok(Trial {
645 open: reason.is_none(),
646 used_micros: used,
647 limit_micros: config.per_workspace_micros,
648 ends_at: Some(config.until.clone()),
649 reason: reason.map(str::to_owned),
650 })
651 }
652
Agents as a team: lifecycle, merge queue, billing and a new shell653 async fn can_start(&self, a: CanStartArgs) -> Result<Outcome<bool>> {
654 if self.stripe.is_none() {
655 return Ok(Outcome::Ok(true));
656 }
Usage limits: unpaid usage can only go so far657 if let Some(stopped) = self.stopped(&a.workspace).await? {
658 return Ok(stopped);
659 }
Agents as a team: lifecycle, merge queue, billing and a new shell660 Ok(self
661 .out_of_credit(&a.workspace.to_lowercase())
662 .await?
663 .unwrap_or(Outcome::Ok(true)))
664 }
665
666 async fn start_run(&self, a: StartRunArgs) -> Result<Outcome<Option<RunTicket>>> {
667 if self.stripe.is_none() {
668 return Ok(Outcome::Ok(None));
669 }
670 let workspace = a.workspace.to_lowercase();
Usage limits: unpaid usage can only go so far671 if let Some(stopped) = self.stopped(&workspace).await? {
672 return Ok(stopped);
673 }
Agents as a team: lifecycle, merge queue, billing and a new shell674 if let Some(refused) = self.out_of_credit(&workspace).await? {
675 return Ok(refused);
676 }
677 let now = now_ms();
678 let run_id = new_id("run", now);
679 let mut bytes = [0u8; 32];
680 getrandom::getrandom(&mut bytes).expect("no source of randomness");
681 let token = hex::encode(bytes);
682 self.db
683 .prepare(
Prices keep themselves current with what g1t pays684 "INSERT INTO runs (id, workspace, repo, number, task, model, token_hash, created_at, billed_to, session_id)
685 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
Agents as a team: lifecycle, merge queue, billing and a new shell686 )
687 .bind(&[
688 run_id.as_str().into(),
689 workspace.into(),
690 format!("{}/{}", a.repo.namespace, a.repo.name).into(),
691 a.number.into(),
692 a.task.into(),
693 a.model.into(),
694 hash(&token).into(),
695 rfc3339(now).into(),
Integrations: your own model provider, alerts that open issues, tickets agents read696 if a.billed_to == "workspace" { "workspace" } else { "g1t" }.into(),
Prices keep themselves current with what g1t pays697 optional(a.session.as_deref().filter(|_| a.billed_to != "workspace")),
Agents as a team: lifecycle, merge queue, billing and a new shell698 ])?
699 .run()
700 .await?;
701 Ok(Outcome::Ok(Some(RunTicket { run_id, token })))
702 }
703
704 async fn finish_run(&self, a: FinishRunArgs) -> Result<Outcome<bool>> {
705 let run = self
706 .db
707 .prepare(
Integrations: your own model provider, alerts that open issues, tickets agents read708 "SELECT workspace, repo, number, task, model, token_hash, billed_to FROM runs
Agents as a team: lifecycle, merge queue, billing and a new shell709 WHERE id = ? AND finished_at IS NULL",
710 )
711 .bind(&[a.run_id.as_str().into()])?
712 .first::<RunRow>(None)
713 .await?;
714 let Some(run) = run.filter(|run| run.token_hash == hash(&a.token)) else {
715 return Ok(Outcome::fail(FailureCode::NotFound, "Run not found."));
716 };
717 if !a.cost_usd.is_finite() || a.cost_usd < 0.0 {
718 return Ok(Outcome::fail(FailureCode::Invalid, "That is not a cost."));
719 }
720 // Only whoever closes the run charges for it.
721 let claimed = self
722 .db
723 .prepare(
724 "UPDATE runs SET finished_at = ? WHERE id = ? AND finished_at IS NULL RETURNING id",
725 )
726 .bind(&[rfc3339(now_ms()).into(), a.run_id.as_str().into()])?
727 .first::<Touched>(None)
728 .await?;
729 if claimed.is_none() {
730 return Ok(Outcome::Ok(false));
731 }
Integrations: your own model provider, alerts that open issues, tickets agents read732 // On the workspace's own provider, the model was paid for there:
733 // g1t charges its fee, and keeps the provider's cost to show.
Billing accounts, terms and enterprises; g1t is no longer free734 let base = if run.own_provider() {
Integrations: your own model provider, alerts that open issues, tickets agents read735 self.orchestration_fee_micros
736 } else {
Billing accounts, terms and enterprises; g1t is no longer free737 // The free allowance on g1t's models covers what it can.
738 let cost = charge_micros(a.cost_usd, 0);
739 let covered = self.trial_covers(&run.workspace, cost).await?;
740 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 read741 };
Billing accounts, terms and enterprises; g1t is no longer free742 let (charge, terms_note) = self.charged(&run.workspace, base).await?;
Integrations: your own model provider, alerts that open issues, tickets agents read743 let mut description = match run.task.as_str() {
Agents as a team: lifecycle, merge queue, billing and a new shell744 "plan" => format!("Planning for {}", run.repo),
745 "review" => format!("Review of {}#{}", run.repo, run.number),
746 "update" => format!("Catching up {}#{}", run.repo, run.number),
747 _ => format!("Work on {}#{}", run.repo, run.number),
748 };
Integrations: your own model provider, alerts that open issues, tickets agents read749 if run.own_provider() {
750 description.push_str(", on your own model provider");
751 }
Billing accounts, terms and enterprises; g1t is no longer free752 description.push_str(&terms_note);
Agents as a team: lifecycle, merge queue, billing and a new shell753 self.enter(
754 &run.workspace,
755 EntryKind::Usage,
756 -charge,
757 &description,
758 &a.run_id,
759 Some(&run),
760 Some(charge_micros(a.cost_usd, 0)),
761 None,
762 None,
763 )
764 .await?;
765 Ok(Outcome::Ok(true))
766 }
767}
768
Every sandbox is metered by the second769impl Billing {
770 /// Records how long a sandbox ran: its cost always, and a charge for
771 /// the seconds past the month's free minutes.
772 async fn record_sandbox(&self, a: RecordSandboxArgs) -> Result<Outcome<bool>> {
773 if self.stripe.is_none() || a.seconds == 0 {
774 return Ok(Outcome::Ok(false));
775 }
776 let workspace = a.workspace.to_lowercase();
777 let seen = self
778 .db
779 .prepare("SELECT id FROM ledger WHERE reference = ?")
780 .bind(&[a.reference.as_str().into()])?
781 .first::<Touched>(None)
782 .await?;
783 if seen.is_some() {
784 return Ok(Outcome::Ok(false));
785 }
786 let now = now_ms();
787 let timestamp = rfc3339(now);
788 let month = &timestamp[..7];
789 #[derive(Deserialize)]
790 struct Used {
791 seconds: i64,
792 }
793 let seconds = i64::from(a.seconds);
794 let after = self
795 .db
796 .prepare(
797 "INSERT INTO sandbox_months (workspace, month, seconds) VALUES (?1, ?2, ?3)
798 ON CONFLICT (workspace, month) DO UPDATE SET seconds = seconds + ?3
799 RETURNING seconds",
800 )
801 .bind(&[workspace.as_str().into(), month.into(), (seconds as f64).into()])?
802 .first::<Used>(None)
803 .await?
804 .map_or(seconds, |used| used.seconds);
805 let billable = sandbox_billable(after - seconds, seconds);
Prices keep themselves current with what g1t pays806 // From the price book, which follows what Cloudflare bills g1t.
807 let (cost_per_second, price_per_second) = self.price("sandbox_second").await?.unwrap_or((
808 sandbox_allowance::COST_MICROS_PER_SECOND as f64,
809 sandbox_allowance::MICROS_PER_SECOND as f64,
810 ));
Billing accounts, terms and enterprises; g1t is no longer free811 let (charge, terms_note) = self.charged(&workspace, (billable as f64 * price_per_second).ceil() as i64).await?;
Every sandbox is metered by the second812 let mut description = format!("{}: {} of sandbox time", a.description, duration(seconds));
813 if billable < seconds {
814 description.push_str(if billable == 0 {
815 ", within the month's free minutes"
816 } else {
817 ", partly within the month's free minutes"
818 });
819 }
Billing accounts, terms and enterprises; g1t is no longer free820 if billable > 0 {
821 description.push_str(&terms_note);
Every sandbox is metered by the second822 }
823 self.db
824 .batch(vec![
825 self.db
826 .prepare(
827 "INSERT INTO ledger
828 (id, workspace, kind, amount_micros, description, repo, task,
829 cost_micros, reference, created_at, billed_to)
830 VALUES (?, ?, 'usage', ?, ?, ?, 'sandbox', ?, ?, ?, 'g1t')",
831 )
832 .bind(&[
833 new_id("led", now).into(),
834 workspace.as_str().into(),
835 (-(charge as f64)).into(),
836 description.as_str().into(),
837 optional(a.repo.as_deref()),
Prices keep themselves current with what g1t pays838 (seconds as f64 * cost_per_second).ceil().into(),
Every sandbox is metered by the second839 a.reference.as_str().into(),
840 timestamp.as_str().into(),
841 ])?,
842 self.db
843 .prepare(
844 "INSERT INTO accounts (workspace, balance_micros, created_at)
845 VALUES (?1, ?2, ?3)
846 ON CONFLICT (workspace) DO UPDATE SET balance_micros = balance_micros + ?2",
847 )
848 .bind(&[
849 workspace.as_str().into(),
850 (-(charge as f64)).into(),
851 timestamp.as_str().into(),
852 ])?,
853 ])
854 .await?;
855 Ok(Outcome::Ok(true))
856 }
857}
858
859/// Of `seconds` used after `before` this month, how many are past the
860/// free minutes.
861fn sandbox_billable(before: i64, seconds: i64) -> i64 {
862 let free_left = (sandbox_allowance::FREE_SECONDS - before).max(0);
863 (seconds - free_left).max(0)
864}
865
866/// `1h 2m`, `3m 12s` or `40s`.
867fn duration(seconds: i64) -> String {
868 let (h, m, s) = (seconds / 3600, seconds % 3600 / 60, seconds % 60);
869 if h > 0 {
870 format!("{h}h {m}m")
871 } else if m > 0 {
872 format!("{m}m {s}s")
873 } else {
874 format!("{s}s")
875 }
876}
877
Billing accounts, terms and enterprises; g1t is no longer free878impl Billing {
879 /// What a workspace is charged for something that would be `base`:
880 /// nothing while g1t is free, or as its account's terms say. With a
881 /// note for the statement when it differs.
882 pub(crate) async fn charged(&self, workspace: &str, base: i64) -> Result<(i64, String)> {
883 if self.free {
884 return Ok((0, " (free while g1t is being built out)".to_owned()));
885 }
886 let terms = self.terms_of(workspace).await?;
887 let charge = terms.apply(base);
888 let note = match terms.kind {
889 TermsKind::Comped => " (comped)".to_owned(),
890 TermsKind::Custom if terms.discount_percent > 0 && base > 0 => format!(" ({}% off)", terms.discount_percent),
891 _ => String::new(),
892 };
893 Ok((charge, note))
894 }
895}
896
Agents as a team: lifecycle, merge queue, billing and a new shell897fn members_only<T>() -> Outcome<T> {
898 Outcome::fail(
899 FailureCode::Forbidden,
900 "Only members can see a workspace's billing.",
901 )
902}
903
Prices keep themselves current with what g1t pays904impl Billing {
905 fn from_env(env: &Env) -> Result<Self> {
906 Ok(Billing {
907 db: env.d1("DB")?,
908 stripe: env
909 .secret("STRIPE_SECRET_KEY")
910 .ok()
911 .map(|key| key.to_string())
912 .filter(|key| !key.is_empty())
913 .map(Stripe::new),
914 margin_percent: env
915 .var("MARGIN_PERCENT")
916 .ok()
917 .and_then(|percent| percent.to_string().parse().ok())
918 .unwrap_or(20),
919 orchestration_fee_micros: env
920 .var("ORCHESTRATION_FEE_MICROS")
921 .ok()
922 .and_then(|fee| fee.to_string().parse().ok())
923 .unwrap_or(100_000),
924 free: env.var("FREE_WHILE_BUILDING").is_ok_and(|v| v.to_string() == "true"),
925 ceilings: limits::Ceilings::from_env(&env),
Billing accounts, terms and enterprises; g1t is no longer free926 prepaid_only: env.var("PREPAID_ONLY").is_ok_and(|v| v.to_string() == "true"),
Prices keep themselves current with what g1t pays927 deployments_monthly_cents: env
928 .var("DEPLOYMENTS_MONTHLY_CENTS")
929 .ok()
930 .and_then(|cents| cents.to_string().parse().ok())
931 .unwrap_or(500),
932 trial: {
933 let number = |name: &str| env.var(name).ok().and_then(|v| v.to_string().parse::<i64>().ok());
934 match (
935 number("TRIAL_WORKSPACE_MICROS"),
936 number("TRIAL_TOTAL_MICROS"),
937 env.var("TRIAL_UNTIL").ok().map(|v| v.to_string()),
938 ) {
939 (Some(per_workspace_micros), Some(total_micros), Some(until))
940 if per_workspace_micros > 0 && !until.is_empty() =>
941 {
942 Some(TrialConfig {
943 per_workspace_micros,
944 total_micros,
945 until,
946 })
947 }
948 _ => None,
949 }
950 },
951 })
952 }
953}
954
955#[event(scheduled)]
956async fn scheduled(event: ScheduledEvent, env: Env, _ctx: ScheduleContext) {
957 let Ok(billing) = Billing::from_env(&env) else {
958 return;
959 };
960 let keeper = keeper::Keeper::from_env(&env);
961 if let Err(error) = billing.settle_runs(&keeper).await {
962 worker::console_error!("settling runs failed: {error}");
963 }
Billing accounts, terms and enterprises; g1t is no longer free964 if let Err(error) = billing.autopay().await {
965 worker::console_error!("paying at the limit failed: {error}");
966 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace967 if let Err(error) = billing.close_months().await {
968 worker::console_error!("closing the month failed: {error}");
969 }
Stripe webhooks, enterprise invoices, and sudo for both970 if let Err(error) = billing.invoice_enterprises().await {
971 worker::console_error!("invoicing enterprises failed: {error}");
972 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace973 if let Ok(identity) = env.service("IDENTITY") {
974 if let Err(error) = billing.warn_limits(&identity).await {
975 worker::console_error!("warning owners failed: {error}");
976 }
977 }
The keeper reads Cloudflare as it really answers978 // Once a day, and at once if the costs were never checked: check every
979 // cost against what Cloudflare billed.
980 if event.cron() == keeper::DAILY || billing.never_checked().await.unwrap_or(false) {
Prices keep themselves current with what g1t pays981 if let Err(error) = billing.reconcile(&keeper).await {
982 worker::console_error!("checking costs against Cloudflare failed: {error}");
983 }
984 }
985}
986
Agents and memory, checks and conflicts, profiles, slug renames, custom domains987/// Events from the bus, on billing's own queue: only a workspace's rename
988/// matters here (see `rename`).
989#[event(queue)]
990async fn queue(batch: MessageBatch<g1t_contracts::events::Event>, env: Env, _ctx: Context) -> Result<()> {
991 let billing = Billing::from_env(&env)?;
992 let identity = env.service("IDENTITY").ok();
993 for message in batch.messages()? {
994 billing.on_event(identity.as_ref(), message.body()).await?;
995 message.ack();
996 }
997 Ok(())
998}
999
Agents as a team: lifecycle, merge queue, billing and a new shell1000#[event(fetch)]
1001async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> {
1002 let Some(method) = rpc_method(&request) else {
1003 return Response::error("Not found", 404);
1004 };
1005 let body: serde_json::Value = request.json().await?;
Prices keep themselves current with what g1t pays1006 let billing = Billing::from_env(&env)?;
Agents as a team: lifecycle, merge queue, billing and a new shell1007 match method.as_str() {
1008 "status" => reply(&billing.status()),
1009 "account" => reply(&billing.account(args(body)?).await?),
1010 "ledger" => reply(&billing.ledger(args(body)?).await?),
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request1011 "usage" => reply(&billing.usage(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1012 "checkout" => reply(&billing.checkout(args(body)?).await?),
1013 "confirm" => reply(&billing.confirm(args(body)?).await?),
1014 "can_start" => reply(&billing.can_start(args(body)?).await?),
A free allowance on g1t's models, so anyone can try its agents1015 "trial" => reply(&billing.trial(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1016 "start_run" => reply(&billing.start_run(args(body)?).await?),
1017 "finish_run" => reply(&billing.finish_run(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan1018 "features" => reply(&billing.features(args(body)?).await?),
1019 "subscribe" => reply(&billing.subscribe(args(body)?).await?),
1020 "confirm_subscription" => reply(&billing.confirm_subscription(args(body)?).await?),
1021 "cancel_subscription" => reply(&billing.cancel_subscription(args(body)?).await?),
1022 "has_feature" => reply(&billing.has_feature(args(body)?).await?),
1023 "charge_feature" => reply(&billing.charge_feature(args(body)?).await?),
Every sandbox is metered by the second1024 "record_sandbox" => reply(&billing.record_sandbox(args(body)?).await?),
Usage limits: unpaid usage can only go so far1025 "limit" => reply(&billing.limit(args(body)?).await?),
1026 "check_limit" => reply(&billing.check_limit(args(body)?).await?),
1027 "set_spend_limit" => reply(&billing.set_spend_limit(args(body)?).await?),
Prices keep themselves current with what g1t pays1028 "prices" => reply(&billing.prices().await?),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1029 "billing_portal" => reply(&billing.billing_portal(args(body)?).await?),
1030 "admin_billing_link" => reply(&billing.admin_billing_link(args(body)?).await?),
Stripe webhooks, enterprise invoices, and sudo for both1031 "admin_stripe" => reply(&billing.admin_stripe(args(body)?).await?),
1032 "admin_enterprise_billing" => reply(&billing.admin_enterprise_billing(args(body)?).await?),
1033 "admin_invoice_enterprise" => reply(&billing.admin_invoice_enterprise(args(body)?).await?),
1034 "stripe_webhook" => reply(&billing.stripe_webhook(args(body)?).await?),
Two limits, real invoices, trust that grows by itself, sales signals1035 "invoices" => reply(&billing.invoices(args(body)?).await?),
1036 "admin_workspace_invoices" => {
1037 let a: AdminWorkspaceInvoicesArgs = args(body)?;
1038 reply(&billing.workspace_invoices(&a.workspace.to_lowercase()).await?)
1039 }
1040 "admin_signals" => reply(&billing.admin_signals(args(body)?).await?),
1041 "admin_overview" => reply(&billing.admin_overview(args(body)?).await?),
1042 "admin_sales" => reply(&billing.admin_sales(args(body)?).await?),
1043 "admin_set_sales" => reply(&billing.admin_set_sales(args(body)?).await?),
1044 "admin_add_note" => reply(&billing.admin_add_note(args(body)?).await?),
Billing lists every invoice and every staff change; signals carry follow-ups1045 "admin_invoices" => reply(&billing.admin_invoices(args(body)?).await?),
1046 "admin_audit" => reply(&billing.admin_audit(args(body)?).await?),
Prices keep themselves current with what g1t pays1047 "note_pending" => reply(&billing.note_pending(args(body)?).await?),
Billing accounts, terms and enterprises; g1t is no longer free1048 "admin_accounts" => reply(&billing.admin_accounts(args(body)?).await?),
1049 "admin_account" => reply(&billing.admin_account(args(body)?).await?),
1050 "admin_set_terms" => reply(&billing.admin_set_terms(args(body)?).await?),
1051 "admin_create_enterprise" => reply(&billing.admin_create_enterprise(args(body)?).await?),
1052 "admin_attach" => reply(&billing.admin_attach(args(body)?).await?),
1053 "admin_credit" => reply(&billing.admin_credit(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1054 _ => Response::error("Unknown method", 404),
1055 }
1056}
1057
1058#[cfg(test)]
1059mod tests {
1060 use super::*;
1061
1062 #[test]
1063 fn a_run_is_charged_its_cost_plus_the_margin() {
1064 // $0.05 at 20% is six cents.
1065 assert_eq!(charge_micros(0.05, 20), 60_000);
1066 assert_eq!(charge_micros(1.0, 20), 1_200_000);
1067 assert_eq!(charge_micros(0.05, 0), 50_000);
1068 }
1069
1070 #[test]
1071 fn fractions_of_a_millionth_round_up_and_nothing_costs_less_than_nothing() {
1072 assert_eq!(charge_micros(0.000_000_4, 20), 2);
1073 assert_eq!(charge_micros(0.0, 20), 0);
1074 assert_eq!(charge_micros(-3.0, 20), 0);
1075 }
1076
1077 #[test]
Every sandbox is metered by the second1078 fn sandbox_seconds_are_charged_only_past_the_free_minutes() {
1079 let free = sandbox_allowance::FREE_SECONDS;
1080 assert_eq!(sandbox_billable(0, 600), 0);
1081 assert_eq!(sandbox_billable(free - 100, 600), 500);
1082 assert_eq!(sandbox_billable(free + 5, 600), 600);
1083 }
1084
1085 #[test]
1086 fn durations_read_plainly() {
1087 assert_eq!(duration(40), "40s");
1088 assert_eq!(duration(192), "3m 12s");
1089 assert_eq!(duration(3720), "1h 2m");
1090 }
1091
1092 #[test]
Agents as a team: lifecycle, merge queue, billing and a new shell1093 fn an_absurd_cost_is_capped() {
1094 assert_eq!(charge_micros(1e9, 20), 120 * MICROS_PER_DOLLAR);
1095 }
1096}