g1t/services/billing/src/lib.rs

1,309 lines57,112 bytesCodeBlame

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

Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1//! The billing service: what g1t's compute costs, charged to the workspace
2//! it ran for at what g1t pays plus 20%.
Agents as a team: lifecycle, merge queue, billing and a new shell3//!
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look4//! One paid plan, "g1t" (see `features`): $20 a month per workspace, never
5//! per person, with $10 of usage included, deployments, and more private
6//! storage. The forge is free for everyone; compute needs the plan or a
7//! card check (see `compute` and `cards`). Before anything that costs money
8//! starts, the service that starts it reserves its estimate here; when it
9//! is done, what it cost goes on the ledger plus the margin, drawn first
10//! from what the plan includes, a trial or g1t's pools (see `credits`).
11//! Every change is a ledger entry, and a balance is always the sum of its
12//! ledger.
Paid features: a workspace turns on Deployments with a monthly plan13//!
Agents as a team: lifecycle, merge queue, billing and a new shell14//! Without a card processor configured the service says so and charges
15//! nothing, so that g1t still runs where billing has not been set up.
16//!
17//! Reached only through service bindings; see `g1t_contracts::billing` for
18//! the methods and their arguments.
19
Billing accounts, terms and enterprises; g1t is no longer free20mod accounts;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays21mod budget;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look22mod cards;
23mod closing;
24mod compute;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily25mod costs;
26mod margin;
27mod pricing;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put28mod credits;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look29mod overages;
30mod requests;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put31mod storage;
Two limits, real invoices, trust that grows by itself, sales signals32mod invoices;
33mod sales;
The statement is a month at a time, a line per kind of charge34mod statement;
Stripe webhooks, enterprise invoices, and sudo for both35mod webhooks;
Paid features: a workspace turns on Deployments with a monthly plan36mod features;
Prices keep themselves current with what g1t pays37mod keeper;
Usage limits: unpaid usage can only go so far38mod limits;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains39mod rename;
sudo: reset a test workspace's billing so it starts again as a new customer; refused on a live Stripe key, for comped workspaces and for an enterprise's40mod reset;
Audit logs are kept by plan: a week on free, 90 days on the plan, and what staff set for an account in sudo41mod retention;
Agents as a team: lifecycle, merge queue, billing and a new shell42mod stripe;
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept43mod stripe_sync;
Costs: Cloudflare's subscriptions read from Cloudflare each day, the estimate only until then; sudo's costs split into Costs & margin and Bill & pricing44mod subscriptions;
Mission control shows model usage, yours and the workspace's: tokens, cost, active days, cache share, each day, and the mix45mod tokens;
Agents as a team: lifecycle, merge queue, billing and a new shell46
47use g1t_contracts::billing::*;
48use g1t_contracts::time::rfc3339;
49use g1t_contracts::{FailureCode, Outcome, Role, new_id};
Billing accounts, terms and enterprises; g1t is no longer free50use g1t_contracts::billing::TermsKind;
Agents as a team: lifecycle, merge queue, billing and a new shell51use g1t_kit::{args, now_ms, reply, rpc_method};
52use serde::Deserialize;
53use sha2::{Digest, Sha256};
54use worker::wasm_bindgen::JsValue;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains55use worker::{Context, D1Database, Env, MessageBatch, MessageExt, Request, Response, Result, ScheduleContext, ScheduledEvent, event};
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index56use futures_util::future::{try_join, try_join5};
Agents as a team: lifecycle, merge queue, billing and a new shell57
58use stripe::Stripe;
59
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look60/// Prepaying: $25 at the least; by card up to $10,000 at a time, and by
61/// bank transfer from $1,000 to $100,000.
62const MIN_TOP_UP_CENTS: u32 = 2_500;
63const MAX_TOP_UP_CENTS: u32 = 1_000_000;
64const MIN_BANK_TRANSFER_CENTS: u32 = 100_000;
65const MAX_BANK_TRANSFER_CENTS: u32 = 10_000_000;
Agents as a team: lifecycle, merge queue, billing and a new shell66const LEDGER_PAGE: u32 = 100;
67/// A run's reported cost is believed up to this much. A sandbox cannot
68/// spend more in the time it has, so anything above is a fault.
69const MAX_RUN_COST_USD: f64 = 100.0;
70
71/// What a run is charged: its cost plus the margin, rounded up to a whole
72/// millionth of a dollar.
73pub fn charge_micros(cost_usd: f64, margin_percent: u32) -> i64 {
74 let cost_micros = (cost_usd.clamp(0.0, MAX_RUN_COST_USD) * MICROS_PER_DOLLAR as f64).ceil();
75 (cost_micros * f64::from(100 + margin_percent) / 100.0).ceil() as i64
76}
77
Merge branch 'worktree-agent-a633ac0f7f66d419d'78/// What a cost g1t trusts (the price book's, or what AI Gateway priced a
79/// run at) is charged at: plus the margin, rounded up to a whole millionth.
80/// Unlike `charge_micros`, never capped: only a sandbox's own report is
81/// held to `MAX_RUN_COST_USD`, so a run that really cost more is charged
82/// for all of it once it is settled.
83pub fn margin_on(cost_micros: i64, margin_percent: u32) -> i64 {
84 let cost = i128::from(cost_micros.max(0));
85 let charge = (cost * i128::from(100 + margin_percent) + 99) / 100;
86 i64::try_from(charge).unwrap_or(i64::MAX)
87}
88
Agents as a team: lifecycle, merge queue, billing and a new shell89fn hash(token: &str) -> String {
90 hex::encode(Sha256::digest(token.as_bytes()))
91}
92
93fn optional(value: Option<&str>) -> JsValue {
94 value.map_or(JsValue::NULL, JsValue::from)
95}
96
97#[derive(Deserialize)]
98struct AccountRow {
99 balance_micros: i64,
100 customer_id: Option<String>,
101}
102
103#[derive(Deserialize)]
104struct LedgerRow {
105 id: String,
106 kind: EntryKind,
107 amount_micros: i64,
108 description: String,
109 repo: Option<String>,
110 number: Option<u32>,
111 task: Option<String>,
112 model: Option<String>,
113 created_by: Option<String>,
114 created_at: String,
Integrations: your own model provider, alerts that open issues, tickets agents read115 billed_to: Option<String>,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace116 #[serde(default)]
117 workspace: Option<String>,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put118 #[serde(default)]
119 credit_micros: Option<i64>,
120 #[serde(default)]
121 trial_micros: Option<i64>,
122 #[serde(default)]
123 oss_micros: Option<i64>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look124 #[serde(default)]
125 given_micros: Option<i64>,
Agents as a team: lifecycle, merge queue, billing and a new shell126}
127
128impl From<LedgerRow> for LedgerEntry {
129 fn from(row: LedgerRow) -> Self {
130 LedgerEntry {
131 id: row.id,
132 kind: row.kind,
133 amount_micros: row.amount_micros,
134 description: row.description,
135 repo: row.repo,
136 number: row.number,
137 task: row.task,
138 model: row.model,
Integrations: your own model provider, alerts that open issues, tickets agents read139 billed_to: row.billed_to.unwrap_or_else(|| "g1t".to_owned()),
Agents as a team: lifecycle, merge queue, billing and a new shell140 created_by: row.created_by,
141 created_at: row.created_at,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace142 workspace: row.workspace,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put143 credit_micros: row.credit_micros.unwrap_or(0),
144 trial_micros: row.trial_micros.unwrap_or(0),
145 oss_micros: row.oss_micros.unwrap_or(0),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look146 given_micros: row.given_micros.unwrap_or(0),
Agents as a team: lifecycle, merge queue, billing and a new shell147 }
148 }
149}
150
151#[derive(Deserialize)]
152struct RunRow {
153 workspace: String,
154 repo: String,
155 number: u32,
156 task: String,
157 model: String,
158 token_hash: String,
Integrations: your own model provider, alerts that open issues, tickets agents read159 billed_to: Option<String>,
160}
161
162impl RunRow {
163 fn own_provider(&self) -> bool {
164 self.billed_to.as_deref() == Some("workspace")
165 }
Agents as a team: lifecycle, merge queue, billing and a new shell166}
167
168#[derive(Deserialize)]
169struct CheckoutRow {
170 workspace: String,
171 created_by: String,
172}
173
174/// A row an `UPDATE … RETURNING` touched.
175#[derive(Deserialize)]
176struct Touched {
177 #[allow(dead_code)]
178 id: String,
179}
180
181struct Billing {
182 db: D1Database,
183 /// Absent when no card processor is configured.
184 stripe: Option<Stripe>,
Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard185 /// The destination's signing secret from Stripe (`STRIPE_WEBHOOK_SECRET`);
186 /// without it no event is believed.
187 webhook_secret: Option<String>,
Agents as a team: lifecycle, merge queue, billing and a new shell188 margin_percent: u32,
Free while g1t is being built out; agents can check out their own forks189 /// While g1t is being built out, nothing is charged (`FREE_WHILE_BUILDING`).
190 free: bool,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put191 /// Whether new workspaces get trial credit (`TRIAL_WORKSPACE_MICROS`
192 /// and `TRIAL_MONTHLY_POOL_MICROS` both above zero).
193 trials_on: bool,
194 /// The plans' and pools' numbers; see `credits`.
195 plans: credits::Config,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look196 /// The repos service: which repositories are public, what private ones
197 /// hold, and their git operations. Absent where it is not bound.
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put198 repos: Option<worker::Fetcher>,
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member199 /// The packages service: what each workspace's packages hold.
200 packages: Option<worker::Fetcher>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look201 /// The identity service, which emails owners. Absent where it is not
202 /// bound.
203 identity: Option<worker::Fetcher>,
Usage limits: unpaid usage can only go so far204 /// How far unpaid usage may go; see `limits`.
205 ceilings: limits::Ceilings,
Billing accounts, terms and enterprises; g1t is no longer free206 /// `PREPAID_ONLY`: the old rule, that agents need credit first.
207 prepaid_only: bool,
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays208 /// The caps on what g1t pays for itself; see `budget`.
209 caps: budget::Caps,
210 /// The worker's bindings, for emailing staff (`EMAIL`).
211 env: Env,
A free allowance on g1t's models, so anyone can try its agents212}
213
Agents as a team: lifecycle, merge queue, billing and a new shell214impl Billing {
215 fn status(&self) -> Status {
216 Status {
217 enabled: self.stripe.is_some(),
218 live: self.stripe.as_ref().is_some_and(Stripe::live),
Free while g1t is being built out; agents can check out their own forks219 free: self.free,
Agents as a team: lifecycle, merge queue, billing and a new shell220 }
221 }
222
223 async fn row(&self, workspace: &str) -> Result<Option<AccountRow>> {
224 self.db
225 .prepare("SELECT balance_micros, customer_id FROM accounts WHERE workspace = ?")
226 .bind(&[workspace.into()])?
227 .first::<AccountRow>(None)
228 .await
229 }
230
231 async fn standing(&self, workspace: &str) -> Result<Account> {
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept232 // The card as last synced (stripe_sync.rs), not asked of Stripe.
233 let (row, card) = try_join(self.row(workspace), self.saved_card(workspace)).await?;
Agents as a team: lifecycle, merge queue, billing and a new shell234 Ok(Account {
235 workspace: workspace.to_owned(),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace236 balance_micros: row.map_or(0, |row| row.balance_micros),
Agents as a team: lifecycle, merge queue, billing and a new shell237 status: self.status(),
238 margin_percent: self.margin_percent,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace239 card,
Agents as a team: lifecycle, merge queue, billing and a new shell240 })
241 }
242
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace243 /// The workspace's customer at Stripe, made the first time one is needed.
244 pub(crate) async fn customer_for(&self, workspace: &str) -> Result<String> {
245 let Some(stripe) = &self.stripe else {
246 return Err(worker::Error::RustError("payments are not set up".into()));
247 };
248 if let Some(customer) = self.row(workspace).await?.and_then(|row| row.customer_id) {
249 return Ok(customer);
250 }
251 let customer = stripe.create_customer(workspace).await?;
252 self.db
253 .prepare(
254 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at) VALUES (?1, 0, ?2, ?3)
255 ON CONFLICT (workspace) DO UPDATE SET customer_id = ?2",
256 )
257 .bind(&[workspace.into(), customer.as_str().into(), rfc3339(now_ms()).into()])?
258 .run()
259 .await?;
260 Ok(customer)
261 }
262
263 /// Stripe's hosted billing page for the workspace. Owners only.
264 async fn billing_portal(&self, a: BillingPortalArgs) -> Result<Outcome<Checkout>> {
265 let workspace = a.workspace.to_lowercase();
266 if a.actor.role_in(&workspace) != Some(Role::Owner) {
267 return Ok(Outcome::fail(FailureCode::Forbidden, "Only an owner can manage the workspace's billing."));
268 }
269 let Some(stripe) = &self.stripe else {
270 return Ok(Outcome::fail(FailureCode::Conflict, "Payments are not set up on this g1t."));
271 };
272 let customer = match self.customer_for(&workspace).await {
273 Ok(customer) => customer,
274 Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe could not be reached: {error}"))),
275 };
276 match stripe.portal_session(&customer, &a.return_url).await {
277 Ok(url) => Ok(Outcome::Ok(Checkout { url })),
278 Err(error) if stripe::is_missing(&error) => {
279 // The customer was removed at Stripe: a new one next time.
280 self.forget_customer(&workspace).await?;
281 Ok(Outcome::fail(FailureCode::Conflict, "Stripe no longer had this workspace's customer. Try again."))
282 }
283 Err(error) => Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe's billing page could not be opened: {error}"))),
284 }
285 }
286
Agents as a team: lifecycle, merge queue, billing and a new shell287 /// Adds a ledger entry and moves the balance by the same amount, as
288 /// one write.
289 #[allow(clippy::too_many_arguments)]
290 async fn enter(
291 &self,
292 workspace: &str,
293 kind: EntryKind,
294 amount_micros: i64,
295 description: &str,
296 reference: &str,
297 run: Option<&RunRow>,
298 cost_micros: Option<i64>,
299 created_by: Option<&str>,
300 customer: Option<&str>,
301 ) -> Result<()> {
302 let now = now_ms();
303 let timestamp = rfc3339(now);
304 let kind = match kind {
305 EntryKind::TopUp => "top_up",
306 EntryKind::Usage => "usage",
307 };
308 self.db
309 .batch(vec![
310 self.db
311 .prepare(
312 "INSERT INTO ledger
313 (id, workspace, kind, amount_micros, description, repo, number, task,
Integrations: your own model provider, alerts that open issues, tickets agents read314 model, cost_micros, reference, created_by, created_at, billed_to)
315 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
Agents as a team: lifecycle, merge queue, billing and a new shell316 )
317 .bind(&[
318 new_id("led", now).into(),
319 workspace.into(),
320 kind.into(),
321 // D1 takes numbers as doubles, which hold every
322 // amount this service will see exactly.
323 (amount_micros as f64).into(),
324 description.into(),
325 optional(run.map(|run| run.repo.as_str())),
326 run.map_or(JsValue::NULL, |run| run.number.into()),
327 optional(run.map(|run| run.task.as_str())),
328 optional(run.map(|run| run.model.as_str())),
329 cost_micros.map_or(JsValue::NULL, |cost| (cost as f64).into()),
330 reference.into(),
331 optional(created_by),
332 timestamp.as_str().into(),
Integrations: your own model provider, alerts that open issues, tickets agents read333 run.map_or("g1t", |run| if run.own_provider() { "workspace" } else { "g1t" }).into(),
Agents as a team: lifecycle, merge queue, billing and a new shell334 ])?,
335 self.db
336 .prepare(
337 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at)
338 VALUES (?1, ?2, ?3, ?4)
339 ON CONFLICT (workspace) DO UPDATE SET
340 balance_micros = balance_micros + ?2,
341 customer_id = COALESCE(?3, customer_id)",
342 )
343 .bind(&[
344 workspace.into(),
345 (amount_micros as f64).into(),
346 optional(customer),
347 timestamp.as_str().into(),
348 ])?,
349 ])
350 .await?;
Billing accounts, terms and enterprises; g1t is no longer free351 // Money in clears a card declined at the limit.
352 if kind == "top_up" {
353 self.db
354 .prepare("UPDATE limits SET autopay_failed_at = NULL, autopay_error = NULL WHERE workspace = ?")
355 .bind(&[workspace.into()])?
356 .run()
357 .await?;
358 }
Agents as a team: lifecycle, merge queue, billing and a new shell359 Ok(())
360 }
361
362 async fn account(&self, a: AccountArgs) -> Result<Outcome<Account>> {
363 let workspace = a.workspace.to_lowercase();
364 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
365 return Ok(members_only());
366 }
367 Ok(Outcome::Ok(self.standing(&workspace).await?))
368 }
369
370 async fn ledger(&self, a: AccountArgs) -> Result<Outcome<Vec<LedgerEntry>>> {
371 let workspace = a.workspace.to_lowercase();
372 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
373 return Ok(members_only());
374 }
375 let rows = self
376 .db
377 .prepare("SELECT * FROM ledger WHERE workspace = ? ORDER BY id DESC LIMIT ?")
378 .bind(&[workspace.into(), LEDGER_PAGE.into()])?
379 .all()
380 .await?
381 .results::<LedgerRow>()?;
382 Ok(Outcome::Ok(
383 rows.into_iter().map(LedgerEntry::from).collect(),
384 ))
385 }
386
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request387 async fn usage(&self, a: UsageArgs) -> Result<Outcome<Usage>> {
388 let workspace = a.workspace.to_lowercase();
389 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
390 return Ok(members_only());
391 }
392 #[derive(serde::Deserialize)]
393 struct SliceRow {
394 key: Option<String>,
395 micros: Option<i64>,
396 runs: Option<u32>,
397 }
A comped workspace's usage chart and breakdowns show what runs used at cost, as the free tier's do398 // While nothing is charged (g1t is free, or the workspace is
399 // comped), what was used is what there is to show.
400 #[derive(serde::Deserialize)]
401 struct Comped {
402 n: i64,
403 }
404 let comped = self
405 .db
406 .prepare("SELECT COUNT(*) AS n FROM billing_accounts WHERE kind = 'workspace' AND terms_kind = 'comped' AND substr(id, 4) = ?1")
407 .bind(&[workspace.as_str().into()])?
408 .first::<Comped>(None)
409 .await?
410 .is_some_and(|row| row.n > 0);
411 let measure = if self.free || comped { "COALESCE(cost_micros, 0)" } else { "-amount_micros" };
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request412 let slices = |key: &str, limit: u32| {
413 format!(
Usage while free is shown at cost; agents get rustfmt and clippy414 "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 request415 WHERE workspace = ?1 AND kind = 'usage' AND created_at >= ?2
416 GROUP BY 1 ORDER BY micros DESC LIMIT {limit}"
417 )
418 };
419 let query = |sql: String| {
420 let db = &self.db;
421 let workspace = workspace.clone();
422 let since = a.since.clone();
423 async move {
424 let rows = db
425 .prepare(sql)
426 .bind(&[workspace.into(), since.into()])?
427 .all()
428 .await?
429 .results::<SliceRow>()?;
430 Ok::<Vec<UsageSlice>, worker::Error>(
431 rows.into_iter()
432 .map(|row| UsageSlice {
433 key: row.key.unwrap_or_else(|| "other".to_owned()),
434 micros: row.micros.unwrap_or_default(),
435 runs: row.runs.unwrap_or_default(),
436 })
437 .collect(),
438 )
439 }
440 };
441 #[derive(serde::Deserialize)]
442 struct Totals {
443 spent: Option<i64>,
Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged444 g1t_cost: Option<i64>,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request445 cost: Option<i64>,
Integrations: your own model provider, alerts that open issues, tickets agents read446 provider: Option<i64>,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request447 runs: Option<u32>,
448 added: Option<i64>,
449 }
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index450 let totals = async {
451 self.db
452 .prepare(
453 "SELECT
454 -SUM(CASE WHEN kind = 'usage' THEN amount_micros END) AS spent,
Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged455 SUM(CASE WHEN kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' THEN cost_micros END) AS g1t_cost,
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index456 SUM(CASE WHEN kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' THEN cost_micros END) AS cost,
457 SUM(CASE WHEN kind = 'usage' AND billed_to = 'workspace' THEN cost_micros END) AS provider,
458 SUM(CASE WHEN kind = 'usage' THEN 1 ELSE 0 END) AS runs,
459 SUM(CASE WHEN kind = 'top_up' THEN amount_micros END) AS added
460 FROM ledger WHERE workspace = ?1 AND created_at >= ?2",
461 )
462 .bind(&[workspace.as_str().into(), a.since.as_str().into()])?
463 .first::<Totals>(None)
464 .await
465 };
466 // The totals and the five slices read the same rows independently,
467 // so they go to D1 at once: one round trip of waiting, not six.
468 let (totals, (by_day, by_task, by_repo, by_pull, by_model)) = try_join(
469 totals,
470 try_join5(
471 query(slices("substr(created_at, 1, 10) || '/' || COALESCE(task, 'other')", 400)),
472 query(slices("task", 20)),
473 query(slices("repo", 20)),
474 query(slices("repo || '#' || number", 10)),
475 query(slices("model", 10)),
476 ),
477 )
478 .await?;
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request479 let totals = totals.unwrap_or(Totals {
480 spent: None,
Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged481 g1t_cost: None,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request482 cost: None,
Integrations: your own model provider, alerts that open issues, tickets agents read483 provider: None,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request484 runs: None,
485 added: None,
486 });
487 Ok(Outcome::Ok(Usage {
488 spent_micros: totals.spent.unwrap_or_default(),
Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged489 // At price, what g1t's usage came to, less what was charged: the
490 // part the included usage, the trial, a pool, or a free period paid.
491 covered_micros: (crate::credits::with_margin(totals.g1t_cost.unwrap_or_default(), self.margin_percent)
492 - totals.spent.unwrap_or_default())
493 .max(0),
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request494 cost_micros: totals.cost.unwrap_or_default(),
Integrations: your own model provider, alerts that open issues, tickets agents read495 provider_micros: totals.provider.unwrap_or_default(),
Usage while free is shown at cost; agents get rustfmt and clippy496 used_micros: totals.cost.unwrap_or_default() + totals.provider.unwrap_or_default(),
497 free: self.free,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request498 runs: totals.runs.unwrap_or_default(),
499 added_micros: totals.added.unwrap_or_default(),
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index500 by_day,
501 by_task,
502 by_repo,
503 by_pull,
504 by_model,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request505 since: a.since,
506 }))
507 }
508
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look509 /// `checkout`: prepays usage, by card or (from $1,000) bank transfer.
Agents as a team: lifecycle, merge queue, billing and a new shell510 async fn checkout(&self, a: CheckoutArgs) -> Result<Outcome<Checkout>> {
511 let workspace = a.workspace.to_lowercase();
512 if a.actor.role_in(&workspace) != Some(Role::Owner) {
513 return Ok(Outcome::fail(
514 FailureCode::Forbidden,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look515 "Only an owner can prepay for a workspace.",
Agents as a team: lifecycle, merge queue, billing and a new shell516 ));
517 }
518 let Some(stripe) = &self.stripe else {
519 return Ok(Outcome::fail(
520 FailureCode::Conflict,
521 "Payments are not set up on this g1t yet.",
522 ));
523 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look524 let bank_transfer = a.method.as_deref() == Some("bank_transfer");
525 if let Err(why) = prepay_amount(a.amount_cents, bank_transfer) {
526 return Ok(Outcome::fail(FailureCode::Invalid, why));
Agents as a team: lifecycle, merge queue, billing and a new shell527 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look528 // A bank transfer needs a customer for its account details.
529 let customer = if bank_transfer {
530 match self.customer_for(&workspace).await {
531 Ok(customer) => Some(customer),
532 Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe could not be reached: {error}"))),
533 }
534 } else {
535 self.row(&workspace).await?.and_then(|row| row.customer_id)
536 };
Project dependencies: addresses, preview stacks, Affects, and agents who know537 let session = match stripe
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look538 .start_checkout(&workspace, a.amount_cents, customer.as_deref(), &a.return_url, bank_transfer)
Project dependencies: addresses, preview stacks, Affects, and agents who know539 .await
540 {
541 Ok(session) => session,
542 // A customer saved under another Stripe account: start afresh.
543 Err(error) if customer.is_some() && stripe::is_missing(&error) => {
544 self.forget_customer(&workspace).await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look545 let customer = if bank_transfer { Some(self.customer_for(&workspace).await?) } else { None };
546 stripe.start_checkout(&workspace, a.amount_cents, customer.as_deref(), &a.return_url, bank_transfer).await?
Project dependencies: addresses, preview stacks, Affects, and agents who know547 }
548 Err(error) => return Err(error),
549 };
Agents as a team: lifecycle, merge queue, billing and a new shell550 let Some(url) = session.url else {
551 return Err(worker::Error::RustError(
552 "the card processor returned no payment page".into(),
553 ));
554 };
555 self.db
556 .prepare(
557 "INSERT INTO checkouts (id, workspace, amount_cents, created_by, created_at)
558 VALUES (?, ?, ?, ?, ?)",
559 )
560 .bind(&[
561 session.id.into(),
562 workspace.into(),
563 a.amount_cents.into(),
564 a.actor.username.into(),
565 rfc3339(now_ms()).into(),
566 ])?
567 .run()
568 .await?;
569 Ok(Outcome::Ok(Checkout { url }))
570 }
571
572 /// Credits a payment if the processor says it was made and it has not
573 /// been credited before. The amount credited is what the processor
574 /// says was paid, not what anyone here remembers asking for.
575 async fn confirm(&self, a: ConfirmArgs) -> Result<Outcome<Account>> {
576 let workspace = a.workspace.to_lowercase();
577 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
578 return Ok(members_only());
579 }
580 let (Some(stripe), Some(checkout)) = (
581 &self.stripe,
582 self.db
583 .prepare(
584 "SELECT workspace, created_by FROM checkouts
585 WHERE id = ? AND workspace = ? AND status = 'open'",
586 )
587 .bind(&[a.session.as_str().into(), workspace.as_str().into()])?
588 .first::<CheckoutRow>(None)
589 .await?,
590 ) else {
591 // Unknown, someone else's, or already credited: nothing to do.
592 return Ok(Outcome::Ok(self.standing(&workspace).await?));
593 };
594 let session = stripe.session(&a.session).await?;
595 let paid = session
596 .amount_total
597 .filter(|_| session.payment_status == "paid");
598 if let Some(cents) = paid {
599 // Only whoever flips it from open to paid enters the credit.
600 let claimed = self
601 .db
602 .prepare(
603 "UPDATE checkouts SET status = 'paid' WHERE id = ? AND status = 'open'
604 RETURNING id",
605 )
606 .bind(&[a.session.as_str().into()])?
607 .first::<Touched>(None)
608 .await?;
609 if claimed.is_some() {
610 self.enter(
611 &checkout.workspace,
612 EntryKind::TopUp,
613 i64::from(cents) * MICROS_PER_DOLLAR / 100,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look614 "Paid in advance",
Agents as a team: lifecycle, merge queue, billing and a new shell615 &session.id,
616 None,
617 None,
618 Some(&checkout.created_by),
619 session.customer.as_deref(),
620 )
621 .await?;
622 }
623 }
624 Ok(Outcome::Ok(self.standing(&workspace).await?))
625 }
626
Project dependencies: addresses, preview stacks, Affects, and agents who know627 /// Drops a saved customer the card processor no longer knows.
628 pub(crate) async fn forget_customer(&self, workspace: &str) -> Result<()> {
629 self.db
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept630 .prepare(
631 "UPDATE accounts SET customer_id = NULL, card_brand = NULL, card_last4 = NULL, card_exp_month = NULL,
632 card_exp_year = NULL, card_synced_at = NULL WHERE workspace = ?",
633 )
Project dependencies: addresses, preview stacks, Affects, and agents who know634 .bind(&[workspace.into()])?
635 .run()
636 .await?;
637 Ok(())
638 }
639
Agents as a team: lifecycle, merge queue, billing and a new shell640 /// A refusal if the workspace has no credit to start an agent with.
641 async fn out_of_credit<T>(&self, workspace: &str) -> Result<Option<Outcome<T>>> {
Billing accounts, terms and enterprises; g1t is no longer free642 // Billing is postpaid: usage limits decide whether work starts
643 // (see `limits`), and credit is a prepayment that lowers what is
644 // owed. A balance no longer has to be positive to start.
645 if self.free || !self.prepaid_only {
Free while g1t is being built out; agents can check out their own forks646 return Ok(None);
647 }
Agents as a team: lifecycle, merge queue, billing and a new shell648 let balance = self
649 .row(workspace)
650 .await?
651 .map_or(0, |row| row.balance_micros);
652 Ok((balance <= 0).then(|| {
653 Outcome::fail(
654 FailureCode::PaymentRequired,
655 format!(
656 "The {workspace} workspace has no agent credit. An owner can add some under Billing on the workspace's page."
657 ),
658 )
659 }))
Billing accounts, terms and enterprises; g1t is no longer free660 }
661
Agents as a team: lifecycle, merge queue, billing and a new shell662 async fn can_start(&self, a: CanStartArgs) -> Result<Outcome<bool>> {
663 if self.stripe.is_none() {
664 return Ok(Outcome::Ok(true));
665 }
Usage limits: unpaid usage can only go so far666 if let Some(stopped) = self.stopped(&a.workspace).await? {
667 return Ok(stopped);
668 }
Agents as a team: lifecycle, merge queue, billing and a new shell669 Ok(self
670 .out_of_credit(&a.workspace.to_lowercase())
671 .await?
672 .unwrap_or(Outcome::Ok(true)))
673 }
674
675 async fn start_run(&self, a: StartRunArgs) -> Result<Outcome<Option<RunTicket>>> {
676 if self.stripe.is_none() {
677 return Ok(Outcome::Ok(None));
678 }
679 let workspace = a.workspace.to_lowercase();
Usage limits: unpaid usage can only go so far680 if let Some(stopped) = self.stopped(&workspace).await? {
681 return Ok(stopped);
682 }
Agents as a team: lifecycle, merge queue, billing and a new shell683 if let Some(refused) = self.out_of_credit(&workspace).await? {
684 return Ok(refused);
685 }
686 let now = now_ms();
687 let run_id = new_id("run", now);
688 let mut bytes = [0u8; 32];
689 getrandom::getrandom(&mut bytes).expect("no source of randomness");
690 let token = hex::encode(bytes);
691 self.db
692 .prepare(
Auto model routing: the cheapest tier that can do each piece of work, a retry goes up a tier, and each run records its tier693 "INSERT INTO runs (id, workspace, repo, number, task, model, token_hash, created_at, billed_to, session_id, tier)
694 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
Agents as a team: lifecycle, merge queue, billing and a new shell695 )
696 .bind(&[
697 run_id.as_str().into(),
698 workspace.into(),
699 format!("{}/{}", a.repo.namespace, a.repo.name).into(),
700 a.number.into(),
701 a.task.into(),
702 a.model.into(),
703 hash(&token).into(),
704 rfc3339(now).into(),
Integrations: your own model provider, alerts that open issues, tickets agents read705 if a.billed_to == "workspace" { "workspace" } else { "g1t" }.into(),
Prices keep themselves current with what g1t pays706 optional(a.session.as_deref().filter(|_| a.billed_to != "workspace")),
Auto model routing: the cheapest tier that can do each piece of work, a retry goes up a tier, and each run records its tier707 optional(
708 a.tier
709 .as_deref()
710 .filter(|tier| a.billed_to != "workspace" && matches!(*tier, "small" | "large")),
711 ),
Agents as a team: lifecycle, merge queue, billing and a new shell712 ])?
713 .run()
714 .await?;
715 Ok(Outcome::Ok(Some(RunTicket { run_id, token })))
716 }
717
718 async fn finish_run(&self, a: FinishRunArgs) -> Result<Outcome<bool>> {
719 let run = self
720 .db
721 .prepare(
Integrations: your own model provider, alerts that open issues, tickets agents read722 "SELECT workspace, repo, number, task, model, token_hash, billed_to FROM runs
Agents as a team: lifecycle, merge queue, billing and a new shell723 WHERE id = ? AND finished_at IS NULL",
724 )
725 .bind(&[a.run_id.as_str().into()])?
726 .first::<RunRow>(None)
727 .await?;
728 let Some(run) = run.filter(|run| run.token_hash == hash(&a.token)) else {
729 return Ok(Outcome::fail(FailureCode::NotFound, "Run not found."));
730 };
731 if !a.cost_usd.is_finite() || a.cost_usd < 0.0 {
732 return Ok(Outcome::fail(FailureCode::Invalid, "That is not a cost."));
733 }
734 // Only whoever closes the run charges for it.
735 let claimed = self
736 .db
737 .prepare(
738 "UPDATE runs SET finished_at = ? WHERE id = ? AND finished_at IS NULL RETURNING id",
739 )
740 .bind(&[rfc3339(now_ms()).into(), a.run_id.as_str().into()])?
741 .first::<Touched>(None)
742 .await?;
743 if claimed.is_none() {
744 return Ok(Outcome::Ok(false));
745 }
Prices are what g1t pays plus 20%, from the first second746 // On the workspace's own provider, the model was paid for there,
747 // and the run's sandbox time is recorded on its own: nothing more
748 // to charge.
749 if run.own_provider() {
750 return Ok(Outcome::Ok(true));
751 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look752 // Its cost plus the margin, on the account's terms; then the plan's
753 // included usage and the trial credit pay what they can, and g1t
754 // covers a free workspace's overrun (see `credits`). Agents are
755 // never the open-source pool's.
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put756 let base = charge_micros(a.cost_usd, self.margin_percent);
Merge branch 'worktree-agent-a633ac0f7f66d419d'757 let (charge, terms_note, discount) = self.charged(&run.workspace, base).await?;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put758 let month = credits::month_of(&rfc3339(now_ms()));
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look759 let eligible = credits::eligible_for(Some(ComputeKind::Agent), None);
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put760 let drawn = self.draw(&run.workspace, charge, &month, &eligible).await?;
Integrations: your own model provider, alerts that open issues, tickets agents read761 let mut description = match run.task.as_str() {
Agents as a team: lifecycle, merge queue, billing and a new shell762 "plan" => format!("Planning for {}", run.repo),
763 "review" => format!("Review of {}#{}", run.repo, run.number),
764 "update" => format!("Catching up {}#{}", run.repo, run.number),
765 _ => format!("Work on {}#{}", run.repo, run.number),
766 };
Billing accounts, terms and enterprises; g1t is no longer free767 description.push_str(&terms_note);
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put768 description.push_str(&drawn.note());
Agents as a team: lifecycle, merge queue, billing and a new shell769 self.enter(
770 &run.workspace,
771 EntryKind::Usage,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put772 -(charge - drawn.total()),
Agents as a team: lifecycle, merge queue, billing and a new shell773 &description,
774 &a.run_id,
775 Some(&run),
776 Some(charge_micros(a.cost_usd, 0)),
777 None,
778 None,
779 )
780 .await?;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put781 self.record_drawn(&a.run_id, &drawn).await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'782 self.record_discount(&a.run_id, discount).await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays783 self.count_spend(&run.workspace, charge_micros(a.cost_usd, 0), charge - drawn.total(), &drawn).await;
Agents as a team: lifecycle, merge queue, billing and a new shell784 Ok(Outcome::Ok(true))
785 }
786}
787
Every sandbox is metered by the second788impl Billing {
Prices are what g1t pays plus 20%, from the first second789 /// Records how long a sandbox ran, with its cost and its charge: every
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look790 /// second, from the first, at the price book's price; on its own CPU
791 /// when it reports it. Settles its reservation, if it names one.
Every sandbox is metered by the second792 async fn record_sandbox(&self, a: RecordSandboxArgs) -> Result<Outcome<bool>> {
Fast pages, required checks on the branch, self-hosted runners, honest incidents793 // Self-hosted time is recorded wherever g1t runs, for its minutes;
794 // anything else only where there is a bill to put it on.
795 if (self.stripe.is_none() && !a.self_hosted) || a.seconds == 0 {
Every sandbox is metered by the second796 return Ok(Outcome::Ok(false));
797 }
798 let workspace = a.workspace.to_lowercase();
799 let seen = self
800 .db
801 .prepare("SELECT id FROM ledger WHERE reference = ?")
802 .bind(&[a.reference.as_str().into()])?
803 .first::<Touched>(None)
804 .await?;
805 if seen.is_some() {
806 return Ok(Outcome::Ok(false));
807 }
808 let now = now_ms();
809 let timestamp = rfc3339(now);
810 let seconds = i64::from(a.seconds);
Fast pages, required checks on the branch, self-hosted runners, honest incidents811 // On the workspace's own machine: its minutes go on usage, at $0,
812 // and whatever was reserved for it is given back.
813 if a.self_hosted {
814 let description = format!("{}: {} of self-hosted runner time, $0", a.description, duration(seconds));
815 self.db
816 .prepare(
817 "INSERT INTO ledger
818 (id, workspace, kind, amount_micros, description, repo, task,
819 cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros)
820 VALUES (?, ?, 'usage', 0, ?, ?, 'self_hosted', 0, ?, ?, 'workspace', 0, 0, 0, 0)",
821 )
822 .bind(&[
823 new_id("led", now).into(),
824 workspace.as_str().into(),
825 description.as_str().into(),
826 optional(a.repo.as_deref()),
827 a.reference.as_str().into(),
828 timestamp.as_str().into(),
829 ])?
830 .run()
831 .await?;
832 if let Some(reservation) = &a.reservation_id {
833 self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: 0 }).await?;
834 }
835 return Ok(Outcome::Ok(true));
836 }
Prices are what g1t pays plus 20%, from the first second837 // From the price book, which follows what Cloudflare bills g1t. A
838 // sandbox is the same container as a build, so without a row it is
839 // a build second's cost plus the margin.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look840 let (cost_per_second, _) = self.price("sandbox_second").await?.unwrap_or_else(|| {
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas841 let cost = deployment_costs::MICROS_PER_BUILD_SECOND as f64;
Prices are what g1t pays plus 20%, from the first second842 (cost, Price::price_for(cost, self.margin_percent))
843 });
Fast pages, required checks on the branch, self-hosted runners, honest incidents844 // A larger machine (`runs-on: g1t-4core`): its memory and disk
845 // cost more each second, and without its own CPU it is priced at
846 // its vCPUs as busy as the standard machine's.
847 let instance = a.instance.as_deref().and_then(g1t_contracts::actions::instance_named);
848 let base_scale = instance.map_or(1.0, |i| keeper::base_scale(i.memory_gib, i.disk_gb));
849 let price_scale = instance.map_or(1.0, |i| i.price_scale);
850 let vcpus = instance.map_or(4.0, |i| i.vcpu.max(4.0));
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look851 // Its own CPU when the sandbox reports it; otherwise the average.
852 let parts = match a.cpu_seconds.filter(|cpu| cpu.is_finite() && *cpu >= 0.0) {
853 Some(cpu) => match (self.price("sandbox_base_second").await?, self.price("sandbox_cpu_second").await?) {
Fast pages, required checks on the branch, self-hosted runners, honest incidents854 (Some((base, _)), Some((vcpu, _))) => {
855 Some((keeper::run_cost(seconds, cpu.min(seconds as f64 * vcpus), base * base_scale, vcpu), cpu))
856 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look857 _ => None,
858 },
859 None => None,
860 };
Fast pages, required checks on the branch, self-hosted runners, honest incidents861 let cost = parts.map_or(seconds as f64 * cost_per_second * price_scale, |(cost, _)| cost).ceil() as i64;
Merge branch 'worktree-agent-a633ac0f7f66d419d'862 let (charge, terms_note, discount) = self.charged(&workspace, credits::with_margin(cost, self.margin_percent)).await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look863 let eligible = credits::eligible_for(a.kind, a.repo.as_deref());
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put864 let drawn = self.draw(&workspace, charge, &credits::month_of(&timestamp), &eligible).await?;
865 let charge = charge - drawn.total();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look866 let cpu_note = parts.map_or(String::new(), |(_, cpu)| format!(", {cpu:.0} vCPU-seconds"));
867 let description = format!("{}: {} of sandbox time{cpu_note}{terms_note}{}", a.description, duration(seconds), drawn.note());
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily868 // The price versions it was charged at (pricing.rs).
869 let meters: &[&str] = if parts.is_some() { &["sandbox_base_second", "sandbox_cpu_second"] } else { &["sandbox_second"] };
870 let mut versions = Vec::new();
871 for meter in meters {
872 versions.extend(self.version_now(meter).await?);
873 }
874 let price_version = versions.join(",");
Every sandbox is metered by the second875 self.db
876 .batch(vec![
877 self.db
878 .prepare(
879 "INSERT INTO ledger
880 (id, workspace, kind, amount_micros, description, repo, task,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily881 cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros, price_version)
882 VALUES (?, ?, 'usage', ?, ?, ?, 'sandbox', ?, ?, ?, 'g1t', ?, ?, ?, ?, ?)",
Every sandbox is metered by the second883 )
884 .bind(&[
885 new_id("led", now).into(),
886 workspace.as_str().into(),
887 (-(charge as f64)).into(),
888 description.as_str().into(),
889 optional(a.repo.as_deref()),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look890 (cost as f64).into(),
Every sandbox is metered by the second891 a.reference.as_str().into(),
892 timestamp.as_str().into(),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put893 (drawn.credit as f64).into(),
894 (drawn.trial as f64).into(),
895 (drawn.oss as f64).into(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look896 (drawn.given as f64).into(),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily897 optional(Some(price_version.as_str()).filter(|v| !v.is_empty())),
Every sandbox is metered by the second898 ])?,
899 self.db
900 .prepare(
901 "INSERT INTO accounts (workspace, balance_micros, created_at)
902 VALUES (?1, ?2, ?3)
903 ON CONFLICT (workspace) DO UPDATE SET balance_micros = balance_micros + ?2",
904 )
905 .bind(&[
906 workspace.as_str().into(),
907 (-(charge as f64)).into(),
908 timestamp.as_str().into(),
909 ])?,
910 ])
911 .await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'912 self.record_discount(&a.reference, discount).await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays913 self.count_spend(&workspace, cost, charge, &drawn).await;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look914 if let Some(reservation) = &a.reservation_id {
915 self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: cost }).await?;
916 }
Every sandbox is metered by the second917 Ok(Outcome::Ok(true))
918 }
919}
920
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look921/// Whether an amount may be prepaid: $25 at the least by card, and from
922/// $1,000 by bank transfer.
923pub(crate) fn prepay_amount(cents: u32, bank_transfer: bool) -> std::result::Result<(), String> {
924 let (min, max) = if bank_transfer { (MIN_BANK_TRANSFER_CENTS, MAX_BANK_TRANSFER_CENTS) } else { (MIN_TOP_UP_CENTS, MAX_TOP_UP_CENTS) };
925 if (min..=max).contains(&cents) {
926 return Ok(());
927 }
928 Err(if bank_transfer {
929 format!("Prepay between ${} and ${} by bank transfer.", min / 100, group(max / 100))
930 } else {
931 format!("Prepay between ${} and ${} by card; from $1,000, a bank transfer works too.", min / 100, group(max / 100))
932 })
933}
934
935/// `10,000` for 10000.
936fn group(n: u32) -> String {
937 let digits = n.to_string();
938 let mut out = String::new();
939 for (i, c) in digits.chars().enumerate() {
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept940 if i > 0 && (digits.len() - i).is_multiple_of(3) {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look941 out.push(',');
942 }
943 out.push(c);
944 }
945 out
946}
947
948#[cfg(test)]
Prices are what g1t pays plus 20%, from the first second949/// What `seconds` of sandbox time are charged at `price_per_second`, in
950/// millionths of a dollar: every second, rounded up to the next millionth.
951fn sandbox_charge(seconds: i64, price_per_second: f64) -> i64 {
952 (seconds as f64 * price_per_second).ceil() as i64
Every sandbox is metered by the second953}
954
955/// `1h 2m`, `3m 12s` or `40s`.
956fn duration(seconds: i64) -> String {
957 let (h, m, s) = (seconds / 3600, seconds % 3600 / 60, seconds % 60);
958 if h > 0 {
959 format!("{h}h {m}m")
960 } else if m > 0 {
961 format!("{m}m {s}s")
962 } else {
963 format!("{s}s")
964 }
965}
966
Billing accounts, terms and enterprises; g1t is no longer free967impl Billing {
968 /// What a workspace is charged for something that would be `base`:
969 /// nothing while g1t is free, or as its account's terms say. With a
970 /// note for the statement when it differs.
Merge branch 'worktree-agent-a633ac0f7f66d419d'971 /// A charge at cost plus the margin (`base`) on the account's terms:
972 /// what is charged, the note for the statement, and what a discount
973 /// gave away below `base`. That last is written on the entry
974 /// (`record_discount`) so the reconciliation counts it as given, never
975 /// as margin lost: a sold charge is worth at least its cost plus the
976 /// margin.
977 pub(crate) async fn charged(&self, workspace: &str, base: i64) -> Result<(i64, String, i64)> {
Billing accounts, terms and enterprises; g1t is no longer free978 if self.free {
Merge branch 'worktree-agent-a633ac0f7f66d419d'979 return Ok((0, " (free while g1t is being built out)".to_owned(), 0));
Billing accounts, terms and enterprises; g1t is no longer free980 }
981 let terms = self.terms_of(workspace).await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'982 let (charge, discount) = terms.discounted(base);
Billing accounts, terms and enterprises; g1t is no longer free983 let note = match terms.kind {
984 TermsKind::Comped => " (comped)".to_owned(),
985 TermsKind::Custom if terms.discount_percent > 0 && base > 0 => format!(" ({}% off)", terms.discount_percent),
986 _ => String::new(),
987 };
Merge branch 'worktree-agent-a633ac0f7f66d419d'988 Ok((charge, note, discount))
989 }
990
991 /// What a discount gave away on an entry, below cost plus the margin
992 /// (less than nothing on a correction down).
993 pub(crate) async fn record_discount(&self, reference: &str, micros: i64) -> Result<()> {
994 if micros == 0 {
995 return Ok(());
996 }
997 self.db
998 .prepare("UPDATE ledger SET discount_micros = ? WHERE reference = ?")
999 .bind(&[(micros as f64).into(), reference.into()])?
1000 .run()
1001 .await?;
1002 Ok(())
Billing accounts, terms and enterprises; g1t is no longer free1003 }
1004}
1005
Agents as a team: lifecycle, merge queue, billing and a new shell1006fn members_only<T>() -> Outcome<T> {
1007 Outcome::fail(
1008 FailureCode::Forbidden,
1009 "Only members can see a workspace's billing.",
1010 )
1011}
1012
Prices keep themselves current with what g1t pays1013impl Billing {
1014 fn from_env(env: &Env) -> Result<Self> {
1015 Ok(Billing {
1016 db: env.d1("DB")?,
1017 stripe: env
1018 .secret("STRIPE_SECRET_KEY")
1019 .ok()
1020 .map(|key| key.to_string())
1021 .filter(|key| !key.is_empty())
1022 .map(Stripe::new),
Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard1023 webhook_secret: env
1024 .secret("STRIPE_WEBHOOK_SECRET")
1025 .ok()
1026 .map(|secret| secret.to_string().trim().to_owned())
1027 .filter(|secret| !secret.is_empty()),
Prices keep themselves current with what g1t pays1028 margin_percent: env
1029 .var("MARGIN_PERCENT")
1030 .ok()
1031 .and_then(|percent| percent.to_string().parse().ok())
1032 .unwrap_or(20),
1033 free: env.var("FREE_WHILE_BUILDING").is_ok_and(|v| v.to_string() == "true"),
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1034 ceilings: limits::Ceilings::from_env(env),
Billing accounts, terms and enterprises; g1t is no longer free1035 prepaid_only: env.var("PREPAID_ONLY").is_ok_and(|v| v.to_string() == "true"),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1036 trials_on: {
1037 let plans = credits::Config::from_env(env);
1038 plans.trial_workspace_micros > 0 && plans.trial_monthly_pool_micros > 0
Prices keep themselves current with what g1t pays1039 },
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1040 plans: credits::Config::from_env(env),
1041 repos: env.service("REPOS").ok(),
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member1042 packages: env.service("PACKAGES").ok(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1043 identity: env.service("IDENTITY").ok(),
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays1044 caps: budget::Caps::from_env(env),
1045 env: env.clone(),
Prices keep themselves current with what g1t pays1046 })
1047 }
1048}
1049
1050#[event(scheduled)]
1051async fn scheduled(event: ScheduledEvent, env: Env, _ctx: ScheduleContext) {
1052 let Ok(billing) = Billing::from_env(&env) else {
1053 return;
1054 };
1055 let keeper = keeper::Keeper::from_env(&env);
1056 if let Err(error) = billing.settle_runs(&keeper).await {
1057 worker::console_error!("settling runs failed: {error}");
1058 }
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1059 // Stripe events billing never received, handled now.
1060 match billing.replay_events().await {
1061 Ok(done) => worker::console_log!("stripe replay: {done}"),
1062 Err(error) => worker::console_error!("replaying Stripe events failed: {error}"),
1063 }
Billing accounts, terms and enterprises; g1t is no longer free1064 if let Err(error) = billing.autopay().await {
1065 worker::console_error!("paying at the limit failed: {error}");
1066 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1067 // Last month's metered usage (scans, embeddings, storage) goes on the
1068 // ledger before the month is closed and invoiced.
1069 if let Err(error) = billing.charge_pending().await {
1070 worker::console_error!("charging last month's metered usage failed: {error}");
1071 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1072 if let Err(error) = billing.close_months().await {
1073 worker::console_error!("closing the month failed: {error}");
1074 }
Stripe webhooks, enterprise invoices, and sudo for both1075 if let Err(error) = billing.invoice_enterprises().await {
1076 worker::console_error!("invoicing enterprises failed: {error}");
1077 }
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays1078 // Comped budgets' alerts, and a tripped breaker staff were not told of.
1079 if let Err(error) = billing.watch_spend().await {
1080 worker::console_error!("watching g1t's own spend failed: {error}");
1081 }
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1082 if let Ok(identity) = env.service("IDENTITY")
1083 && let Err(error) = billing.warn_limits(&identity).await {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1084 worker::console_error!("warning owners failed: {error}");
1085 }
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1086 // Once a day: Stripe's endpoint kept listening to billing's events and
1087 // enabled, and saved cards and plans not read in a while read again.
1088 if event.cron() == keeper::DAILY {
Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard1089 match billing.keep_endpoint("billing").await {
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1090 Ok(done) => worker::console_log!("stripe endpoint: {done}"),
1091 Err(error) => worker::console_error!("keeping Stripe's endpoint failed: {error}"),
1092 }
1093 match billing.refresh_from_stripe().await {
1094 Ok(done) => worker::console_log!("stripe refresh: {done}"),
1095 Err(error) => worker::console_error!("refreshing from Stripe failed: {error}"),
1096 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1097 }
The keeper reads Cloudflare as it really answers1098 // Once a day, and at once if the costs were never checked: check every
1099 // cost against what Cloudflare billed.
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1100 if (event.cron() == keeper::DAILY || billing.never_checked().await.unwrap_or(false))
1101 && let Err(error) = billing.reconcile(&keeper).await {
Prices keep themselves current with what g1t pays1102 worker::console_error!("checking costs against Cloudflare failed: {error}");
1103 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1104 // Once a day: what Cloudflare charged, reconciled against what g1t
1105 // counted and charged; prices whose day has come; margin alerts
1106 // (margin.rs). After the keeper, so its proposals are in.
1107 if event.cron() == keeper::DAILY {
1108 match billing.costs_daily(&env, &keeper).await {
1109 Ok(run) => worker::console_log!("costs: {} lines, {} days, {} proposals, {} alerts", run.lines, run.days, run.proposals, run.alerts),
1110 Err(error) => worker::console_error!("reconciling costs failed: {error}"),
1111 }
1112 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1113 // Once a day: what each workspace's private repositories hold, its git
1114 // operations, Deployments plans from before the g1t plan set to end,
1115 // and old reservations cleared.
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1116 if event.cron() == keeper::DAILY {
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member1117 if let Err(error) = billing.measure_packages().await {
1118 worker::console_error!("measuring package storage failed: {error}");
1119 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1120 if let Err(error) = billing.measure_storage().await {
1121 worker::console_error!("measuring storage failed: {error}");
1122 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1123 if let Err(error) = billing.measure_git().await {
1124 worker::console_error!("measuring git operations failed: {error}");
1125 }
1126 if let Err(error) = billing.retire_deployments_plans().await {
1127 worker::console_error!("ending Deployments plans failed: {error}");
1128 }
1129 if let Err(error) = billing.sweep_reservations().await {
1130 worker::console_error!("clearing reservations failed: {error}");
1131 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1132 }
Prices keep themselves current with what g1t pays1133}
1134
Agents and memory, checks and conflicts, profiles, slug renames, custom domains1135/// Events from the bus, on billing's own queue: only a workspace's rename
1136/// matters here (see `rename`).
1137#[event(queue)]
1138async fn queue(batch: MessageBatch<g1t_contracts::events::Event>, env: Env, _ctx: Context) -> Result<()> {
1139 let billing = Billing::from_env(&env)?;
1140 let identity = env.service("IDENTITY").ok();
1141 for message in batch.messages()? {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1142 // A repository transferred: its share of the open-source pool this
1143 // month follows it. What it was charged stays with the workspace
1144 // it was charged to; usage from now on is charged to the new one.
1145 if g1t_kit::transfer::on_event(&env, &billing.db, message.body(), closing::TRANSFERRED).await? {
1146 message.ack();
1147 continue;
1148 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains1149 billing.on_event(identity.as_ref(), message.body()).await?;
1150 message.ack();
1151 }
1152 Ok(())
1153}
1154
Agents as a team: lifecycle, merge queue, billing and a new shell1155#[event(fetch)]
1156async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> {
1157 let Some(method) = rpc_method(&request) else {
1158 return Response::error("Not found", 404);
1159 };
Fast pages, required checks on the branch, self-hosted runners, honest incidents1160 // A replica near the caller when it asks for one (crates/kit/src/d1.rs);
1161 // what other services call (can_start, start_run) asks for none.
1162 let (db, served) = g1t_kit::d1::open(&env, "DB", &request)?;
Agents as a team: lifecycle, merge queue, billing and a new shell1163 let body: serde_json::Value = request.json().await?;
Fast pages, required checks on the branch, self-hosted runners, honest incidents1164 let mut billing = Billing::from_env(&env)?;
1165 billing.db = db;
1166 let answered = match method.as_str() {
Agents as a team: lifecycle, merge queue, billing and a new shell1167 "status" => reply(&billing.status()),
1168 "account" => reply(&billing.account(args(body)?).await?),
1169 "ledger" => reply(&billing.ledger(args(body)?).await?),
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request1170 "usage" => reply(&billing.usage(args(body)?).await?),
Mission control shows model usage, yours and the workspace's: tokens, cost, active days, cache share, each day, and the mix1171 "record_tokens" => reply(&billing.record_tokens(args(body)?).await?),
1172 "token_usage" => reply(&billing.token_usage(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1173 "checkout" => reply(&billing.checkout(args(body)?).await?),
1174 "confirm" => reply(&billing.confirm(args(body)?).await?),
1175 "can_start" => reply(&billing.can_start(args(body)?).await?),
A free allowance on g1t's models, so anyone can try its agents1176 "trial" => reply(&billing.trial(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1177 "start_run" => reply(&billing.start_run(args(body)?).await?),
1178 "finish_run" => reply(&billing.finish_run(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan1179 "features" => reply(&billing.features(args(body)?).await?),
1180 "subscribe" => reply(&billing.subscribe(args(body)?).await?),
1181 "confirm_subscription" => reply(&billing.confirm_subscription(args(body)?).await?),
1182 "cancel_subscription" => reply(&billing.cancel_subscription(args(body)?).await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1183 "close_workspace" => reply(&billing.close_workspace(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan1184 "has_feature" => reply(&billing.has_feature(args(body)?).await?),
1185 "charge_feature" => reply(&billing.charge_feature(args(body)?).await?),
Every sandbox is metered by the second1186 "record_sandbox" => reply(&billing.record_sandbox(args(body)?).await?),
Usage limits: unpaid usage can only go so far1187 "limit" => reply(&billing.limit(args(body)?).await?),
1188 "check_limit" => reply(&billing.check_limit(args(body)?).await?),
1189 "set_spend_limit" => reply(&billing.set_spend_limit(args(body)?).await?),
Prices keep themselves current with what g1t pays1190 "prices" => reply(&billing.prices().await?),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1191 "billing_portal" => reply(&billing.billing_portal(args(body)?).await?),
1192 "admin_billing_link" => reply(&billing.admin_billing_link(args(body)?).await?),
Stripe webhooks, enterprise invoices, and sudo for both1193 "admin_stripe" => reply(&billing.admin_stripe(args(body)?).await?),
1194 "admin_enterprise_billing" => reply(&billing.admin_enterprise_billing(args(body)?).await?),
1195 "admin_invoice_enterprise" => reply(&billing.admin_invoice_enterprise(args(body)?).await?),
1196 "stripe_webhook" => reply(&billing.stripe_webhook(args(body)?).await?),
Two limits, real invoices, trust that grows by itself, sales signals1197 "invoices" => reply(&billing.invoices(args(body)?).await?),
The statement is a month at a time, a line per kind of charge1198 "statement" => reply(&billing.statement(args(body)?).await?),
1199 "statement_entries" => reply(&billing.statement_entries(args(body)?).await?),
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas1200 "usage_meters" => reply(&billing.usage_meters(args(body)?).await?),
Two limits, real invoices, trust that grows by itself, sales signals1201 "admin_workspace_invoices" => {
1202 let a: AdminWorkspaceInvoicesArgs = args(body)?;
1203 reply(&billing.workspace_invoices(&a.workspace.to_lowercase()).await?)
1204 }
1205 "admin_signals" => reply(&billing.admin_signals(args(body)?).await?),
1206 "admin_overview" => reply(&billing.admin_overview(args(body)?).await?),
1207 "admin_sales" => reply(&billing.admin_sales(args(body)?).await?),
1208 "admin_set_sales" => reply(&billing.admin_set_sales(args(body)?).await?),
1209 "admin_add_note" => reply(&billing.admin_add_note(args(body)?).await?),
Billing lists every invoice and every staff change; signals carry follow-ups1210 "admin_invoices" => reply(&billing.admin_invoices(args(body)?).await?),
1211 "admin_audit" => reply(&billing.admin_audit(args(body)?).await?),
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member1212 // A staff change made in another service, for sudo's audit log:
1213 // identity's restores and purges of deleted workspaces.
1214 "admin_log" => {
1215 let a: AdminLogArgs = args(body)?;
1216 billing
1217 .audit(&accounts::own_account(&a.workspace), &a.action, &a.detail, &a.by)
1218 .await?;
1219 reply(&true)
1220 }
Prices keep themselves current with what g1t pays1221 "note_pending" => reply(&billing.note_pending(args(body)?).await?),
Billing accounts, terms and enterprises; g1t is no longer free1222 "admin_accounts" => reply(&billing.admin_accounts(args(body)?).await?),
1223 "admin_account" => reply(&billing.admin_account(args(body)?).await?),
1224 "admin_set_terms" => reply(&billing.admin_set_terms(args(body)?).await?),
1225 "admin_create_enterprise" => reply(&billing.admin_create_enterprise(args(body)?).await?),
1226 "admin_attach" => reply(&billing.admin_attach(args(body)?).await?),
1227 "admin_credit" => reply(&billing.admin_credit(args(body)?).await?),
sudo: a billing reset runs the costs analysis again so every figure is fresh; every submit button shows it is working (CSS only); no margin percentage on less than a cent sold1228 "admin_reset_billing" => reply(&billing.admin_reset_billing(&env, args(body)?).await?),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1229 "admin_set_allowances" => reply(&billing.admin_set_allowances(args(body)?).await?),
1230 "entitlements" => reply(&billing.entitlements(args(body)?).await?),
Audit logs are kept by plan: a week on free, 90 days on the plan, and what staff set for an account in sudo1231 "audit_retention" => reply(&billing.audit_retention(args(body)?).await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1232 "reserve" => reply(&billing.reserve(args(body)?).await?),
1233 "settle" => reply(&billing.settle_reservation(args(body)?).await?),
1234 "card_check" => reply(&billing.card_check(args(body)?).await?),
1235 "confirm_card_check" => reply(&billing.confirm_card_check(args(body)?).await?),
1236 "request_limit" => reply(&billing.request_limit(args(body)?).await?),
1237 "limit_requests" => reply(&billing.limit_requests(args(body)?).await?),
1238 "confirm_spike" => reply(&billing.confirm_spike(args(body)?).await?),
1239 "set_caps" => reply(&billing.set_caps(args(body)?).await?),
1240 "admin_limit_requests" => reply(&billing.admin_limit_requests(args(body)?).await?),
1241 "admin_decide_limit_request" => reply(&billing.admin_decide_limit_request(args(body)?).await?),
1242 "admin_overages" => reply(&billing.admin_overages(args(body)?).await?),
1243 "admin_goodwill" => reply(&billing.admin_goodwill(args(body)?).await?),
1244 "admin_velocity" => reply(&billing.admin_velocity(args(body)?).await?),
1245 "admin_record_payment" => reply(&billing.admin_record_payment(args(body)?).await?),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1246 "admin_costs" => reply(&billing.admin_costs(args(body)?, keeper::Keeper::from_env(&env).can_read_bill()).await?),
1247 "admin_cost_alerts" => reply(&billing.admin_cost_alerts(args(body)?).await?),
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays1248 "admin_spend_caps" => reply(&billing.spend_caps().await?),
1249 "admin_lift_breaker" => reply(&billing.admin_lift_breaker(args(body)?).await?),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1250 "admin_decide_proposal" => reply(&billing.admin_decide_proposal(args(body)?).await?),
1251 "admin_set_cost_settings" => reply(&billing.admin_set_cost_settings(args(body)?).await?),
1252 "admin_set_cost_mapping" => reply(&billing.admin_set_cost_mapping(args(body)?).await?),
1253 "admin_run_costs" => reply(&billing.admin_run_costs(&env, args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1254 _ => Response::error("Unknown method", 404),
Fast pages, required checks on the branch, self-hosted runners, honest incidents1255 };
1256 served.finish(answered)
Agents as a team: lifecycle, merge queue, billing and a new shell1257}
1258
1259#[cfg(test)]
1260mod tests {
1261 use super::*;
1262
1263 #[test]
1264 fn a_run_is_charged_its_cost_plus_the_margin() {
1265 // $0.05 at 20% is six cents.
1266 assert_eq!(charge_micros(0.05, 20), 60_000);
1267 assert_eq!(charge_micros(1.0, 20), 1_200_000);
1268 assert_eq!(charge_micros(0.05, 0), 50_000);
1269 }
1270
1271 #[test]
1272 fn fractions_of_a_millionth_round_up_and_nothing_costs_less_than_nothing() {
1273 assert_eq!(charge_micros(0.000_000_4, 20), 2);
1274 assert_eq!(charge_micros(0.0, 20), 0);
1275 assert_eq!(charge_micros(-3.0, 20), 0);
1276 }
1277
1278 #[test]
Prices are what g1t pays plus 20%, from the first second1279 fn sandbox_time_is_charged_from_the_first_second() {
1280 // 21 millionths a second at cost, plus 20%.
1281 let price = Price::price_for(21.0, 20);
1282 assert_eq!(sandbox_charge(1, price), 26);
1283 assert_eq!(sandbox_charge(60, price), 1_512);
1284 assert_eq!(sandbox_charge(0, price), 0);
Every sandbox is metered by the second1285 }
1286
1287 #[test]
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1288 fn prepaying_starts_at_twenty_five_dollars_and_bank_transfers_at_a_thousand() {
1289 assert!(prepay_amount(2_500, false).is_ok());
1290 assert!(prepay_amount(2_499, false).is_err());
1291 assert!(prepay_amount(10_000, false).is_ok());
1292 assert!(prepay_amount(1_000_000, false).is_ok());
1293 assert_eq!(prepay_amount(1_000_001, false).unwrap_err(), "Prepay between $25 and $10,000 by card; from $1,000, a bank transfer works too.");
1294 assert!(prepay_amount(99_999, true).is_err());
1295 assert!(prepay_amount(100_000, true).is_ok());
1296 }
1297
1298 #[test]
Every sandbox is metered by the second1299 fn durations_read_plainly() {
1300 assert_eq!(duration(40), "40s");
1301 assert_eq!(duration(192), "3m 12s");
1302 assert_eq!(duration(3720), "1h 2m");
1303 }
1304
1305 #[test]
Agents as a team: lifecycle, merge queue, billing and a new shell1306 fn an_absurd_cost_is_capped() {
1307 assert_eq!(charge_micros(1e9, 20), 120 * MICROS_PER_DOLLAR);
1308 }
1309}

This file's history is long; its oldest lines are credited to the oldest commit read.