g1t/services/billing/src/lib.rs

1,194 lines51,517 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;
Agents as a team: lifecycle, merge queue, billing and a new shell40mod stripe;
41
42use g1t_contracts::billing::*;
43use g1t_contracts::time::rfc3339;
44use g1t_contracts::{FailureCode, Outcome, Role, new_id};
Billing accounts, terms and enterprises; g1t is no longer free45use g1t_contracts::billing::TermsKind;
Agents as a team: lifecycle, merge queue, billing and a new shell46use g1t_kit::{args, now_ms, reply, rpc_method};
47use serde::Deserialize;
48use sha2::{Digest, Sha256};
49use worker::wasm_bindgen::JsValue;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains50use worker::{Context, D1Database, Env, MessageBatch, MessageExt, Request, Response, Result, ScheduleContext, ScheduledEvent, event};
Agents as a team: lifecycle, merge queue, billing and a new shell51
52use stripe::Stripe;
53
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look54/// Prepaying: $25 at the least; by card up to $10,000 at a time, and by
55/// bank transfer from $1,000 to $100,000.
56const MIN_TOP_UP_CENTS: u32 = 2_500;
57const MAX_TOP_UP_CENTS: u32 = 1_000_000;
58const MIN_BANK_TRANSFER_CENTS: u32 = 100_000;
59const MAX_BANK_TRANSFER_CENTS: u32 = 10_000_000;
Agents as a team: lifecycle, merge queue, billing and a new shell60const LEDGER_PAGE: u32 = 100;
61/// A run's reported cost is believed up to this much. A sandbox cannot
62/// spend more in the time it has, so anything above is a fault.
63const MAX_RUN_COST_USD: f64 = 100.0;
64
65/// What a run is charged: its cost plus the margin, rounded up to a whole
66/// millionth of a dollar.
67pub fn charge_micros(cost_usd: f64, margin_percent: u32) -> i64 {
68 let cost_micros = (cost_usd.clamp(0.0, MAX_RUN_COST_USD) * MICROS_PER_DOLLAR as f64).ceil();
69 (cost_micros * f64::from(100 + margin_percent) / 100.0).ceil() as i64
70}
71
72fn hash(token: &str) -> String {
73 hex::encode(Sha256::digest(token.as_bytes()))
74}
75
76fn optional(value: Option<&str>) -> JsValue {
77 value.map_or(JsValue::NULL, JsValue::from)
78}
79
80#[derive(Deserialize)]
81struct AccountRow {
82 balance_micros: i64,
83 customer_id: Option<String>,
84}
85
86#[derive(Deserialize)]
87struct LedgerRow {
88 id: String,
89 kind: EntryKind,
90 amount_micros: i64,
91 description: String,
92 repo: Option<String>,
93 number: Option<u32>,
94 task: Option<String>,
95 model: Option<String>,
96 created_by: Option<String>,
97 created_at: String,
Integrations: your own model provider, alerts that open issues, tickets agents read98 billed_to: Option<String>,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace99 #[serde(default)]
100 workspace: Option<String>,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put101 #[serde(default)]
102 credit_micros: Option<i64>,
103 #[serde(default)]
104 trial_micros: Option<i64>,
105 #[serde(default)]
106 oss_micros: Option<i64>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look107 #[serde(default)]
108 given_micros: Option<i64>,
Agents as a team: lifecycle, merge queue, billing and a new shell109}
110
111impl From<LedgerRow> for LedgerEntry {
112 fn from(row: LedgerRow) -> Self {
113 LedgerEntry {
114 id: row.id,
115 kind: row.kind,
116 amount_micros: row.amount_micros,
117 description: row.description,
118 repo: row.repo,
119 number: row.number,
120 task: row.task,
121 model: row.model,
Integrations: your own model provider, alerts that open issues, tickets agents read122 billed_to: row.billed_to.unwrap_or_else(|| "g1t".to_owned()),
Agents as a team: lifecycle, merge queue, billing and a new shell123 created_by: row.created_by,
124 created_at: row.created_at,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace125 workspace: row.workspace,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put126 credit_micros: row.credit_micros.unwrap_or(0),
127 trial_micros: row.trial_micros.unwrap_or(0),
128 oss_micros: row.oss_micros.unwrap_or(0),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look129 given_micros: row.given_micros.unwrap_or(0),
Agents as a team: lifecycle, merge queue, billing and a new shell130 }
131 }
132}
133
134#[derive(Deserialize)]
135struct RunRow {
136 workspace: String,
137 repo: String,
138 number: u32,
139 task: String,
140 model: String,
141 token_hash: String,
Integrations: your own model provider, alerts that open issues, tickets agents read142 billed_to: Option<String>,
143}
144
145impl RunRow {
146 fn own_provider(&self) -> bool {
147 self.billed_to.as_deref() == Some("workspace")
148 }
Agents as a team: lifecycle, merge queue, billing and a new shell149}
150
151#[derive(Deserialize)]
152struct CheckoutRow {
153 workspace: String,
154 created_by: String,
155}
156
157/// A row an `UPDATE … RETURNING` touched.
158#[derive(Deserialize)]
159struct Touched {
160 #[allow(dead_code)]
161 id: String,
162}
163
164struct Billing {
165 db: D1Database,
166 /// Absent when no card processor is configured.
167 stripe: Option<Stripe>,
168 margin_percent: u32,
Free while g1t is being built out; agents can check out their own forks169 /// While g1t is being built out, nothing is charged (`FREE_WHILE_BUILDING`).
170 free: bool,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put171 /// Whether new workspaces get trial credit (`TRIAL_WORKSPACE_MICROS`
172 /// and `TRIAL_MONTHLY_POOL_MICROS` both above zero).
173 trials_on: bool,
174 /// The plans' and pools' numbers; see `credits`.
175 plans: credits::Config,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look176 /// The repos service: which repositories are public, what private ones
177 /// 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 put178 repos: Option<worker::Fetcher>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look179 /// The identity service, which emails owners. Absent where it is not
180 /// bound.
181 identity: Option<worker::Fetcher>,
Usage limits: unpaid usage can only go so far182 /// How far unpaid usage may go; see `limits`.
183 ceilings: limits::Ceilings,
Billing accounts, terms and enterprises; g1t is no longer free184 /// `PREPAID_ONLY`: the old rule, that agents need credit first.
185 prepaid_only: bool,
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays186 /// The caps on what g1t pays for itself; see `budget`.
187 caps: budget::Caps,
188 /// The worker's bindings, for emailing staff (`EMAIL`).
189 env: Env,
A free allowance on g1t's models, so anyone can try its agents190}
191
Agents as a team: lifecycle, merge queue, billing and a new shell192impl Billing {
193 fn status(&self) -> Status {
194 Status {
195 enabled: self.stripe.is_some(),
196 live: self.stripe.as_ref().is_some_and(Stripe::live),
Free while g1t is being built out; agents can check out their own forks197 free: self.free,
Agents as a team: lifecycle, merge queue, billing and a new shell198 }
199 }
200
201 async fn row(&self, workspace: &str) -> Result<Option<AccountRow>> {
202 self.db
203 .prepare("SELECT balance_micros, customer_id FROM accounts WHERE workspace = ?")
204 .bind(&[workspace.into()])?
205 .first::<AccountRow>(None)
206 .await
207 }
208
209 async fn standing(&self, workspace: &str) -> Result<Account> {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace210 let row = self.row(workspace).await?;
211 let card = match (&self.stripe, row.as_ref().and_then(|row| row.customer_id.as_deref())) {
212 (Some(stripe), Some(customer)) => stripe.card(customer).await.ok().flatten().map(|card| Card {
213 brand: card.brand,
214 last4: card.last4,
215 exp_month: card.exp_month,
216 exp_year: card.exp_year,
217 }),
218 _ => None,
219 };
Agents as a team: lifecycle, merge queue, billing and a new shell220 Ok(Account {
221 workspace: workspace.to_owned(),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace222 balance_micros: row.map_or(0, |row| row.balance_micros),
Agents as a team: lifecycle, merge queue, billing and a new shell223 status: self.status(),
224 margin_percent: self.margin_percent,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace225 card,
Agents as a team: lifecycle, merge queue, billing and a new shell226 })
227 }
228
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace229 /// The workspace's customer at Stripe, made the first time one is needed.
230 pub(crate) async fn customer_for(&self, workspace: &str) -> Result<String> {
231 let Some(stripe) = &self.stripe else {
232 return Err(worker::Error::RustError("payments are not set up".into()));
233 };
234 if let Some(customer) = self.row(workspace).await?.and_then(|row| row.customer_id) {
235 return Ok(customer);
236 }
237 let customer = stripe.create_customer(workspace).await?;
238 self.db
239 .prepare(
240 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at) VALUES (?1, 0, ?2, ?3)
241 ON CONFLICT (workspace) DO UPDATE SET customer_id = ?2",
242 )
243 .bind(&[workspace.into(), customer.as_str().into(), rfc3339(now_ms()).into()])?
244 .run()
245 .await?;
246 Ok(customer)
247 }
248
249 /// Stripe's hosted billing page for the workspace. Owners only.
250 async fn billing_portal(&self, a: BillingPortalArgs) -> Result<Outcome<Checkout>> {
251 let workspace = a.workspace.to_lowercase();
252 if a.actor.role_in(&workspace) != Some(Role::Owner) {
253 return Ok(Outcome::fail(FailureCode::Forbidden, "Only an owner can manage the workspace's billing."));
254 }
255 let Some(stripe) = &self.stripe else {
256 return Ok(Outcome::fail(FailureCode::Conflict, "Payments are not set up on this g1t."));
257 };
258 let customer = match self.customer_for(&workspace).await {
259 Ok(customer) => customer,
260 Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe could not be reached: {error}"))),
261 };
262 match stripe.portal_session(&customer, &a.return_url).await {
263 Ok(url) => Ok(Outcome::Ok(Checkout { url })),
264 Err(error) if stripe::is_missing(&error) => {
265 // The customer was removed at Stripe: a new one next time.
266 self.forget_customer(&workspace).await?;
267 Ok(Outcome::fail(FailureCode::Conflict, "Stripe no longer had this workspace's customer. Try again."))
268 }
269 Err(error) => Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe's billing page could not be opened: {error}"))),
270 }
271 }
272
Agents as a team: lifecycle, merge queue, billing and a new shell273 /// Adds a ledger entry and moves the balance by the same amount, as
274 /// one write.
275 #[allow(clippy::too_many_arguments)]
276 async fn enter(
277 &self,
278 workspace: &str,
279 kind: EntryKind,
280 amount_micros: i64,
281 description: &str,
282 reference: &str,
283 run: Option<&RunRow>,
284 cost_micros: Option<i64>,
285 created_by: Option<&str>,
286 customer: Option<&str>,
287 ) -> Result<()> {
288 let now = now_ms();
289 let timestamp = rfc3339(now);
290 let kind = match kind {
291 EntryKind::TopUp => "top_up",
292 EntryKind::Usage => "usage",
293 };
294 self.db
295 .batch(vec![
296 self.db
297 .prepare(
298 "INSERT INTO ledger
299 (id, workspace, kind, amount_micros, description, repo, number, task,
Integrations: your own model provider, alerts that open issues, tickets agents read300 model, cost_micros, reference, created_by, created_at, billed_to)
301 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
Agents as a team: lifecycle, merge queue, billing and a new shell302 )
303 .bind(&[
304 new_id("led", now).into(),
305 workspace.into(),
306 kind.into(),
307 // D1 takes numbers as doubles, which hold every
308 // amount this service will see exactly.
309 (amount_micros as f64).into(),
310 description.into(),
311 optional(run.map(|run| run.repo.as_str())),
312 run.map_or(JsValue::NULL, |run| run.number.into()),
313 optional(run.map(|run| run.task.as_str())),
314 optional(run.map(|run| run.model.as_str())),
315 cost_micros.map_or(JsValue::NULL, |cost| (cost as f64).into()),
316 reference.into(),
317 optional(created_by),
318 timestamp.as_str().into(),
Integrations: your own model provider, alerts that open issues, tickets agents read319 run.map_or("g1t", |run| if run.own_provider() { "workspace" } else { "g1t" }).into(),
Agents as a team: lifecycle, merge queue, billing and a new shell320 ])?,
321 self.db
322 .prepare(
323 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at)
324 VALUES (?1, ?2, ?3, ?4)
325 ON CONFLICT (workspace) DO UPDATE SET
326 balance_micros = balance_micros + ?2,
327 customer_id = COALESCE(?3, customer_id)",
328 )
329 .bind(&[
330 workspace.into(),
331 (amount_micros as f64).into(),
332 optional(customer),
333 timestamp.as_str().into(),
334 ])?,
335 ])
336 .await?;
Billing accounts, terms and enterprises; g1t is no longer free337 // Money in clears a card declined at the limit.
338 if kind == "top_up" {
339 self.db
340 .prepare("UPDATE limits SET autopay_failed_at = NULL, autopay_error = NULL WHERE workspace = ?")
341 .bind(&[workspace.into()])?
342 .run()
343 .await?;
344 }
Agents as a team: lifecycle, merge queue, billing and a new shell345 Ok(())
346 }
347
348 async fn account(&self, a: AccountArgs) -> Result<Outcome<Account>> {
349 let workspace = a.workspace.to_lowercase();
350 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
351 return Ok(members_only());
352 }
353 Ok(Outcome::Ok(self.standing(&workspace).await?))
354 }
355
356 async fn ledger(&self, a: AccountArgs) -> Result<Outcome<Vec<LedgerEntry>>> {
357 let workspace = a.workspace.to_lowercase();
358 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
359 return Ok(members_only());
360 }
361 let rows = self
362 .db
363 .prepare("SELECT * FROM ledger WHERE workspace = ? ORDER BY id DESC LIMIT ?")
364 .bind(&[workspace.into(), LEDGER_PAGE.into()])?
365 .all()
366 .await?
367 .results::<LedgerRow>()?;
368 Ok(Outcome::Ok(
369 rows.into_iter().map(LedgerEntry::from).collect(),
370 ))
371 }
372
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request373 async fn usage(&self, a: UsageArgs) -> Result<Outcome<Usage>> {
374 let workspace = a.workspace.to_lowercase();
375 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
376 return Ok(members_only());
377 }
378 #[derive(serde::Deserialize)]
379 struct SliceRow {
380 key: Option<String>,
381 micros: Option<i64>,
382 runs: Option<u32>,
383 }
Usage while free is shown at cost; agents get rustfmt and clippy384 // While nothing is charged, what was used is what there is to show.
385 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 request386 let slices = |key: &str, limit: u32| {
387 format!(
Usage while free is shown at cost; agents get rustfmt and clippy388 "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 request389 WHERE workspace = ?1 AND kind = 'usage' AND created_at >= ?2
390 GROUP BY 1 ORDER BY micros DESC LIMIT {limit}"
391 )
392 };
393 let query = |sql: String| {
394 let db = &self.db;
395 let workspace = workspace.clone();
396 let since = a.since.clone();
397 async move {
398 let rows = db
399 .prepare(sql)
400 .bind(&[workspace.into(), since.into()])?
401 .all()
402 .await?
403 .results::<SliceRow>()?;
404 Ok::<Vec<UsageSlice>, worker::Error>(
405 rows.into_iter()
406 .map(|row| UsageSlice {
407 key: row.key.unwrap_or_else(|| "other".to_owned()),
408 micros: row.micros.unwrap_or_default(),
409 runs: row.runs.unwrap_or_default(),
410 })
411 .collect(),
412 )
413 }
414 };
415 #[derive(serde::Deserialize)]
416 struct Totals {
417 spent: Option<i64>,
418 cost: Option<i64>,
Integrations: your own model provider, alerts that open issues, tickets agents read419 provider: Option<i64>,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request420 runs: Option<u32>,
421 added: Option<i64>,
422 }
423 let totals = self
424 .db
425 .prepare(
426 "SELECT
427 -SUM(CASE WHEN kind = 'usage' THEN amount_micros END) AS spent,
Integrations: your own model provider, alerts that open issues, tickets agents read428 SUM(CASE WHEN kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' THEN cost_micros END) AS cost,
429 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 request430 SUM(CASE WHEN kind = 'usage' THEN 1 ELSE 0 END) AS runs,
431 SUM(CASE WHEN kind = 'top_up' THEN amount_micros END) AS added
432 FROM ledger WHERE workspace = ?1 AND created_at >= ?2",
433 )
434 .bind(&[workspace.as_str().into(), a.since.as_str().into()])?
435 .first::<Totals>(None)
436 .await?;
437 let totals = totals.unwrap_or(Totals {
438 spent: None,
439 cost: None,
Integrations: your own model provider, alerts that open issues, tickets agents read440 provider: None,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request441 runs: None,
442 added: None,
443 });
444 Ok(Outcome::Ok(Usage {
445 spent_micros: totals.spent.unwrap_or_default(),
446 cost_micros: totals.cost.unwrap_or_default(),
Integrations: your own model provider, alerts that open issues, tickets agents read447 provider_micros: totals.provider.unwrap_or_default(),
Usage while free is shown at cost; agents get rustfmt and clippy448 used_micros: totals.cost.unwrap_or_default() + totals.provider.unwrap_or_default(),
449 free: self.free,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request450 runs: totals.runs.unwrap_or_default(),
451 added_micros: totals.added.unwrap_or_default(),
452 by_day: query(slices("substr(created_at, 1, 10) || '/' || COALESCE(task, 'other')", 400)).await?,
453 by_task: query(slices("task", 20)).await?,
454 by_repo: query(slices("repo", 20)).await?,
455 by_pull: query(slices("repo || '#' || number", 10)).await?,
456 by_model: query(slices("model", 10)).await?,
457 since: a.since,
458 }))
459 }
460
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look461 /// `checkout`: prepays usage, by card or (from $1,000) bank transfer.
Agents as a team: lifecycle, merge queue, billing and a new shell462 async fn checkout(&self, a: CheckoutArgs) -> Result<Outcome<Checkout>> {
463 let workspace = a.workspace.to_lowercase();
464 if a.actor.role_in(&workspace) != Some(Role::Owner) {
465 return Ok(Outcome::fail(
466 FailureCode::Forbidden,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look467 "Only an owner can prepay for a workspace.",
Agents as a team: lifecycle, merge queue, billing and a new shell468 ));
469 }
470 let Some(stripe) = &self.stripe else {
471 return Ok(Outcome::fail(
472 FailureCode::Conflict,
473 "Payments are not set up on this g1t yet.",
474 ));
475 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look476 let bank_transfer = a.method.as_deref() == Some("bank_transfer");
477 if let Err(why) = prepay_amount(a.amount_cents, bank_transfer) {
478 return Ok(Outcome::fail(FailureCode::Invalid, why));
Agents as a team: lifecycle, merge queue, billing and a new shell479 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look480 // A bank transfer needs a customer for its account details.
481 let customer = if bank_transfer {
482 match self.customer_for(&workspace).await {
483 Ok(customer) => Some(customer),
484 Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, format!("Stripe could not be reached: {error}"))),
485 }
486 } else {
487 self.row(&workspace).await?.and_then(|row| row.customer_id)
488 };
Project dependencies: addresses, preview stacks, Affects, and agents who know489 let session = match stripe
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look490 .start_checkout(&workspace, a.amount_cents, customer.as_deref(), &a.return_url, bank_transfer)
Project dependencies: addresses, preview stacks, Affects, and agents who know491 .await
492 {
493 Ok(session) => session,
494 // A customer saved under another Stripe account: start afresh.
495 Err(error) if customer.is_some() && stripe::is_missing(&error) => {
496 self.forget_customer(&workspace).await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look497 let customer = if bank_transfer { Some(self.customer_for(&workspace).await?) } else { None };
498 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 know499 }
500 Err(error) => return Err(error),
501 };
Agents as a team: lifecycle, merge queue, billing and a new shell502 let Some(url) = session.url else {
503 return Err(worker::Error::RustError(
504 "the card processor returned no payment page".into(),
505 ));
506 };
507 self.db
508 .prepare(
509 "INSERT INTO checkouts (id, workspace, amount_cents, created_by, created_at)
510 VALUES (?, ?, ?, ?, ?)",
511 )
512 .bind(&[
513 session.id.into(),
514 workspace.into(),
515 a.amount_cents.into(),
516 a.actor.username.into(),
517 rfc3339(now_ms()).into(),
518 ])?
519 .run()
520 .await?;
521 Ok(Outcome::Ok(Checkout { url }))
522 }
523
524 /// Credits a payment if the processor says it was made and it has not
525 /// been credited before. The amount credited is what the processor
526 /// says was paid, not what anyone here remembers asking for.
527 async fn confirm(&self, a: ConfirmArgs) -> Result<Outcome<Account>> {
528 let workspace = a.workspace.to_lowercase();
529 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
530 return Ok(members_only());
531 }
532 let (Some(stripe), Some(checkout)) = (
533 &self.stripe,
534 self.db
535 .prepare(
536 "SELECT workspace, created_by FROM checkouts
537 WHERE id = ? AND workspace = ? AND status = 'open'",
538 )
539 .bind(&[a.session.as_str().into(), workspace.as_str().into()])?
540 .first::<CheckoutRow>(None)
541 .await?,
542 ) else {
543 // Unknown, someone else's, or already credited: nothing to do.
544 return Ok(Outcome::Ok(self.standing(&workspace).await?));
545 };
546 let session = stripe.session(&a.session).await?;
547 let paid = session
548 .amount_total
549 .filter(|_| session.payment_status == "paid");
550 if let Some(cents) = paid {
551 // Only whoever flips it from open to paid enters the credit.
552 let claimed = self
553 .db
554 .prepare(
555 "UPDATE checkouts SET status = 'paid' WHERE id = ? AND status = 'open'
556 RETURNING id",
557 )
558 .bind(&[a.session.as_str().into()])?
559 .first::<Touched>(None)
560 .await?;
561 if claimed.is_some() {
562 self.enter(
563 &checkout.workspace,
564 EntryKind::TopUp,
565 i64::from(cents) * MICROS_PER_DOLLAR / 100,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look566 "Paid in advance",
Agents as a team: lifecycle, merge queue, billing and a new shell567 &session.id,
568 None,
569 None,
570 Some(&checkout.created_by),
571 session.customer.as_deref(),
572 )
573 .await?;
574 }
575 }
576 Ok(Outcome::Ok(self.standing(&workspace).await?))
577 }
578
Project dependencies: addresses, preview stacks, Affects, and agents who know579 /// Drops a saved customer the card processor no longer knows.
580 pub(crate) async fn forget_customer(&self, workspace: &str) -> Result<()> {
581 self.db
582 .prepare("UPDATE accounts SET customer_id = NULL WHERE workspace = ?")
583 .bind(&[workspace.into()])?
584 .run()
585 .await?;
586 Ok(())
587 }
588
Agents as a team: lifecycle, merge queue, billing and a new shell589 /// A refusal if the workspace has no credit to start an agent with.
590 async fn out_of_credit<T>(&self, workspace: &str) -> Result<Option<Outcome<T>>> {
Billing accounts, terms and enterprises; g1t is no longer free591 // Billing is postpaid: usage limits decide whether work starts
592 // (see `limits`), and credit is a prepayment that lowers what is
593 // owed. A balance no longer has to be positive to start.
594 if self.free || !self.prepaid_only {
Free while g1t is being built out; agents can check out their own forks595 return Ok(None);
596 }
Agents as a team: lifecycle, merge queue, billing and a new shell597 let balance = self
598 .row(workspace)
599 .await?
600 .map_or(0, |row| row.balance_micros);
601 Ok((balance <= 0).then(|| {
602 Outcome::fail(
603 FailureCode::PaymentRequired,
604 format!(
605 "The {workspace} workspace has no agent credit. An owner can add some under Billing on the workspace's page."
606 ),
607 )
608 }))
Billing accounts, terms and enterprises; g1t is no longer free609 }
610
Agents as a team: lifecycle, merge queue, billing and a new shell611 async fn can_start(&self, a: CanStartArgs) -> Result<Outcome<bool>> {
612 if self.stripe.is_none() {
613 return Ok(Outcome::Ok(true));
614 }
Usage limits: unpaid usage can only go so far615 if let Some(stopped) = self.stopped(&a.workspace).await? {
616 return Ok(stopped);
617 }
Agents as a team: lifecycle, merge queue, billing and a new shell618 Ok(self
619 .out_of_credit(&a.workspace.to_lowercase())
620 .await?
621 .unwrap_or(Outcome::Ok(true)))
622 }
623
624 async fn start_run(&self, a: StartRunArgs) -> Result<Outcome<Option<RunTicket>>> {
625 if self.stripe.is_none() {
626 return Ok(Outcome::Ok(None));
627 }
628 let workspace = a.workspace.to_lowercase();
Usage limits: unpaid usage can only go so far629 if let Some(stopped) = self.stopped(&workspace).await? {
630 return Ok(stopped);
631 }
Agents as a team: lifecycle, merge queue, billing and a new shell632 if let Some(refused) = self.out_of_credit(&workspace).await? {
633 return Ok(refused);
634 }
635 let now = now_ms();
636 let run_id = new_id("run", now);
637 let mut bytes = [0u8; 32];
638 getrandom::getrandom(&mut bytes).expect("no source of randomness");
639 let token = hex::encode(bytes);
640 self.db
641 .prepare(
Prices keep themselves current with what g1t pays642 "INSERT INTO runs (id, workspace, repo, number, task, model, token_hash, created_at, billed_to, session_id)
643 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
Agents as a team: lifecycle, merge queue, billing and a new shell644 )
645 .bind(&[
646 run_id.as_str().into(),
647 workspace.into(),
648 format!("{}/{}", a.repo.namespace, a.repo.name).into(),
649 a.number.into(),
650 a.task.into(),
651 a.model.into(),
652 hash(&token).into(),
653 rfc3339(now).into(),
Integrations: your own model provider, alerts that open issues, tickets agents read654 if a.billed_to == "workspace" { "workspace" } else { "g1t" }.into(),
Prices keep themselves current with what g1t pays655 optional(a.session.as_deref().filter(|_| a.billed_to != "workspace")),
Agents as a team: lifecycle, merge queue, billing and a new shell656 ])?
657 .run()
658 .await?;
659 Ok(Outcome::Ok(Some(RunTicket { run_id, token })))
660 }
661
662 async fn finish_run(&self, a: FinishRunArgs) -> Result<Outcome<bool>> {
663 let run = self
664 .db
665 .prepare(
Integrations: your own model provider, alerts that open issues, tickets agents read666 "SELECT workspace, repo, number, task, model, token_hash, billed_to FROM runs
Agents as a team: lifecycle, merge queue, billing and a new shell667 WHERE id = ? AND finished_at IS NULL",
668 )
669 .bind(&[a.run_id.as_str().into()])?
670 .first::<RunRow>(None)
671 .await?;
672 let Some(run) = run.filter(|run| run.token_hash == hash(&a.token)) else {
673 return Ok(Outcome::fail(FailureCode::NotFound, "Run not found."));
674 };
675 if !a.cost_usd.is_finite() || a.cost_usd < 0.0 {
676 return Ok(Outcome::fail(FailureCode::Invalid, "That is not a cost."));
677 }
678 // Only whoever closes the run charges for it.
679 let claimed = self
680 .db
681 .prepare(
682 "UPDATE runs SET finished_at = ? WHERE id = ? AND finished_at IS NULL RETURNING id",
683 )
684 .bind(&[rfc3339(now_ms()).into(), a.run_id.as_str().into()])?
685 .first::<Touched>(None)
686 .await?;
687 if claimed.is_none() {
688 return Ok(Outcome::Ok(false));
689 }
Prices are what g1t pays plus 20%, from the first second690 // On the workspace's own provider, the model was paid for there,
691 // and the run's sandbox time is recorded on its own: nothing more
692 // to charge.
693 if run.own_provider() {
694 return Ok(Outcome::Ok(true));
695 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look696 // Its cost plus the margin, on the account's terms; then the plan's
697 // included usage and the trial credit pay what they can, and g1t
698 // covers a free workspace's overrun (see `credits`). Agents are
699 // 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 put700 let base = charge_micros(a.cost_usd, self.margin_percent);
Billing accounts, terms and enterprises; g1t is no longer free701 let (charge, terms_note) = self.charged(&run.workspace, base).await?;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put702 let month = credits::month_of(&rfc3339(now_ms()));
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look703 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 put704 let drawn = self.draw(&run.workspace, charge, &month, &eligible).await?;
Integrations: your own model provider, alerts that open issues, tickets agents read705 let mut description = match run.task.as_str() {
Agents as a team: lifecycle, merge queue, billing and a new shell706 "plan" => format!("Planning for {}", run.repo),
707 "review" => format!("Review of {}#{}", run.repo, run.number),
708 "update" => format!("Catching up {}#{}", run.repo, run.number),
709 _ => format!("Work on {}#{}", run.repo, run.number),
710 };
Billing accounts, terms and enterprises; g1t is no longer free711 description.push_str(&terms_note);
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put712 description.push_str(&drawn.note());
Agents as a team: lifecycle, merge queue, billing and a new shell713 self.enter(
714 &run.workspace,
715 EntryKind::Usage,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put716 -(charge - drawn.total()),
Agents as a team: lifecycle, merge queue, billing and a new shell717 &description,
718 &a.run_id,
719 Some(&run),
720 Some(charge_micros(a.cost_usd, 0)),
721 None,
722 None,
723 )
724 .await?;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put725 self.record_drawn(&a.run_id, &drawn).await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays726 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 shell727 Ok(Outcome::Ok(true))
728 }
729}
730
Every sandbox is metered by the second731impl Billing {
Prices are what g1t pays plus 20%, from the first second732 /// 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 look733 /// second, from the first, at the price book's price; on its own CPU
734 /// when it reports it. Settles its reservation, if it names one.
Every sandbox is metered by the second735 async fn record_sandbox(&self, a: RecordSandboxArgs) -> Result<Outcome<bool>> {
Fast pages, required checks on the branch, self-hosted runners, honest incidents736 // Self-hosted time is recorded wherever g1t runs, for its minutes;
737 // anything else only where there is a bill to put it on.
738 if (self.stripe.is_none() && !a.self_hosted) || a.seconds == 0 {
Every sandbox is metered by the second739 return Ok(Outcome::Ok(false));
740 }
741 let workspace = a.workspace.to_lowercase();
742 let seen = self
743 .db
744 .prepare("SELECT id FROM ledger WHERE reference = ?")
745 .bind(&[a.reference.as_str().into()])?
746 .first::<Touched>(None)
747 .await?;
748 if seen.is_some() {
749 return Ok(Outcome::Ok(false));
750 }
751 let now = now_ms();
752 let timestamp = rfc3339(now);
753 let seconds = i64::from(a.seconds);
Fast pages, required checks on the branch, self-hosted runners, honest incidents754 // On the workspace's own machine: its minutes go on usage, at $0,
755 // and whatever was reserved for it is given back.
756 if a.self_hosted {
757 let description = format!("{}: {} of self-hosted runner time, $0", a.description, duration(seconds));
758 self.db
759 .prepare(
760 "INSERT INTO ledger
761 (id, workspace, kind, amount_micros, description, repo, task,
762 cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros)
763 VALUES (?, ?, 'usage', 0, ?, ?, 'self_hosted', 0, ?, ?, 'workspace', 0, 0, 0, 0)",
764 )
765 .bind(&[
766 new_id("led", now).into(),
767 workspace.as_str().into(),
768 description.as_str().into(),
769 optional(a.repo.as_deref()),
770 a.reference.as_str().into(),
771 timestamp.as_str().into(),
772 ])?
773 .run()
774 .await?;
775 if let Some(reservation) = &a.reservation_id {
776 self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: 0 }).await?;
777 }
778 return Ok(Outcome::Ok(true));
779 }
Prices are what g1t pays plus 20%, from the first second780 // From the price book, which follows what Cloudflare bills g1t. A
781 // sandbox is the same container as a build, so without a row it is
782 // a build second's cost plus the margin.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look783 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 quotas784 let cost = deployment_costs::MICROS_PER_BUILD_SECOND as f64;
Prices are what g1t pays plus 20%, from the first second785 (cost, Price::price_for(cost, self.margin_percent))
786 });
Fast pages, required checks on the branch, self-hosted runners, honest incidents787 // A larger machine (`runs-on: g1t-4core`): its memory and disk
788 // cost more each second, and without its own CPU it is priced at
789 // its vCPUs as busy as the standard machine's.
790 let instance = a.instance.as_deref().and_then(g1t_contracts::actions::instance_named);
791 let base_scale = instance.map_or(1.0, |i| keeper::base_scale(i.memory_gib, i.disk_gb));
792 let price_scale = instance.map_or(1.0, |i| i.price_scale);
793 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 look794 // Its own CPU when the sandbox reports it; otherwise the average.
795 let parts = match a.cpu_seconds.filter(|cpu| cpu.is_finite() && *cpu >= 0.0) {
796 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 incidents797 (Some((base, _)), Some((vcpu, _))) => {
798 Some((keeper::run_cost(seconds, cpu.min(seconds as f64 * vcpus), base * base_scale, vcpu), cpu))
799 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look800 _ => None,
801 },
802 None => None,
803 };
Fast pages, required checks on the branch, self-hosted runners, honest incidents804 let cost = parts.map_or(seconds as f64 * cost_per_second * price_scale, |(cost, _)| cost).ceil() as i64;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look805 let (charge, terms_note) = self.charged(&workspace, credits::with_margin(cost, self.margin_percent)).await?;
806 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 put807 let drawn = self.draw(&workspace, charge, &credits::month_of(&timestamp), &eligible).await?;
808 let charge = charge - drawn.total();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look809 let cpu_note = parts.map_or(String::new(), |(_, cpu)| format!(", {cpu:.0} vCPU-seconds"));
810 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 daily811 // The price versions it was charged at (pricing.rs).
812 let meters: &[&str] = if parts.is_some() { &["sandbox_base_second", "sandbox_cpu_second"] } else { &["sandbox_second"] };
813 let mut versions = Vec::new();
814 for meter in meters {
815 versions.extend(self.version_now(meter).await?);
816 }
817 let price_version = versions.join(",");
Every sandbox is metered by the second818 self.db
819 .batch(vec![
820 self.db
821 .prepare(
822 "INSERT INTO ledger
823 (id, workspace, kind, amount_micros, description, repo, task,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily824 cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros, price_version)
825 VALUES (?, ?, 'usage', ?, ?, ?, 'sandbox', ?, ?, ?, 'g1t', ?, ?, ?, ?, ?)",
Every sandbox is metered by the second826 )
827 .bind(&[
828 new_id("led", now).into(),
829 workspace.as_str().into(),
830 (-(charge as f64)).into(),
831 description.as_str().into(),
832 optional(a.repo.as_deref()),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look833 (cost as f64).into(),
Every sandbox is metered by the second834 a.reference.as_str().into(),
835 timestamp.as_str().into(),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put836 (drawn.credit as f64).into(),
837 (drawn.trial as f64).into(),
838 (drawn.oss as f64).into(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look839 (drawn.given as f64).into(),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily840 optional(Some(price_version.as_str()).filter(|v| !v.is_empty())),
Every sandbox is metered by the second841 ])?,
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?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays855 self.count_spend(&workspace, cost, charge, &drawn).await;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look856 if let Some(reservation) = &a.reservation_id {
857 self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: cost }).await?;
858 }
Every sandbox is metered by the second859 Ok(Outcome::Ok(true))
860 }
861}
862
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look863/// Whether an amount may be prepaid: $25 at the least by card, and from
864/// $1,000 by bank transfer.
865pub(crate) fn prepay_amount(cents: u32, bank_transfer: bool) -> std::result::Result<(), String> {
866 let (min, max) = if bank_transfer { (MIN_BANK_TRANSFER_CENTS, MAX_BANK_TRANSFER_CENTS) } else { (MIN_TOP_UP_CENTS, MAX_TOP_UP_CENTS) };
867 if (min..=max).contains(&cents) {
868 return Ok(());
869 }
870 Err(if bank_transfer {
871 format!("Prepay between ${} and ${} by bank transfer.", min / 100, group(max / 100))
872 } else {
873 format!("Prepay between ${} and ${} by card; from $1,000, a bank transfer works too.", min / 100, group(max / 100))
874 })
875}
876
877/// `10,000` for 10000.
878fn group(n: u32) -> String {
879 let digits = n.to_string();
880 let mut out = String::new();
881 for (i, c) in digits.chars().enumerate() {
882 if i > 0 && (digits.len() - i) % 3 == 0 {
883 out.push(',');
884 }
885 out.push(c);
886 }
887 out
888}
889
890#[cfg(test)]
Prices are what g1t pays plus 20%, from the first second891/// What `seconds` of sandbox time are charged at `price_per_second`, in
892/// millionths of a dollar: every second, rounded up to the next millionth.
893fn sandbox_charge(seconds: i64, price_per_second: f64) -> i64 {
894 (seconds as f64 * price_per_second).ceil() as i64
Every sandbox is metered by the second895}
896
897/// `1h 2m`, `3m 12s` or `40s`.
898fn duration(seconds: i64) -> String {
899 let (h, m, s) = (seconds / 3600, seconds % 3600 / 60, seconds % 60);
900 if h > 0 {
901 format!("{h}h {m}m")
902 } else if m > 0 {
903 format!("{m}m {s}s")
904 } else {
905 format!("{s}s")
906 }
907}
908
Billing accounts, terms and enterprises; g1t is no longer free909impl Billing {
910 /// What a workspace is charged for something that would be `base`:
911 /// nothing while g1t is free, or as its account's terms say. With a
912 /// note for the statement when it differs.
913 pub(crate) async fn charged(&self, workspace: &str, base: i64) -> Result<(i64, String)> {
914 if self.free {
915 return Ok((0, " (free while g1t is being built out)".to_owned()));
916 }
917 let terms = self.terms_of(workspace).await?;
918 let charge = terms.apply(base);
919 let note = match terms.kind {
920 TermsKind::Comped => " (comped)".to_owned(),
921 TermsKind::Custom if terms.discount_percent > 0 && base > 0 => format!(" ({}% off)", terms.discount_percent),
922 _ => String::new(),
923 };
924 Ok((charge, note))
925 }
926}
927
Agents as a team: lifecycle, merge queue, billing and a new shell928fn members_only<T>() -> Outcome<T> {
929 Outcome::fail(
930 FailureCode::Forbidden,
931 "Only members can see a workspace's billing.",
932 )
933}
934
Prices keep themselves current with what g1t pays935impl Billing {
936 fn from_env(env: &Env) -> Result<Self> {
937 Ok(Billing {
938 db: env.d1("DB")?,
939 stripe: env
940 .secret("STRIPE_SECRET_KEY")
941 .ok()
942 .map(|key| key.to_string())
943 .filter(|key| !key.is_empty())
944 .map(Stripe::new),
945 margin_percent: env
946 .var("MARGIN_PERCENT")
947 .ok()
948 .and_then(|percent| percent.to_string().parse().ok())
949 .unwrap_or(20),
950 free: env.var("FREE_WHILE_BUILDING").is_ok_and(|v| v.to_string() == "true"),
951 ceilings: limits::Ceilings::from_env(&env),
Billing accounts, terms and enterprises; g1t is no longer free952 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 put953 trials_on: {
954 let plans = credits::Config::from_env(env);
955 plans.trial_workspace_micros > 0 && plans.trial_monthly_pool_micros > 0
Prices keep themselves current with what g1t pays956 },
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put957 plans: credits::Config::from_env(env),
958 repos: env.service("REPOS").ok(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look959 identity: env.service("IDENTITY").ok(),
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays960 caps: budget::Caps::from_env(env),
961 env: env.clone(),
Prices keep themselves current with what g1t pays962 })
963 }
964}
965
966#[event(scheduled)]
967async fn scheduled(event: ScheduledEvent, env: Env, _ctx: ScheduleContext) {
968 let Ok(billing) = Billing::from_env(&env) else {
969 return;
970 };
971 let keeper = keeper::Keeper::from_env(&env);
972 if let Err(error) = billing.settle_runs(&keeper).await {
973 worker::console_error!("settling runs failed: {error}");
974 }
Billing accounts, terms and enterprises; g1t is no longer free975 if let Err(error) = billing.autopay().await {
976 worker::console_error!("paying at the limit failed: {error}");
977 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put978 // Last month's metered usage (scans, embeddings, storage) goes on the
979 // ledger before the month is closed and invoiced.
980 if let Err(error) = billing.charge_pending().await {
981 worker::console_error!("charging last month's metered usage failed: {error}");
982 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace983 if let Err(error) = billing.close_months().await {
984 worker::console_error!("closing the month failed: {error}");
985 }
Stripe webhooks, enterprise invoices, and sudo for both986 if let Err(error) = billing.invoice_enterprises().await {
987 worker::console_error!("invoicing enterprises failed: {error}");
988 }
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays989 // Comped budgets' alerts, and a tripped breaker staff were not told of.
990 if let Err(error) = billing.watch_spend().await {
991 worker::console_error!("watching g1t's own spend failed: {error}");
992 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace993 if let Ok(identity) = env.service("IDENTITY") {
994 if let Err(error) = billing.warn_limits(&identity).await {
995 worker::console_error!("warning owners failed: {error}");
996 }
997 }
The keeper reads Cloudflare as it really answers998 // Once a day, and at once if the costs were never checked: check every
999 // cost against what Cloudflare billed.
1000 if event.cron() == keeper::DAILY || billing.never_checked().await.unwrap_or(false) {
Prices keep themselves current with what g1t pays1001 if let Err(error) = billing.reconcile(&keeper).await {
1002 worker::console_error!("checking costs against Cloudflare failed: {error}");
1003 }
1004 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1005 // Once a day: what Cloudflare charged, reconciled against what g1t
1006 // counted and charged; prices whose day has come; margin alerts
1007 // (margin.rs). After the keeper, so its proposals are in.
1008 if event.cron() == keeper::DAILY {
1009 match billing.costs_daily(&env, &keeper).await {
1010 Ok(run) => worker::console_log!("costs: {} lines, {} days, {} proposals, {} alerts", run.lines, run.days, run.proposals, run.alerts),
1011 Err(error) => worker::console_error!("reconciling costs failed: {error}"),
1012 }
1013 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1014 // Once a day: what each workspace's private repositories hold, its git
1015 // operations, Deployments plans from before the g1t plan set to end,
1016 // and old reservations cleared.
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1017 if event.cron() == keeper::DAILY {
1018 if let Err(error) = billing.measure_storage().await {
1019 worker::console_error!("measuring storage failed: {error}");
1020 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1021 if let Err(error) = billing.measure_git().await {
1022 worker::console_error!("measuring git operations failed: {error}");
1023 }
1024 if let Err(error) = billing.retire_deployments_plans().await {
1025 worker::console_error!("ending Deployments plans failed: {error}");
1026 }
1027 if let Err(error) = billing.sweep_reservations().await {
1028 worker::console_error!("clearing reservations failed: {error}");
1029 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1030 }
Prices keep themselves current with what g1t pays1031}
1032
Agents and memory, checks and conflicts, profiles, slug renames, custom domains1033/// Events from the bus, on billing's own queue: only a workspace's rename
1034/// matters here (see `rename`).
1035#[event(queue)]
1036async fn queue(batch: MessageBatch<g1t_contracts::events::Event>, env: Env, _ctx: Context) -> Result<()> {
1037 let billing = Billing::from_env(&env)?;
1038 let identity = env.service("IDENTITY").ok();
1039 for message in batch.messages()? {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1040 // A repository transferred: its share of the open-source pool this
1041 // month follows it. What it was charged stays with the workspace
1042 // it was charged to; usage from now on is charged to the new one.
1043 if g1t_kit::transfer::on_event(&env, &billing.db, message.body(), closing::TRANSFERRED).await? {
1044 message.ack();
1045 continue;
1046 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains1047 billing.on_event(identity.as_ref(), message.body()).await?;
1048 message.ack();
1049 }
1050 Ok(())
1051}
1052
Agents as a team: lifecycle, merge queue, billing and a new shell1053#[event(fetch)]
1054async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> {
1055 let Some(method) = rpc_method(&request) else {
1056 return Response::error("Not found", 404);
1057 };
Fast pages, required checks on the branch, self-hosted runners, honest incidents1058 // A replica near the caller when it asks for one (crates/kit/src/d1.rs);
1059 // what other services call (can_start, start_run) asks for none.
1060 let (db, served) = g1t_kit::d1::open(&env, "DB", &request)?;
Agents as a team: lifecycle, merge queue, billing and a new shell1061 let body: serde_json::Value = request.json().await?;
Fast pages, required checks on the branch, self-hosted runners, honest incidents1062 let mut billing = Billing::from_env(&env)?;
1063 billing.db = db;
1064 let answered = match method.as_str() {
Agents as a team: lifecycle, merge queue, billing and a new shell1065 "status" => reply(&billing.status()),
1066 "account" => reply(&billing.account(args(body)?).await?),
1067 "ledger" => reply(&billing.ledger(args(body)?).await?),
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request1068 "usage" => reply(&billing.usage(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1069 "checkout" => reply(&billing.checkout(args(body)?).await?),
1070 "confirm" => reply(&billing.confirm(args(body)?).await?),
1071 "can_start" => reply(&billing.can_start(args(body)?).await?),
A free allowance on g1t's models, so anyone can try its agents1072 "trial" => reply(&billing.trial(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1073 "start_run" => reply(&billing.start_run(args(body)?).await?),
1074 "finish_run" => reply(&billing.finish_run(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan1075 "features" => reply(&billing.features(args(body)?).await?),
1076 "subscribe" => reply(&billing.subscribe(args(body)?).await?),
1077 "confirm_subscription" => reply(&billing.confirm_subscription(args(body)?).await?),
1078 "cancel_subscription" => reply(&billing.cancel_subscription(args(body)?).await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1079 "close_workspace" => reply(&billing.close_workspace(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan1080 "has_feature" => reply(&billing.has_feature(args(body)?).await?),
1081 "charge_feature" => reply(&billing.charge_feature(args(body)?).await?),
Every sandbox is metered by the second1082 "record_sandbox" => reply(&billing.record_sandbox(args(body)?).await?),
Usage limits: unpaid usage can only go so far1083 "limit" => reply(&billing.limit(args(body)?).await?),
1084 "check_limit" => reply(&billing.check_limit(args(body)?).await?),
1085 "set_spend_limit" => reply(&billing.set_spend_limit(args(body)?).await?),
Prices keep themselves current with what g1t pays1086 "prices" => reply(&billing.prices().await?),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1087 "billing_portal" => reply(&billing.billing_portal(args(body)?).await?),
1088 "admin_billing_link" => reply(&billing.admin_billing_link(args(body)?).await?),
Stripe webhooks, enterprise invoices, and sudo for both1089 "admin_stripe" => reply(&billing.admin_stripe(args(body)?).await?),
1090 "admin_enterprise_billing" => reply(&billing.admin_enterprise_billing(args(body)?).await?),
1091 "admin_invoice_enterprise" => reply(&billing.admin_invoice_enterprise(args(body)?).await?),
1092 "stripe_webhook" => reply(&billing.stripe_webhook(args(body)?).await?),
Two limits, real invoices, trust that grows by itself, sales signals1093 "invoices" => reply(&billing.invoices(args(body)?).await?),
The statement is a month at a time, a line per kind of charge1094 "statement" => reply(&billing.statement(args(body)?).await?),
1095 "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 quotas1096 "usage_meters" => reply(&billing.usage_meters(args(body)?).await?),
Two limits, real invoices, trust that grows by itself, sales signals1097 "admin_workspace_invoices" => {
1098 let a: AdminWorkspaceInvoicesArgs = args(body)?;
1099 reply(&billing.workspace_invoices(&a.workspace.to_lowercase()).await?)
1100 }
1101 "admin_signals" => reply(&billing.admin_signals(args(body)?).await?),
1102 "admin_overview" => reply(&billing.admin_overview(args(body)?).await?),
1103 "admin_sales" => reply(&billing.admin_sales(args(body)?).await?),
1104 "admin_set_sales" => reply(&billing.admin_set_sales(args(body)?).await?),
1105 "admin_add_note" => reply(&billing.admin_add_note(args(body)?).await?),
Billing lists every invoice and every staff change; signals carry follow-ups1106 "admin_invoices" => reply(&billing.admin_invoices(args(body)?).await?),
1107 "admin_audit" => reply(&billing.admin_audit(args(body)?).await?),
Prices keep themselves current with what g1t pays1108 "note_pending" => reply(&billing.note_pending(args(body)?).await?),
Billing accounts, terms and enterprises; g1t is no longer free1109 "admin_accounts" => reply(&billing.admin_accounts(args(body)?).await?),
1110 "admin_account" => reply(&billing.admin_account(args(body)?).await?),
1111 "admin_set_terms" => reply(&billing.admin_set_terms(args(body)?).await?),
1112 "admin_create_enterprise" => reply(&billing.admin_create_enterprise(args(body)?).await?),
1113 "admin_attach" => reply(&billing.admin_attach(args(body)?).await?),
1114 "admin_credit" => reply(&billing.admin_credit(args(body)?).await?),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1115 "admin_set_allowances" => reply(&billing.admin_set_allowances(args(body)?).await?),
1116 "entitlements" => reply(&billing.entitlements(args(body)?).await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1117 "reserve" => reply(&billing.reserve(args(body)?).await?),
1118 "settle" => reply(&billing.settle_reservation(args(body)?).await?),
1119 "card_check" => reply(&billing.card_check(args(body)?).await?),
1120 "confirm_card_check" => reply(&billing.confirm_card_check(args(body)?).await?),
1121 "request_limit" => reply(&billing.request_limit(args(body)?).await?),
1122 "limit_requests" => reply(&billing.limit_requests(args(body)?).await?),
1123 "confirm_spike" => reply(&billing.confirm_spike(args(body)?).await?),
1124 "set_caps" => reply(&billing.set_caps(args(body)?).await?),
1125 "admin_limit_requests" => reply(&billing.admin_limit_requests(args(body)?).await?),
1126 "admin_decide_limit_request" => reply(&billing.admin_decide_limit_request(args(body)?).await?),
1127 "admin_overages" => reply(&billing.admin_overages(args(body)?).await?),
1128 "admin_goodwill" => reply(&billing.admin_goodwill(args(body)?).await?),
1129 "admin_velocity" => reply(&billing.admin_velocity(args(body)?).await?),
1130 "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 daily1131 "admin_costs" => reply(&billing.admin_costs(args(body)?, keeper::Keeper::from_env(&env).can_read_bill()).await?),
1132 "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 pays1133 "admin_spend_caps" => reply(&billing.spend_caps().await?),
1134 "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 daily1135 "admin_decide_proposal" => reply(&billing.admin_decide_proposal(args(body)?).await?),
1136 "admin_set_cost_settings" => reply(&billing.admin_set_cost_settings(args(body)?).await?),
1137 "admin_set_cost_mapping" => reply(&billing.admin_set_cost_mapping(args(body)?).await?),
1138 "admin_run_costs" => reply(&billing.admin_run_costs(&env, args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1139 _ => Response::error("Unknown method", 404),
Fast pages, required checks on the branch, self-hosted runners, honest incidents1140 };
1141 served.finish(answered)
Agents as a team: lifecycle, merge queue, billing and a new shell1142}
1143
1144#[cfg(test)]
1145mod tests {
1146 use super::*;
1147
1148 #[test]
1149 fn a_run_is_charged_its_cost_plus_the_margin() {
1150 // $0.05 at 20% is six cents.
1151 assert_eq!(charge_micros(0.05, 20), 60_000);
1152 assert_eq!(charge_micros(1.0, 20), 1_200_000);
1153 assert_eq!(charge_micros(0.05, 0), 50_000);
1154 }
1155
1156 #[test]
1157 fn fractions_of_a_millionth_round_up_and_nothing_costs_less_than_nothing() {
1158 assert_eq!(charge_micros(0.000_000_4, 20), 2);
1159 assert_eq!(charge_micros(0.0, 20), 0);
1160 assert_eq!(charge_micros(-3.0, 20), 0);
1161 }
1162
1163 #[test]
Prices are what g1t pays plus 20%, from the first second1164 fn sandbox_time_is_charged_from_the_first_second() {
1165 // 21 millionths a second at cost, plus 20%.
1166 let price = Price::price_for(21.0, 20);
1167 assert_eq!(sandbox_charge(1, price), 26);
1168 assert_eq!(sandbox_charge(60, price), 1_512);
1169 assert_eq!(sandbox_charge(0, price), 0);
Every sandbox is metered by the second1170 }
1171
1172 #[test]
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1173 fn prepaying_starts_at_twenty_five_dollars_and_bank_transfers_at_a_thousand() {
1174 assert!(prepay_amount(2_500, false).is_ok());
1175 assert!(prepay_amount(2_499, false).is_err());
1176 assert!(prepay_amount(10_000, false).is_ok());
1177 assert!(prepay_amount(1_000_000, false).is_ok());
1178 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.");
1179 assert!(prepay_amount(99_999, true).is_err());
1180 assert!(prepay_amount(100_000, true).is_ok());
1181 }
1182
1183 #[test]
Every sandbox is metered by the second1184 fn durations_read_plainly() {
1185 assert_eq!(duration(40), "40s");
1186 assert_eq!(duration(192), "3m 12s");
1187 assert_eq!(duration(3720), "1h 2m");
1188 }
1189
1190 #[test]
Agents as a team: lifecycle, merge queue, billing and a new shell1191 fn an_absurd_cost_is_capped() {
1192 assert_eq!(charge_micros(1e9, 20), 120 * MICROS_PER_DOLLAR);
1193 }
1194}