Skip to content
1,578 linesCodeBlameRaw

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;
Usage, Billing settings and prepaid AI credit; fixes from the UX audit21mod ai;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays22mod budget;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look23mod cards;
24mod closing;
25mod compute;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily26mod costs;
27mod margin;
28mod pricing;
Usage, Billing settings and prepaid AI credit; fixes from the UX audit29mod report;
30mod details;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put31mod credits;
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging32mod grants;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look33mod overages;
34mod requests;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put35mod storage;
Two limits, real invoices, trust that grows by itself, sales signals36mod invoices;
37mod sales;
The statement is a month at a time, a line per kind of charge38mod statement;
Stripe webhooks, enterprise invoices, and sudo for both39mod webhooks;
Paid features: a workspace turns on Deployments with a monthly plan40mod features;
Prices keep themselves current with what g1t pays41mod keeper;
Usage limits: unpaid usage can only go so far42mod limits;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains43mod 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's44mod reset;
Audit logs are kept by plan: a week on free, 90 days on the plan, and what staff set for an account in sudo45mod retention;
Agents as a team: lifecycle, merge queue, billing and a new shell46mod stripe;
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept47mod 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 & pricing48mod subscriptions;
Billing: Stripe Tax on every payment, the card fee on every card payment, and free_workspaces49mod tax;
Mission control shows model usage, yours and the workspace's: tokens, cost, active days, cache share, each day, and the mix50mod tokens;
Agents as a team: lifecycle, merge queue, billing and a new shell51
52use g1t_contracts::billing::*;
53use g1t_contracts::time::rfc3339;
54use g1t_contracts::{FailureCode, Outcome, Role, new_id};
55use g1t_kit::{args, now_ms, reply, rpc_method};
56use serde::Deserialize;
57use sha2::{Digest, Sha256};
58use worker::wasm_bindgen::JsValue;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains59use 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 index60use futures_util::future::{try_join, try_join5};
Agents as a team: lifecycle, merge queue, billing and a new shell61
62use stripe::Stripe;
63
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look64/// Prepaying: $25 at the least; by card up to $10,000 at a time, and by
65/// bank transfer from $1,000 to $100,000.
66const MIN_TOP_UP_CENTS: u32 = 2_500;
67const MAX_TOP_UP_CENTS: u32 = 1_000_000;
68const MIN_BANK_TRANSFER_CENTS: u32 = 100_000;
69const MAX_BANK_TRANSFER_CENTS: u32 = 10_000_000;
Agents as a team: lifecycle, merge queue, billing and a new shell70const LEDGER_PAGE: u32 = 100;
71/// A run's reported cost is believed up to this much. A sandbox cannot
72/// spend more in the time it has, so anything above is a fault.
73const MAX_RUN_COST_USD: f64 = 100.0;
74
75/// What a run is charged: its cost plus the margin, rounded up to a whole
76/// millionth of a dollar.
77pub fn charge_micros(cost_usd: f64, margin_percent: u32) -> i64 {
78 let cost_micros = (cost_usd.clamp(0.0, MAX_RUN_COST_USD) * MICROS_PER_DOLLAR as f64).ceil();
79 (cost_micros * f64::from(100 + margin_percent) / 100.0).ceil() as i64
80}
81
Merge branch 'worktree-agent-a633ac0f7f66d419d'82/// What a cost g1t trusts (the price book's, or what AI Gateway priced a
83/// run at) is charged at: plus the margin, rounded up to a whole millionth.
84/// Unlike `charge_micros`, never capped: only a sandbox's own report is
85/// held to `MAX_RUN_COST_USD`, so a run that really cost more is charged
86/// for all of it once it is settled.
87pub fn margin_on(cost_micros: i64, margin_percent: u32) -> i64 {
88 let cost = i128::from(cost_micros.max(0));
89 let charge = (cost * i128::from(100 + margin_percent) + 99) / 100;
90 i64::try_from(charge).unwrap_or(i64::MAX)
91}
92
Agents as a team: lifecycle, merge queue, billing and a new shell93fn hash(token: &str) -> String {
94 hex::encode(Sha256::digest(token.as_bytes()))
95}
96
97fn optional(value: Option<&str>) -> JsValue {
98 value.map_or(JsValue::NULL, JsValue::from)
99}
100
101#[derive(Deserialize)]
102struct AccountRow {
103 balance_micros: i64,
104 customer_id: Option<String>,
105}
106
107#[derive(Deserialize)]
108struct LedgerRow {
109 id: String,
110 kind: EntryKind,
111 amount_micros: i64,
112 description: String,
113 repo: Option<String>,
114 number: Option<u32>,
115 task: Option<String>,
116 model: Option<String>,
117 created_by: Option<String>,
118 created_at: String,
Integrations: your own model provider, alerts that open issues, tickets agents read119 billed_to: Option<String>,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace120 #[serde(default)]
121 workspace: Option<String>,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put122 #[serde(default)]
123 credit_micros: Option<i64>,
124 #[serde(default)]
125 trial_micros: Option<i64>,
126 #[serde(default)]
127 oss_micros: Option<i64>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look128 #[serde(default)]
129 given_micros: Option<i64>,
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging130 #[serde(default)]
131 credit_kind: Option<String>,
132 #[serde(default)]
133 discount_micros: Option<i64>,
Agents as a team: lifecycle, merge queue, billing and a new shell134}
135
136impl From<LedgerRow> for LedgerEntry {
137 fn from(row: LedgerRow) -> Self {
138 LedgerEntry {
139 id: row.id,
140 kind: row.kind,
141 amount_micros: row.amount_micros,
142 description: row.description,
143 repo: row.repo,
144 number: row.number,
145 task: row.task,
146 model: row.model,
Integrations: your own model provider, alerts that open issues, tickets agents read147 billed_to: row.billed_to.unwrap_or_else(|| "g1t".to_owned()),
Agents as a team: lifecycle, merge queue, billing and a new shell148 created_by: row.created_by,
149 created_at: row.created_at,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace150 workspace: row.workspace,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put151 credit_micros: row.credit_micros.unwrap_or(0),
152 trial_micros: row.trial_micros.unwrap_or(0),
153 oss_micros: row.oss_micros.unwrap_or(0),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look154 given_micros: row.given_micros.unwrap_or(0),
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging155 credit_kind: row.credit_kind.as_deref().and_then(CreditKind::parse),
156 discount_micros: row.discount_micros.unwrap_or(0),
Agents as a team: lifecycle, merge queue, billing and a new shell157 }
158 }
159}
160
161#[derive(Deserialize)]
162struct RunRow {
163 workspace: String,
164 repo: String,
165 number: u32,
166 task: String,
167 model: String,
168 token_hash: String,
Integrations: your own model provider, alerts that open issues, tickets agents read169 billed_to: Option<String>,
170}
171
172impl RunRow {
173 fn own_provider(&self) -> bool {
174 self.billed_to.as_deref() == Some("workspace")
175 }
Agents as a team: lifecycle, merge queue, billing and a new shell176}
177
178#[derive(Deserialize)]
179struct CheckoutRow {
180 workspace: String,
181 created_by: String,
Billing: Stripe Tax on every payment, the card fee on every card payment, and free_workspaces182 #[serde(default)]
183 fee_cents: Option<u32>,
Agents as a team: lifecycle, merge queue, billing and a new shell184}
185
Usage, Billing settings and prepaid AI credit; fixes from the UX audit186/// A payment page started, as `checkouts` keeps it.
187pub(crate) struct NewCheckout<'a> {
188 pub id: &'a str,
189 pub workspace: &'a str,
190 /// What it pays for, in cents: the prepayment, the plan's price, the AI
191 /// credit; 0 for a card check.
192 pub amount_cents: u32,
193 /// The card fee on top, for AI credit.
194 pub fee_cents: u32,
195 pub created_by: &'a str,
196 /// None for a prepayment; `plan`, `security`, `card_check` or
197 /// `ai_credit` otherwise.
198 pub feature: Option<&'a str>,
199}
200
201/// The one insert every payment page goes through, every column named, so
202/// a column added to `checkouts` with no default is caught by
203/// `tests::every_checkout_insert_fills_the_table` rather than by a 500.
204pub(crate) const CHECKOUT_INSERT: &str = "INSERT INTO checkouts (id, workspace, amount_cents, fee_cents, created_by, created_at, feature, status)
205 VALUES (?, ?, ?, ?, ?, ?, ?, 'open')";
206
207impl Billing {
208 pub(crate) async fn record_checkout(&self, c: &NewCheckout<'_>) -> Result<()> {
209 self.db
210 .prepare(CHECKOUT_INSERT)
211 .bind(&[
212 c.id.into(),
213 c.workspace.into(),
214 c.amount_cents.into(),
215 c.fee_cents.into(),
216 c.created_by.into(),
217 rfc3339(now_ms()).into(),
218 optional(c.feature),
219 ])?
220 .run()
221 .await?;
222 Ok(())
223 }
224}
225
Agents as a team: lifecycle, merge queue, billing and a new shell226/// A row an `UPDATE … RETURNING` touched.
227#[derive(Deserialize)]
228struct Touched {
229 #[allow(dead_code)]
230 id: String,
231}
232
233struct Billing {
234 db: D1Database,
235 /// Absent when no card processor is configured.
236 stripe: Option<Stripe>,
Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard237 /// The destination's signing secret from Stripe (`STRIPE_WEBHOOK_SECRET`);
238 /// without it no event is believed.
239 webhook_secret: Option<String>,
Agents as a team: lifecycle, merge queue, billing and a new shell240 margin_percent: u32,
Free while g1t is being built out; agents can check out their own forks241 /// While g1t is being built out, nothing is charged (`FREE_WHILE_BUILDING`).
242 free: bool,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put243 /// Whether new workspaces get trial credit (`TRIAL_WORKSPACE_MICROS`
244 /// and `TRIAL_MONTHLY_POOL_MICROS` both above zero).
245 trials_on: bool,
246 /// The plans' and pools' numbers; see `credits`.
247 plans: credits::Config,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look248 /// The repos service: which repositories are public, what private ones
249 /// 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 put250 repos: Option<worker::Fetcher>,
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member251 /// The packages service: what each workspace's packages hold.
252 packages: Option<worker::Fetcher>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look253 /// The identity service, which emails owners. Absent where it is not
254 /// bound.
255 identity: Option<worker::Fetcher>,
Usage limits: unpaid usage can only go so far256 /// How far unpaid usage may go; see `limits`.
257 ceilings: limits::Ceilings,
Billing accounts, terms and enterprises; g1t is no longer free258 /// `PREPAID_ONLY`: the old rule, that agents need credit first.
259 prepaid_only: bool,
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays260 /// The caps on what g1t pays for itself; see `budget`.
261 caps: budget::Caps,
262 /// The worker's bindings, for emailing staff (`EMAIL`).
263 env: Env,
A free allowance on g1t's models, so anyone can try its agents264}
265
Agents as a team: lifecycle, merge queue, billing and a new shell266impl Billing {
267 fn status(&self) -> Status {
268 Status {
269 enabled: self.stripe.is_some(),
270 live: self.stripe.as_ref().is_some_and(Stripe::live),
Free while g1t is being built out; agents can check out their own forks271 free: self.free,
Agents as a team: lifecycle, merge queue, billing and a new shell272 }
273 }
274
275 async fn row(&self, workspace: &str) -> Result<Option<AccountRow>> {
276 self.db
277 .prepare("SELECT balance_micros, customer_id FROM accounts WHERE workspace = ?")
278 .bind(&[workspace.into()])?
279 .first::<AccountRow>(None)
280 .await
281 }
282
283 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 kept284 // The card as last synced (stripe_sync.rs), not asked of Stripe.
285 let (row, card) = try_join(self.row(workspace), self.saved_card(workspace)).await?;
Agents as a team: lifecycle, merge queue, billing and a new shell286 Ok(Account {
287 workspace: workspace.to_owned(),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace288 balance_micros: row.map_or(0, |row| row.balance_micros),
Agents as a team: lifecycle, merge queue, billing and a new shell289 status: self.status(),
290 margin_percent: self.margin_percent,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace291 card,
Agents as a team: lifecycle, merge queue, billing and a new shell292 })
293 }
294
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace295 /// The workspace's customer at Stripe, made the first time one is needed.
296 pub(crate) async fn customer_for(&self, workspace: &str) -> Result<String> {
297 let Some(stripe) = &self.stripe else {
298 return Err(worker::Error::RustError("payments are not set up".into()));
299 };
300 if let Some(customer) = self.row(workspace).await?.and_then(|row| row.customer_id) {
301 return Ok(customer);
302 }
303 let customer = stripe.create_customer(workspace).await?;
304 self.db
305 .prepare(
306 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at) VALUES (?1, 0, ?2, ?3)
307 ON CONFLICT (workspace) DO UPDATE SET customer_id = ?2",
308 )
309 .bind(&[workspace.into(), customer.as_str().into(), rfc3339(now_ms()).into()])?
310 .run()
311 .await?;
312 Ok(customer)
313 }
314
315 /// Stripe's hosted billing page for the workspace. Owners only.
316 async fn billing_portal(&self, a: BillingPortalArgs) -> Result<Outcome<Checkout>> {
317 let workspace = a.workspace.to_lowercase();
318 if a.actor.role_in(&workspace) != Some(Role::Owner) {
319 return Ok(Outcome::fail(FailureCode::Forbidden, "Only an owner can manage the workspace's billing."));
320 }
321 let Some(stripe) = &self.stripe else {
322 return Ok(Outcome::fail(FailureCode::Conflict, "Payments are not set up on this g1t."));
323 };
324 let customer = match self.customer_for(&workspace).await {
325 Ok(customer) => customer,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit326 Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, crate::stripe::friendly(&error))),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace327 };
328 match stripe.portal_session(&customer, &a.return_url).await {
329 Ok(url) => Ok(Outcome::Ok(Checkout { url })),
330 Err(error) if stripe::is_missing(&error) => {
331 // The customer was removed at Stripe: a new one next time.
332 self.forget_customer(&workspace).await?;
333 Ok(Outcome::fail(FailureCode::Conflict, "Stripe no longer had this workspace's customer. Try again."))
334 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit335 Err(error) => Ok(Outcome::fail(FailureCode::Conflict, crate::stripe::friendly(&error))),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace336 }
337 }
338
Agents as a team: lifecycle, merge queue, billing and a new shell339 /// Adds a ledger entry and moves the balance by the same amount, as
340 /// one write.
341 #[allow(clippy::too_many_arguments)]
342 async fn enter(
343 &self,
344 workspace: &str,
345 kind: EntryKind,
346 amount_micros: i64,
347 description: &str,
348 reference: &str,
349 run: Option<&RunRow>,
350 cost_micros: Option<i64>,
351 created_by: Option<&str>,
352 customer: Option<&str>,
353 ) -> Result<()> {
354 let now = now_ms();
355 let timestamp = rfc3339(now);
356 let kind = match kind {
357 EntryKind::TopUp => "top_up",
358 EntryKind::Usage => "usage",
359 };
360 self.db
361 .batch(vec![
362 self.db
363 .prepare(
364 "INSERT INTO ledger
365 (id, workspace, kind, amount_micros, description, repo, number, task,
Integrations: your own model provider, alerts that open issues, tickets agents read366 model, cost_micros, reference, created_by, created_at, billed_to)
367 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
Agents as a team: lifecycle, merge queue, billing and a new shell368 )
369 .bind(&[
370 new_id("led", now).into(),
371 workspace.into(),
372 kind.into(),
373 // D1 takes numbers as doubles, which hold every
374 // amount this service will see exactly.
375 (amount_micros as f64).into(),
376 description.into(),
377 optional(run.map(|run| run.repo.as_str())),
378 run.map_or(JsValue::NULL, |run| run.number.into()),
379 optional(run.map(|run| run.task.as_str())),
380 optional(run.map(|run| run.model.as_str())),
381 cost_micros.map_or(JsValue::NULL, |cost| (cost as f64).into()),
382 reference.into(),
383 optional(created_by),
384 timestamp.as_str().into(),
Integrations: your own model provider, alerts that open issues, tickets agents read385 run.map_or("g1t", |run| if run.own_provider() { "workspace" } else { "g1t" }).into(),
Agents as a team: lifecycle, merge queue, billing and a new shell386 ])?,
387 self.db
388 .prepare(
389 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at)
390 VALUES (?1, ?2, ?3, ?4)
391 ON CONFLICT (workspace) DO UPDATE SET
392 balance_micros = balance_micros + ?2,
393 customer_id = COALESCE(?3, customer_id)",
394 )
395 .bind(&[
396 workspace.into(),
397 (amount_micros as f64).into(),
398 optional(customer),
399 timestamp.as_str().into(),
400 ])?,
401 ])
402 .await?;
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging403 // Money in clears a card declined at the limit. A refund or a lost
404 // dispute is a top-up of less than nothing: money out, which never
405 // clears it.
406 if kind == "top_up" && amount_micros > 0 {
Billing accounts, terms and enterprises; g1t is no longer free407 self.db
408 .prepare("UPDATE limits SET autopay_failed_at = NULL, autopay_error = NULL WHERE workspace = ?")
409 .bind(&[workspace.into()])?
410 .run()
411 .await?;
412 }
Agents as a team: lifecycle, merge queue, billing and a new shell413 Ok(())
414 }
415
416 async fn account(&self, a: AccountArgs) -> Result<Outcome<Account>> {
417 let workspace = a.workspace.to_lowercase();
418 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
419 return Ok(members_only());
420 }
421 Ok(Outcome::Ok(self.standing(&workspace).await?))
422 }
423
424 async fn ledger(&self, a: AccountArgs) -> Result<Outcome<Vec<LedgerEntry>>> {
425 let workspace = a.workspace.to_lowercase();
426 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
427 return Ok(members_only());
428 }
429 let rows = self
430 .db
431 .prepare("SELECT * FROM ledger WHERE workspace = ? ORDER BY id DESC LIMIT ?")
432 .bind(&[workspace.into(), LEDGER_PAGE.into()])?
433 .all()
434 .await?
435 .results::<LedgerRow>()?;
436 Ok(Outcome::Ok(
437 rows.into_iter().map(LedgerEntry::from).collect(),
438 ))
439 }
440
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request441 async fn usage(&self, a: UsageArgs) -> Result<Outcome<Usage>> {
442 let workspace = a.workspace.to_lowercase();
443 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
444 return Ok(members_only());
445 }
446 #[derive(serde::Deserialize)]
447 struct SliceRow {
448 key: Option<String>,
449 micros: Option<i64>,
450 runs: Option<u32>,
451 }
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging452 // While g1t is free, what was used at cost is what there is to show.
453 // With a discount, usage at its price, so a 100% discount still
454 // shows what the workspace would pay.
Usage, Billing settings and prepaid AI credit; fixes from the UX audit455 // Every slice measures usage at price (statement::PRICE_SQL), the one
456 // figure every page shows as usage, whatever paid for it.
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging457 let discount_percent = self.terms_of(&workspace).await?.percent_off();
Usage, Billing settings and prepaid AI credit; fixes from the UX audit458 let measure = if self.free { "COALESCE(cost_micros, 0)" } else { crate::statement::PRICE_SQL };
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request459 let slices = |key: &str, limit: u32| {
460 format!(
Usage while free is shown at cost; agents get rustfmt and clippy461 "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 request462 WHERE workspace = ?1 AND kind = 'usage' AND created_at >= ?2
463 GROUP BY 1 ORDER BY micros DESC LIMIT {limit}"
464 )
465 };
466 let query = |sql: String| {
467 let db = &self.db;
468 let workspace = workspace.clone();
469 let since = a.since.clone();
470 async move {
471 let rows = db
472 .prepare(sql)
473 .bind(&[workspace.into(), since.into()])?
474 .all()
475 .await?
476 .results::<SliceRow>()?;
477 Ok::<Vec<UsageSlice>, worker::Error>(
478 rows.into_iter()
479 .map(|row| UsageSlice {
480 key: row.key.unwrap_or_else(|| "other".to_owned()),
481 micros: row.micros.unwrap_or_default(),
482 runs: row.runs.unwrap_or_default(),
483 })
484 .collect(),
485 )
486 }
487 };
488 #[derive(serde::Deserialize)]
489 struct Totals {
490 spent: Option<i64>,
491 cost: Option<i64>,
Integrations: your own model provider, alerts that open issues, tickets agents read492 provider: Option<i64>,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request493 runs: Option<u32>,
494 added: Option<i64>,
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging495 discount: Option<i64>,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit496 covered: Option<i64>,
497 price: Option<i64>,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request498 }
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 index499 let totals = async {
500 self.db
Usage, Billing settings and prepaid AI credit; fixes from the UX audit501 .prepare(format!(
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 index502 "SELECT
503 -SUM(CASE WHEN kind = 'usage' THEN amount_micros END) AS spent,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit504 SUM(CASE WHEN kind = 'usage' THEN COALESCE(credit_micros, 0) + COALESCE(trial_micros, 0)
505 + COALESCE(oss_micros, 0) + COALESCE(given_micros, 0) END) AS covered,
506 SUM(CASE WHEN kind = 'usage' THEN {price} END) AS price,",
507 price = crate::statement::PRICE_SQL
508 ) + "
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 index509 SUM(CASE WHEN kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' THEN cost_micros END) AS cost,
510 SUM(CASE WHEN kind = 'usage' AND billed_to = 'workspace' THEN cost_micros END) AS provider,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit511 SUM(CASE WHEN kind = 'usage' AND " + crate::statement::RUN_SQL + " THEN 1 ELSE 0 END) AS runs,
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging512 SUM(CASE WHEN kind = 'top_up' THEN amount_micros END) AS added,
513 SUM(CASE WHEN kind = 'usage' THEN discount_micros END) AS discount
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 index514 FROM ledger WHERE workspace = ?1 AND created_at >= ?2",
515 )
516 .bind(&[workspace.as_str().into(), a.since.as_str().into()])?
517 .first::<Totals>(None)
518 .await
519 };
520 // The totals and the five slices read the same rows independently,
521 // so they go to D1 at once: one round trip of waiting, not six.
522 let (totals, (by_day, by_task, by_repo, by_pull, by_model)) = try_join(
523 totals,
524 try_join5(
525 query(slices("substr(created_at, 1, 10) || '/' || COALESCE(task, 'other')", 400)),
526 query(slices("task", 20)),
527 query(slices("repo", 20)),
528 query(slices("repo || '#' || number", 10)),
529 query(slices("model", 10)),
530 ),
531 )
532 .await?;
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request533 let totals = totals.unwrap_or(Totals {
534 spent: None,
535 cost: None,
Integrations: your own model provider, alerts that open issues, tickets agents read536 provider: None,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request537 runs: None,
538 added: None,
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging539 discount: None,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit540 covered: None,
541 price: None,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request542 });
543 Ok(Outcome::Ok(Usage {
544 spent_micros: totals.spent.unwrap_or_default(),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit545 // What the included usage, the trial, a pool or g1t paid, as the
546 // entries record it.
547 covered_micros: totals.covered.unwrap_or_default(),
548 price_micros: if self.free { totals.cost.unwrap_or_default() } else { totals.price.unwrap_or_default() },
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request549 cost_micros: totals.cost.unwrap_or_default(),
Integrations: your own model provider, alerts that open issues, tickets agents read550 provider_micros: totals.provider.unwrap_or_default(),
Usage while free is shown at cost; agents get rustfmt and clippy551 used_micros: totals.cost.unwrap_or_default() + totals.provider.unwrap_or_default(),
552 free: self.free,
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging553 discount_micros: totals.discount.unwrap_or_default(),
554 discount_percent: (discount_percent > 0).then_some(discount_percent),
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request555 runs: totals.runs.unwrap_or_default(),
556 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 index557 by_day,
558 by_task,
559 by_repo,
560 by_pull,
561 by_model,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request562 since: a.since,
563 }))
564 }
565
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look566 /// `checkout`: prepays usage, by card or (from $1,000) bank transfer.
Agents as a team: lifecycle, merge queue, billing and a new shell567 async fn checkout(&self, a: CheckoutArgs) -> Result<Outcome<Checkout>> {
568 let workspace = a.workspace.to_lowercase();
569 if a.actor.role_in(&workspace) != Some(Role::Owner) {
570 return Ok(Outcome::fail(
571 FailureCode::Forbidden,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look572 "Only an owner can prepay for a workspace.",
Agents as a team: lifecycle, merge queue, billing and a new shell573 ));
574 }
575 let Some(stripe) = &self.stripe else {
576 return Ok(Outcome::fail(
577 FailureCode::Conflict,
578 "Payments are not set up on this g1t yet.",
579 ));
580 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look581 let bank_transfer = a.method.as_deref() == Some("bank_transfer");
582 if let Err(why) = prepay_amount(a.amount_cents, bank_transfer) {
583 return Ok(Outcome::fail(FailureCode::Invalid, why));
Agents as a team: lifecycle, merge queue, billing and a new shell584 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look585 // A bank transfer needs a customer for its account details.
586 let customer = if bank_transfer {
587 match self.customer_for(&workspace).await {
588 Ok(customer) => Some(customer),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit589 Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, stripe::friendly(&error))),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look590 }
591 } else {
592 self.row(&workspace).await?.and_then(|row| row.customer_id)
593 };
Billing: Stripe Tax on every payment, the card fee on every card payment, and free_workspaces594 // By card, Stripe's fee is its own line; a bank transfer has none.
595 let fee = if bank_transfer { 0 } else { self.card_fee_on(i64::from(a.amount_cents)).await? as u32 };
596 let started = match stripe.start_checkout(&workspace, a.amount_cents, fee, customer.as_deref(), &a.return_url, bank_transfer).await {
Project dependencies: addresses, preview stacks, Affects, and agents who know597 // A customer saved under another Stripe account: start afresh.
598 Err(error) if customer.is_some() && stripe::is_missing(&error) => {
599 self.forget_customer(&workspace).await?;
Usage, Billing settings and prepaid AI credit; fixes from the UX audit600 let customer = if bank_transfer { self.customer_for(&workspace).await.ok() } else { None };
Billing: Stripe Tax on every payment, the card fee on every card payment, and free_workspaces601 stripe.start_checkout(&workspace, a.amount_cents, fee, customer.as_deref(), &a.return_url, bank_transfer).await
Project dependencies: addresses, preview stacks, Affects, and agents who know602 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit603 other => other,
Project dependencies: addresses, preview stacks, Affects, and agents who know604 };
Billing: Stripe Tax on every payment, the card fee on every card payment, and free_workspaces605 self.page_opened(started, &workspace, a.amount_cents, fee, &a.actor.username, None).await
Usage, Billing settings and prepaid AI credit; fixes from the UX audit606 }
607
608 /// A payment page Stripe started (or refused), recorded in `checkouts`
609 /// and handed back; any failure as a sentence for the page, never a
610 /// raw error.
611 pub(crate) async fn page_opened(
612 &self,
613 started: Result<stripe::Session>,
614 workspace: &str,
615 amount_cents: u32,
616 fee_cents: u32,
617 created_by: &str,
618 feature: Option<&str>,
619 ) -> Result<Outcome<Checkout>> {
620 let session = match started {
621 Ok(session) => session,
622 Err(error) => {
623 worker::console_error!("{workspace}: Stripe refused a payment page ({}): {error}", feature.unwrap_or("prepay"));
624 return Ok(Outcome::fail(FailureCode::Conflict, stripe::friendly(&error)));
625 }
Agents as a team: lifecycle, merge queue, billing and a new shell626 };
Usage, Billing settings and prepaid AI credit; fixes from the UX audit627 let Some(url) = session.url.clone() else {
628 return Ok(Outcome::fail(FailureCode::Conflict, "Stripe returned no payment page. Try again in a minute."));
629 };
630 let recorded = self
631 .record_checkout(&NewCheckout { id: &session.id, workspace, amount_cents, fee_cents, created_by, feature })
632 .await;
633 if let Err(error) = recorded {
634 worker::console_error!("{workspace}: a payment page could not be recorded: {error}");
635 return Ok(Outcome::fail(FailureCode::Conflict, "g1t could not keep track of the payment page. Nothing was charged; try again."));
636 }
Agents as a team: lifecycle, merge queue, billing and a new shell637 Ok(Outcome::Ok(Checkout { url }))
638 }
639
640 /// Credits a payment if the processor says it was made and it has not
641 /// been credited before. The amount credited is what the processor
642 /// says was paid, not what anyone here remembers asking for.
643 async fn confirm(&self, a: ConfirmArgs) -> Result<Outcome<Account>> {
644 let workspace = a.workspace.to_lowercase();
645 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
646 return Ok(members_only());
647 }
648 let (Some(stripe), Some(checkout)) = (
649 &self.stripe,
650 self.db
651 .prepare(
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging652 // A prepayment only: a plan's or a card check's page is
653 // settled where it was started, never credited as money
654 // paid in advance.
Billing: Stripe Tax on every payment, the card fee on every card payment, and free_workspaces655 "SELECT workspace, created_by, fee_cents FROM checkouts
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging656 WHERE id = ? AND workspace = ? AND status = 'open' AND feature IS NULL",
Agents as a team: lifecycle, merge queue, billing and a new shell657 )
658 .bind(&[a.session.as_str().into(), workspace.as_str().into()])?
659 .first::<CheckoutRow>(None)
660 .await?,
661 ) else {
662 // Unknown, someone else's, or already credited: nothing to do.
663 return Ok(Outcome::Ok(self.standing(&workspace).await?));
664 };
Usage, Billing settings and prepaid AI credit; fixes from the UX audit665 let session = match stripe.session(&a.session).await {
666 Ok(session) => session,
667 Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, crate::stripe::friendly(&error))),
668 };
Billing: Stripe Tax on every payment, the card fee on every card payment, and free_workspaces669 if session.payment_status == "paid" && session.amount_total.is_some() {
Agents as a team: lifecycle, merge queue, billing and a new shell670 // Only whoever flips it from open to paid enters the credit.
671 let claimed = self
672 .db
673 .prepare(
674 "UPDATE checkouts SET status = 'paid' WHERE id = ? AND status = 'open'
675 RETURNING id",
676 )
677 .bind(&[a.session.as_str().into()])?
678 .first::<Touched>(None)
679 .await?;
680 if claimed.is_some() {
Billing: Stripe Tax on every payment, the card fee on every card payment, and free_workspaces681 self.credit_prepayment(&checkout.workspace, &session, checkout.fee_cents.unwrap_or(0), &checkout.created_by).await?;
Agents as a team: lifecycle, merge queue, billing and a new shell682 }
683 }
684 Ok(Outcome::Ok(self.standing(&workspace).await?))
685 }
686
Billing: Stripe Tax on every payment, the card fee on every card payment, and free_workspaces687 /// Enters a paid prepayment page: what its lines came to before tax,
688 /// less the card fee, as credit; its tax and fee kept apart. Once the
689 /// page is claimed `open → paid`. The credit in cents.
690 pub(crate) async fn credit_prepayment(&self, workspace: &str, session: &stripe::Session, fee_cents: u32, by: &str) -> Result<i64> {
691 let fee = i64::from(fee_cents);
692 let cents = tax::prepay_credit_cents(session.before_tax_cents(), fee);
693 let tax_cents = session.tax_cents();
694 let description = if tax_cents > 0 || fee > 0 {
695 format!(
696 "Paid in advance (tax {} and card fee {} paid with it)",
697 features::cents(tax_cents * 10_000),
698 features::cents(fee * 10_000)
699 )
700 } else {
701 "Paid in advance".to_owned()
702 };
703 self.enter(
704 workspace,
705 EntryKind::TopUp,
706 cents * MICROS_PER_DOLLAR / 100,
707 &description,
708 &session.id,
709 None,
710 None,
711 Some(by),
712 session.customer.as_deref(),
713 )
714 .await?;
715 self.record_extras(workspace, &session.id, session.payment_intent.as_deref(), tax::Extras { tax_cents, fee_cents: fee }, None)
716 .await?;
717 Ok(cents)
718 }
719
Project dependencies: addresses, preview stacks, Affects, and agents who know720 /// Drops a saved customer the card processor no longer knows.
721 pub(crate) async fn forget_customer(&self, workspace: &str) -> Result<()> {
722 self.db
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept723 .prepare(
724 "UPDATE accounts SET customer_id = NULL, card_brand = NULL, card_last4 = NULL, card_exp_month = NULL,
725 card_exp_year = NULL, card_synced_at = NULL WHERE workspace = ?",
726 )
Project dependencies: addresses, preview stacks, Affects, and agents who know727 .bind(&[workspace.into()])?
728 .run()
729 .await?;
730 Ok(())
731 }
732
Agents as a team: lifecycle, merge queue, billing and a new shell733 /// A refusal if the workspace has no credit to start an agent with.
734 async fn out_of_credit<T>(&self, workspace: &str) -> Result<Option<Outcome<T>>> {
Billing accounts, terms and enterprises; g1t is no longer free735 // Billing is postpaid: usage limits decide whether work starts
736 // (see `limits`), and credit is a prepayment that lowers what is
737 // owed. A balance no longer has to be positive to start.
738 if self.free || !self.prepaid_only {
Free while g1t is being built out; agents can check out their own forks739 return Ok(None);
740 }
Agents as a team: lifecycle, merge queue, billing and a new shell741 let balance = self
742 .row(workspace)
743 .await?
744 .map_or(0, |row| row.balance_micros);
745 Ok((balance <= 0).then(|| {
746 Outcome::fail(
747 FailureCode::PaymentRequired,
748 format!(
749 "The {workspace} workspace has no agent credit. An owner can add some under Billing on the workspace's page."
750 ),
751 )
752 }))
Billing accounts, terms and enterprises; g1t is no longer free753 }
754
Agents as a team: lifecycle, merge queue, billing and a new shell755 async fn can_start(&self, a: CanStartArgs) -> Result<Outcome<bool>> {
756 if self.stripe.is_none() {
757 return Ok(Outcome::Ok(true));
758 }
Usage limits: unpaid usage can only go so far759 if let Some(stopped) = self.stopped(&a.workspace).await? {
760 return Ok(stopped);
761 }
Agents as a team: lifecycle, merge queue, billing and a new shell762 Ok(self
763 .out_of_credit(&a.workspace.to_lowercase())
764 .await?
765 .unwrap_or(Outcome::Ok(true)))
766 }
767
768 async fn start_run(&self, a: StartRunArgs) -> Result<Outcome<Option<RunTicket>>> {
769 if self.stripe.is_none() {
770 return Ok(Outcome::Ok(None));
771 }
772 let workspace = a.workspace.to_lowercase();
Usage limits: unpaid usage can only go so far773 if let Some(stopped) = self.stopped(&workspace).await? {
774 return Ok(stopped);
775 }
Agents as a team: lifecycle, merge queue, billing and a new shell776 if let Some(refused) = self.out_of_credit(&workspace).await? {
777 return Ok(refused);
778 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit779 // On g1t's models, a workspace on the plan needs AI credit (or
780 // included usage) first: g1t never fronts a model's cost (ai.rs).
781 if a.billed_to != "workspace"
782 && let Some(why) = self.ai_refusal(&workspace).await?
783 {
784 return Ok(Outcome::fail(FailureCode::PaymentRequired, why));
785 }
Agents as a team: lifecycle, merge queue, billing and a new shell786 let now = now_ms();
787 let run_id = new_id("run", now);
788 let mut bytes = [0u8; 32];
789 getrandom::getrandom(&mut bytes).expect("no source of randomness");
790 let token = hex::encode(bytes);
791 self.db
792 .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 tier793 "INSERT INTO runs (id, workspace, repo, number, task, model, token_hash, created_at, billed_to, session_id, tier)
794 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
Agents as a team: lifecycle, merge queue, billing and a new shell795 )
796 .bind(&[
797 run_id.as_str().into(),
798 workspace.into(),
799 format!("{}/{}", a.repo.namespace, a.repo.name).into(),
800 a.number.into(),
801 a.task.into(),
802 a.model.into(),
803 hash(&token).into(),
804 rfc3339(now).into(),
Integrations: your own model provider, alerts that open issues, tickets agents read805 if a.billed_to == "workspace" { "workspace" } else { "g1t" }.into(),
Prices keep themselves current with what g1t pays806 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 tier807 optional(
808 a.tier
809 .as_deref()
810 .filter(|tier| a.billed_to != "workspace" && matches!(*tier, "small" | "large")),
811 ),
Agents as a team: lifecycle, merge queue, billing and a new shell812 ])?
813 .run()
814 .await?;
815 Ok(Outcome::Ok(Some(RunTicket { run_id, token })))
816 }
817
818 async fn finish_run(&self, a: FinishRunArgs) -> Result<Outcome<bool>> {
819 let run = self
820 .db
821 .prepare(
Integrations: your own model provider, alerts that open issues, tickets agents read822 "SELECT workspace, repo, number, task, model, token_hash, billed_to FROM runs
Agents as a team: lifecycle, merge queue, billing and a new shell823 WHERE id = ? AND finished_at IS NULL",
824 )
825 .bind(&[a.run_id.as_str().into()])?
826 .first::<RunRow>(None)
827 .await?;
828 let Some(run) = run.filter(|run| run.token_hash == hash(&a.token)) else {
829 return Ok(Outcome::fail(FailureCode::NotFound, "Run not found."));
830 };
831 if !a.cost_usd.is_finite() || a.cost_usd < 0.0 {
832 return Ok(Outcome::fail(FailureCode::Invalid, "That is not a cost."));
833 }
834 // Only whoever closes the run charges for it.
835 let claimed = self
836 .db
837 .prepare(
838 "UPDATE runs SET finished_at = ? WHERE id = ? AND finished_at IS NULL RETURNING id",
839 )
840 .bind(&[rfc3339(now_ms()).into(), a.run_id.as_str().into()])?
841 .first::<Touched>(None)
842 .await?;
843 if claimed.is_none() {
844 return Ok(Outcome::Ok(false));
845 }
Prices are what g1t pays plus 20%, from the first second846 // On the workspace's own provider, the model was paid for there,
847 // and the run's sandbox time is recorded on its own: nothing more
848 // to charge.
849 if run.own_provider() {
850 return Ok(Outcome::Ok(true));
851 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look852 // Its cost plus the margin, on the account's terms; then the plan's
853 // included usage and the trial credit pay what they can, and g1t
854 // covers a free workspace's overrun (see `credits`). Agents are
855 // never the open-source pool's.
Usage, Billing settings and prepaid AI credit; fixes from the UX audit856 // The model at the provider's price and the price book's markup on it
857 // (`agent_models`: none from 2026-10-08); g1t's own part is the agent
858 // rate, charged on a line of its own below.
859 let base = charge_micros(a.cost_usd, self.model_markup().await?);
Merge branch 'worktree-agent-a633ac0f7f66d419d'860 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 put861 let month = credits::month_of(&rfc3339(now_ms()));
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look862 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 put863 let drawn = self.draw(&run.workspace, charge, &month, &eligible).await?;
Integrations: your own model provider, alerts that open issues, tickets agents read864 let mut description = match run.task.as_str() {
Agents as a team: lifecycle, merge queue, billing and a new shell865 "plan" => format!("Planning for {}", run.repo),
866 "review" => format!("Review of {}#{}", run.repo, run.number),
867 "update" => format!("Catching up {}#{}", run.repo, run.number),
868 _ => format!("Work on {}#{}", run.repo, run.number),
869 };
Billing accounts, terms and enterprises; g1t is no longer free870 description.push_str(&terms_note);
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put871 description.push_str(&drawn.note());
Agents as a team: lifecycle, merge queue, billing and a new shell872 self.enter(
873 &run.workspace,
874 EntryKind::Usage,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put875 -(charge - drawn.total()),
Agents as a team: lifecycle, merge queue, billing and a new shell876 &description,
877 &a.run_id,
878 Some(&run),
879 Some(charge_micros(a.cost_usd, 0)),
880 None,
881 None,
882 )
883 .await?;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put884 self.record_drawn(&a.run_id, &drawn).await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'885 self.record_discount(&a.run_id, discount).await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays886 self.count_spend(&run.workspace, charge_micros(a.cost_usd, 0), charge - drawn.total(), &drawn).await;
Usage, Billing settings and prepaid AI credit; fixes from the UX audit887 self.charge_agent_rate(&a.run_id, &run).await?;
Agents as a team: lifecycle, merge queue, billing and a new shell888 Ok(Outcome::Ok(true))
889 }
890}
891
Every sandbox is metered by the second892impl Billing {
Prices are what g1t pays plus 20%, from the first second893 /// 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 look894 /// second, from the first, at the price book's price; on its own CPU
895 /// when it reports it. Settles its reservation, if it names one.
Every sandbox is metered by the second896 async fn record_sandbox(&self, a: RecordSandboxArgs) -> Result<Outcome<bool>> {
Fast pages, required checks on the branch, self-hosted runners, honest incidents897 // Self-hosted time is recorded wherever g1t runs, for its minutes;
898 // anything else only where there is a bill to put it on.
899 if (self.stripe.is_none() && !a.self_hosted) || a.seconds == 0 {
Every sandbox is metered by the second900 return Ok(Outcome::Ok(false));
901 }
902 let workspace = a.workspace.to_lowercase();
903 let seen = self
904 .db
905 .prepare("SELECT id FROM ledger WHERE reference = ?")
906 .bind(&[a.reference.as_str().into()])?
907 .first::<Touched>(None)
908 .await?;
909 if seen.is_some() {
910 return Ok(Outcome::Ok(false));
911 }
912 let now = now_ms();
913 let timestamp = rfc3339(now);
914 let seconds = i64::from(a.seconds);
Fast pages, required checks on the branch, self-hosted runners, honest incidents915 // On the workspace's own machine: its minutes go on usage, at $0,
916 // and whatever was reserved for it is given back.
917 if a.self_hosted {
918 let description = format!("{}: {} of self-hosted runner time, $0", a.description, duration(seconds));
919 self.db
920 .prepare(
921 "INSERT INTO ledger
922 (id, workspace, kind, amount_micros, description, repo, task,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit923 cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros, quantity)
924 VALUES (?, ?, 'usage', 0, ?, ?, 'self_hosted', 0, ?, ?, 'workspace', 0, 0, 0, 0, ?)",
Fast pages, required checks on the branch, self-hosted runners, honest incidents925 )
926 .bind(&[
927 new_id("led", now).into(),
928 workspace.as_str().into(),
929 description.as_str().into(),
930 optional(a.repo.as_deref()),
931 a.reference.as_str().into(),
932 timestamp.as_str().into(),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit933 (seconds as f64).into(),
Fast pages, required checks on the branch, self-hosted runners, honest incidents934 ])?
935 .run()
936 .await?;
937 if let Some(reservation) = &a.reservation_id {
938 self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: 0 }).await?;
939 }
940 return Ok(Outcome::Ok(true));
941 }
Prices are what g1t pays plus 20%, from the first second942 // From the price book, which follows what Cloudflare bills g1t. A
943 // sandbox is the same container as a build, so without a row it is
944 // a build second's cost plus the margin.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look945 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 quotas946 let cost = deployment_costs::MICROS_PER_BUILD_SECOND as f64;
Prices are what g1t pays plus 20%, from the first second947 (cost, Price::price_for(cost, self.margin_percent))
948 });
Fast pages, required checks on the branch, self-hosted runners, honest incidents949 // A larger machine (`runs-on: g1t-4core`): its memory and disk
950 // cost more each second, and without its own CPU it is priced at
951 // its vCPUs as busy as the standard machine's.
952 let instance = a.instance.as_deref().and_then(g1t_contracts::actions::instance_named);
953 let base_scale = instance.map_or(1.0, |i| keeper::base_scale(i.memory_gib, i.disk_gb));
954 let price_scale = instance.map_or(1.0, |i| i.price_scale);
955 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 look956 // Its own CPU when the sandbox reports it; otherwise the average.
957 let parts = match a.cpu_seconds.filter(|cpu| cpu.is_finite() && *cpu >= 0.0) {
958 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 incidents959 (Some((base, _)), Some((vcpu, _))) => {
960 Some((keeper::run_cost(seconds, cpu.min(seconds as f64 * vcpus), base * base_scale, vcpu), cpu))
961 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look962 _ => None,
963 },
964 None => None,
965 };
Fast pages, required checks on the branch, self-hosted runners, honest incidents966 let cost = parts.map_or(seconds as f64 * cost_per_second * price_scale, |(cost, _)| cost).ceil() as i64;
Merge branch 'worktree-agent-a633ac0f7f66d419d'967 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 look968 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 put969 let drawn = self.draw(&workspace, charge, &credits::month_of(&timestamp), &eligible).await?;
970 let charge = charge - drawn.total();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look971 let cpu_note = parts.map_or(String::new(), |(_, cpu)| format!(", {cpu:.0} vCPU-seconds"));
972 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 daily973 // The price versions it was charged at (pricing.rs).
974 let meters: &[&str] = if parts.is_some() { &["sandbox_base_second", "sandbox_cpu_second"] } else { &["sandbox_second"] };
975 let mut versions = Vec::new();
976 for meter in meters {
977 versions.extend(self.version_now(meter).await?);
978 }
979 let price_version = versions.join(",");
Every sandbox is metered by the second980 self.db
981 .batch(vec![
982 self.db
983 .prepare(
984 "INSERT INTO ledger
985 (id, workspace, kind, amount_micros, description, repo, task,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit986 cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros, price_version, quantity, compute)
987 VALUES (?, ?, 'usage', ?, ?, ?, 'sandbox', ?, ?, ?, 'g1t', ?, ?, ?, ?, ?, ?, ?)",
Every sandbox is metered by the second988 )
989 .bind(&[
990 new_id("led", now).into(),
991 workspace.as_str().into(),
992 (-(charge as f64)).into(),
993 description.as_str().into(),
994 optional(a.repo.as_deref()),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look995 (cost as f64).into(),
Every sandbox is metered by the second996 a.reference.as_str().into(),
997 timestamp.as_str().into(),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put998 (drawn.credit as f64).into(),
999 (drawn.trial as f64).into(),
1000 (drawn.oss as f64).into(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1001 (drawn.given as f64).into(),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1002 optional(Some(price_version.as_str()).filter(|v| !v.is_empty())),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1003 (seconds as f64).into(),
1004 optional(a.kind.map(ComputeKind::as_str)),
Every sandbox is metered by the second1005 ])?,
1006 self.db
1007 .prepare(
1008 "INSERT INTO accounts (workspace, balance_micros, created_at)
1009 VALUES (?1, ?2, ?3)
1010 ON CONFLICT (workspace) DO UPDATE SET balance_micros = balance_micros + ?2",
1011 )
1012 .bind(&[
1013 workspace.as_str().into(),
1014 (-(charge as f64)).into(),
1015 timestamp.as_str().into(),
1016 ])?,
1017 ])
1018 .await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'1019 self.record_discount(&a.reference, discount).await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays1020 self.count_spend(&workspace, cost, charge, &drawn).await;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1021 if let Some(reservation) = &a.reservation_id {
1022 self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: cost }).await?;
1023 }
Every sandbox is metered by the second1024 Ok(Outcome::Ok(true))
1025 }
1026}
1027
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1028/// Whether an amount may be prepaid: $25 at the least by card, and from
1029/// $1,000 by bank transfer.
1030pub(crate) fn prepay_amount(cents: u32, bank_transfer: bool) -> std::result::Result<(), String> {
1031 let (min, max) = if bank_transfer { (MIN_BANK_TRANSFER_CENTS, MAX_BANK_TRANSFER_CENTS) } else { (MIN_TOP_UP_CENTS, MAX_TOP_UP_CENTS) };
1032 if (min..=max).contains(&cents) {
1033 return Ok(());
1034 }
1035 Err(if bank_transfer {
1036 format!("Prepay between ${} and ${} by bank transfer.", min / 100, group(max / 100))
1037 } else {
1038 format!("Prepay between ${} and ${} by card; from $1,000, a bank transfer works too.", min / 100, group(max / 100))
1039 })
1040}
1041
1042/// `10,000` for 10000.
1043fn group(n: u32) -> String {
1044 let digits = n.to_string();
1045 let mut out = String::new();
1046 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 kept1047 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 look1048 out.push(',');
1049 }
1050 out.push(c);
1051 }
1052 out
1053}
1054
1055#[cfg(test)]
Prices are what g1t pays plus 20%, from the first second1056/// What `seconds` of sandbox time are charged at `price_per_second`, in
1057/// millionths of a dollar: every second, rounded up to the next millionth.
1058fn sandbox_charge(seconds: i64, price_per_second: f64) -> i64 {
1059 (seconds as f64 * price_per_second).ceil() as i64
Every sandbox is metered by the second1060}
1061
1062/// `1h 2m`, `3m 12s` or `40s`.
1063fn duration(seconds: i64) -> String {
1064 let (h, m, s) = (seconds / 3600, seconds % 3600 / 60, seconds % 60);
1065 if h > 0 {
1066 format!("{h}h {m}m")
1067 } else if m > 0 {
1068 format!("{m}m {s}s")
1069 } else {
1070 format!("{s}s")
1071 }
1072}
1073
Billing accounts, terms and enterprises; g1t is no longer free1074impl Billing {
1075 /// What a workspace is charged for something that would be `base`:
1076 /// nothing while g1t is free, or as its account's terms say. With a
1077 /// note for the statement when it differs.
Merge branch 'worktree-agent-a633ac0f7f66d419d'1078 /// A charge at cost plus the margin (`base`) on the account's terms:
1079 /// what is charged, the note for the statement, and what a discount
1080 /// gave away below `base`. That last is written on the entry
1081 /// (`record_discount`) so the reconciliation counts it as given, never
1082 /// as margin lost: a sold charge is worth at least its cost plus the
1083 /// margin.
1084 pub(crate) async fn charged(&self, workspace: &str, base: i64) -> Result<(i64, String, i64)> {
Billing accounts, terms and enterprises; g1t is no longer free1085 if self.free {
Merge branch 'worktree-agent-a633ac0f7f66d419d'1086 return Ok((0, " (free while g1t is being built out)".to_owned(), 0));
Billing accounts, terms and enterprises; g1t is no longer free1087 }
1088 let terms = self.terms_of(workspace).await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'1089 let (charge, discount) = terms.discounted(base);
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging1090 let note = match terms.discount_label() {
1091 Some(label) if base > 0 => format!(" ({label})"),
Billing accounts, terms and enterprises; g1t is no longer free1092 _ => String::new(),
1093 };
Merge branch 'worktree-agent-a633ac0f7f66d419d'1094 Ok((charge, note, discount))
1095 }
1096
1097 /// What a discount gave away on an entry, below cost plus the margin
1098 /// (less than nothing on a correction down).
1099 pub(crate) async fn record_discount(&self, reference: &str, micros: i64) -> Result<()> {
1100 if micros == 0 {
1101 return Ok(());
1102 }
1103 self.db
1104 .prepare("UPDATE ledger SET discount_micros = ? WHERE reference = ?")
1105 .bind(&[(micros as f64).into(), reference.into()])?
1106 .run()
1107 .await?;
1108 Ok(())
Billing accounts, terms and enterprises; g1t is no longer free1109 }
1110}
1111
Agents as a team: lifecycle, merge queue, billing and a new shell1112fn members_only<T>() -> Outcome<T> {
1113 Outcome::fail(
1114 FailureCode::Forbidden,
1115 "Only members can see a workspace's billing.",
1116 )
1117}
1118
Prices keep themselves current with what g1t pays1119impl Billing {
1120 fn from_env(env: &Env) -> Result<Self> {
1121 Ok(Billing {
1122 db: env.d1("DB")?,
1123 stripe: env
1124 .secret("STRIPE_SECRET_KEY")
1125 .ok()
1126 .map(|key| key.to_string())
1127 .filter(|key| !key.is_empty())
1128 .map(Stripe::new),
Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard1129 webhook_secret: env
1130 .secret("STRIPE_WEBHOOK_SECRET")
1131 .ok()
1132 .map(|secret| secret.to_string().trim().to_owned())
1133 .filter(|secret| !secret.is_empty()),
Prices keep themselves current with what g1t pays1134 margin_percent: env
1135 .var("MARGIN_PERCENT")
1136 .ok()
1137 .and_then(|percent| percent.to_string().parse().ok())
1138 .unwrap_or(20),
1139 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 kept1140 ceilings: limits::Ceilings::from_env(env),
Billing accounts, terms and enterprises; g1t is no longer free1141 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 put1142 trials_on: {
1143 let plans = credits::Config::from_env(env);
1144 plans.trial_workspace_micros > 0 && plans.trial_monthly_pool_micros > 0
Prices keep themselves current with what g1t pays1145 },
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1146 plans: credits::Config::from_env(env),
1147 repos: env.service("REPOS").ok(),
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member1148 packages: env.service("PACKAGES").ok(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1149 identity: env.service("IDENTITY").ok(),
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays1150 caps: budget::Caps::from_env(env),
1151 env: env.clone(),
Prices keep themselves current with what g1t pays1152 })
1153 }
1154}
1155
1156#[event(scheduled)]
1157async fn scheduled(event: ScheduledEvent, env: Env, _ctx: ScheduleContext) {
1158 let Ok(billing) = Billing::from_env(&env) else {
1159 return;
1160 };
1161 let keeper = keeper::Keeper::from_env(&env);
1162 if let Err(error) = billing.settle_runs(&keeper).await {
1163 worker::console_error!("settling runs failed: {error}");
1164 }
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1165 // Stripe events billing never received, handled now.
1166 match billing.replay_events().await {
1167 Ok(done) => worker::console_log!("stripe replay: {done}"),
1168 Err(error) => worker::console_error!("replaying Stripe events failed: {error}"),
1169 }
Billing accounts, terms and enterprises; g1t is no longer free1170 if let Err(error) = billing.autopay().await {
1171 worker::console_error!("paying at the limit failed: {error}");
1172 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1173 // AI credit below a workspace's auto-reload threshold, reloaded (ai.rs).
1174 match billing.reload_ai_credit().await {
1175 Ok(0) => {}
1176 Ok(done) => worker::console_log!("auto-reloaded AI credit for {done} workspaces"),
1177 Err(error) => worker::console_error!("auto-reloading AI credit failed: {error}"),
1178 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1179 // Last month's metered usage (scans, embeddings, storage) goes on the
1180 // ledger before the month is closed and invoiced.
1181 if let Err(error) = billing.charge_pending().await {
1182 worker::console_error!("charging last month's metered usage failed: {error}");
1183 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1184 if let Err(error) = billing.close_months().await {
1185 worker::console_error!("closing the month failed: {error}");
1186 }
Stripe webhooks, enterprise invoices, and sudo for both1187 if let Err(error) = billing.invoice_enterprises().await {
1188 worker::console_error!("invoicing enterprises failed: {error}");
1189 }
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays1190 // Comped budgets' alerts, and a tripped breaker staff were not told of.
1191 if let Err(error) = billing.watch_spend().await {
1192 worker::console_error!("watching g1t's own spend failed: {error}");
1193 }
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1194 if let Ok(identity) = env.service("IDENTITY")
1195 && let Err(error) = billing.warn_limits(&identity).await {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1196 worker::console_error!("warning owners failed: {error}");
1197 }
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1198 // Once a day: Stripe's endpoint kept listening to billing's events and
1199 // enabled, and saved cards and plans not read in a while read again.
1200 if event.cron() == keeper::DAILY {
Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard1201 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 kept1202 Ok(done) => worker::console_log!("stripe endpoint: {done}"),
1203 Err(error) => worker::console_error!("keeping Stripe's endpoint failed: {error}"),
1204 }
1205 match billing.refresh_from_stripe().await {
1206 Ok(done) => worker::console_log!("stripe refresh: {done}"),
1207 Err(error) => worker::console_error!("refreshing from Stripe failed: {error}"),
1208 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1209 }
The keeper reads Cloudflare as it really answers1210 // Once a day, and at once if the costs were never checked: check every
1211 // 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 kept1212 if (event.cron() == keeper::DAILY || billing.never_checked().await.unwrap_or(false))
1213 && let Err(error) = billing.reconcile(&keeper).await {
Prices keep themselves current with what g1t pays1214 worker::console_error!("checking costs against Cloudflare failed: {error}");
1215 }
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging1216 // Once a day: credit from g1t past its expiry stops counting
1217 // (grants.rs), before the day is reconciled.
1218 if event.cron() == keeper::DAILY {
1219 match billing.expire_credits().await {
1220 Ok(closed) => worker::console_log!("credits expired: {closed}"),
1221 Err(error) => worker::console_error!("expiring credits failed: {error}"),
1222 }
1223 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1224 // Once a day: what Cloudflare charged, reconciled against what g1t
1225 // counted and charged; prices whose day has come; margin alerts
1226 // (margin.rs). After the keeper, so its proposals are in.
1227 if event.cron() == keeper::DAILY {
1228 match billing.costs_daily(&env, &keeper).await {
1229 Ok(run) => worker::console_log!("costs: {} lines, {} days, {} proposals, {} alerts", run.lines, run.days, run.proposals, run.alerts),
1230 Err(error) => worker::console_error!("reconciling costs failed: {error}"),
1231 }
1232 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1233 // Once a day: what each workspace's private repositories hold, its git
1234 // operations, Deployments plans from before the g1t plan set to end,
1235 // and old reservations cleared.
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1236 if event.cron() == keeper::DAILY {
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member1237 if let Err(error) = billing.measure_packages().await {
1238 worker::console_error!("measuring package storage failed: {error}");
1239 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1240 if let Err(error) = billing.measure_storage().await {
1241 worker::console_error!("measuring storage failed: {error}");
1242 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1243 if let Err(error) = billing.measure_git().await {
1244 worker::console_error!("measuring git operations failed: {error}");
1245 }
1246 if let Err(error) = billing.retire_deployments_plans().await {
1247 worker::console_error!("ending Deployments plans failed: {error}");
1248 }
1249 if let Err(error) = billing.sweep_reservations().await {
1250 worker::console_error!("clearing reservations failed: {error}");
1251 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1252 }
Prices keep themselves current with what g1t pays1253}
1254
Agents and memory, checks and conflicts, profiles, slug renames, custom domains1255/// Events from the bus, on billing's own queue: only a workspace's rename
1256/// matters here (see `rename`).
1257#[event(queue)]
1258async fn queue(batch: MessageBatch<g1t_contracts::events::Event>, env: Env, _ctx: Context) -> Result<()> {
1259 let billing = Billing::from_env(&env)?;
1260 let identity = env.service("IDENTITY").ok();
1261 for message in batch.messages()? {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1262 // A repository transferred: its share of the open-source pool this
1263 // month follows it. What it was charged stays with the workspace
1264 // it was charged to; usage from now on is charged to the new one.
1265 if g1t_kit::transfer::on_event(&env, &billing.db, message.body(), closing::TRANSFERRED).await? {
1266 message.ack();
1267 continue;
1268 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains1269 billing.on_event(identity.as_ref(), message.body()).await?;
1270 message.ack();
1271 }
1272 Ok(())
1273}
1274
Agents as a team: lifecycle, merge queue, billing and a new shell1275#[event(fetch)]
1276async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> {
1277 let Some(method) = rpc_method(&request) else {
1278 return Response::error("Not found", 404);
1279 };
Fast pages, required checks on the branch, self-hosted runners, honest incidents1280 // A replica near the caller when it asks for one (crates/kit/src/d1.rs);
1281 // what other services call (can_start, start_run) asks for none.
1282 let (db, served) = g1t_kit::d1::open(&env, "DB", &request)?;
Agents as a team: lifecycle, merge queue, billing and a new shell1283 let body: serde_json::Value = request.json().await?;
Fast pages, required checks on the branch, self-hosted runners, honest incidents1284 let mut billing = Billing::from_env(&env)?;
1285 billing.db = db;
1286 let answered = match method.as_str() {
Agents as a team: lifecycle, merge queue, billing and a new shell1287 "status" => reply(&billing.status()),
1288 "account" => reply(&billing.account(args(body)?).await?),
1289 "ledger" => reply(&billing.ledger(args(body)?).await?),
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging1290 "credits" => reply(&billing.credits(args(body)?).await?),
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request1291 "usage" => reply(&billing.usage(args(body)?).await?),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1292 "usage_report" => reply(&billing.usage_report(args(body)?).await?),
1293 "ai_credit" => reply(&billing.ai_credit(args(body)?).await?),
1294 "buy_ai_credit" => reply(&billing.buy_ai_credit(args(body)?).await?),
1295 "confirm_ai_credit" => reply(&billing.confirm_ai_credit(args(body)?).await?),
1296 "set_ai_reload" => reply(&billing.set_ai_reload(args(body)?).await?),
1297 "set_budget" => reply(&billing.set_budget(args(body)?).await?),
1298 "billing_details" => reply(&billing.billing_details(args(body)?).await?),
1299 "set_billing_details" => reply(&billing.set_billing_details(args(body)?).await?),
Mission control shows model usage, yours and the workspace's: tokens, cost, active days, cache share, each day, and the mix1300 "record_tokens" => reply(&billing.record_tokens(args(body)?).await?),
1301 "token_usage" => reply(&billing.token_usage(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1302 "checkout" => reply(&billing.checkout(args(body)?).await?),
1303 "confirm" => reply(&billing.confirm(args(body)?).await?),
1304 "can_start" => reply(&billing.can_start(args(body)?).await?),
A free allowance on g1t's models, so anyone can try its agents1305 "trial" => reply(&billing.trial(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1306 "start_run" => reply(&billing.start_run(args(body)?).await?),
1307 "finish_run" => reply(&billing.finish_run(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan1308 "features" => reply(&billing.features(args(body)?).await?),
1309 "subscribe" => reply(&billing.subscribe(args(body)?).await?),
1310 "confirm_subscription" => reply(&billing.confirm_subscription(args(body)?).await?),
1311 "cancel_subscription" => reply(&billing.cancel_subscription(args(body)?).await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1312 "close_workspace" => reply(&billing.close_workspace(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan1313 "has_feature" => reply(&billing.has_feature(args(body)?).await?),
Billing: Stripe Tax on every payment, the card fee on every card payment, and free_workspaces1314 "free_workspaces" => reply(&billing.free_workspaces(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan1315 "charge_feature" => reply(&billing.charge_feature(args(body)?).await?),
Every sandbox is metered by the second1316 "record_sandbox" => reply(&billing.record_sandbox(args(body)?).await?),
Usage limits: unpaid usage can only go so far1317 "limit" => reply(&billing.limit(args(body)?).await?),
1318 "check_limit" => reply(&billing.check_limit(args(body)?).await?),
1319 "set_spend_limit" => reply(&billing.set_spend_limit(args(body)?).await?),
Prices keep themselves current with what g1t pays1320 "prices" => reply(&billing.prices().await?),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1321 "billing_portal" => reply(&billing.billing_portal(args(body)?).await?),
1322 "admin_billing_link" => reply(&billing.admin_billing_link(args(body)?).await?),
Stripe webhooks, enterprise invoices, and sudo for both1323 "admin_stripe" => reply(&billing.admin_stripe(args(body)?).await?),
1324 "admin_enterprise_billing" => reply(&billing.admin_enterprise_billing(args(body)?).await?),
Billing: Stripe Tax on every payment, the card fee on every card payment, and free_workspaces1325 "admin_enterprise_address" => reply(&billing.admin_enterprise_address(args(body)?).await?),
Stripe webhooks, enterprise invoices, and sudo for both1326 "admin_invoice_enterprise" => reply(&billing.admin_invoice_enterprise(args(body)?).await?),
1327 "stripe_webhook" => reply(&billing.stripe_webhook(args(body)?).await?),
Two limits, real invoices, trust that grows by itself, sales signals1328 "invoices" => reply(&billing.invoices(args(body)?).await?),
The statement is a month at a time, a line per kind of charge1329 "statement" => reply(&billing.statement(args(body)?).await?),
1330 "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 quotas1331 "usage_meters" => reply(&billing.usage_meters(args(body)?).await?),
Two limits, real invoices, trust that grows by itself, sales signals1332 "admin_workspace_invoices" => {
1333 let a: AdminWorkspaceInvoicesArgs = args(body)?;
1334 reply(&billing.workspace_invoices(&a.workspace.to_lowercase()).await?)
1335 }
1336 "admin_signals" => reply(&billing.admin_signals(args(body)?).await?),
1337 "admin_overview" => reply(&billing.admin_overview(args(body)?).await?),
1338 "admin_sales" => reply(&billing.admin_sales(args(body)?).await?),
1339 "admin_set_sales" => reply(&billing.admin_set_sales(args(body)?).await?),
1340 "admin_add_note" => reply(&billing.admin_add_note(args(body)?).await?),
Billing lists every invoice and every staff change; signals carry follow-ups1341 "admin_invoices" => reply(&billing.admin_invoices(args(body)?).await?),
1342 "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 member1343 // A staff change made in another service, for sudo's audit log:
1344 // identity's restores and purges of deleted workspaces.
1345 "admin_log" => {
1346 let a: AdminLogArgs = args(body)?;
1347 billing
1348 .audit(&accounts::own_account(&a.workspace), &a.action, &a.detail, &a.by)
1349 .await?;
1350 reply(&true)
1351 }
Prices keep themselves current with what g1t pays1352 "note_pending" => reply(&billing.note_pending(args(body)?).await?),
Billing accounts, terms and enterprises; g1t is no longer free1353 "admin_accounts" => reply(&billing.admin_accounts(args(body)?).await?),
1354 "admin_account" => reply(&billing.admin_account(args(body)?).await?),
1355 "admin_set_terms" => reply(&billing.admin_set_terms(args(body)?).await?),
1356 "admin_create_enterprise" => reply(&billing.admin_create_enterprise(args(body)?).await?),
1357 "admin_attach" => reply(&billing.admin_attach(args(body)?).await?),
1358 "admin_credit" => reply(&billing.admin_credit(args(body)?).await?),
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging1359 "admin_credits" => reply(&billing.admin_credits(args(body)?).await?),
1360 "admin_revoke_credit" => reply(&billing.admin_revoke_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 sold1361 "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 put1362 "admin_set_allowances" => reply(&billing.admin_set_allowances(args(body)?).await?),
1363 "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 sudo1364 "audit_retention" => reply(&billing.audit_retention(args(body)?).await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1365 "reserve" => reply(&billing.reserve(args(body)?).await?),
1366 "settle" => reply(&billing.settle_reservation(args(body)?).await?),
1367 "card_check" => reply(&billing.card_check(args(body)?).await?),
1368 "confirm_card_check" => reply(&billing.confirm_card_check(args(body)?).await?),
1369 "request_limit" => reply(&billing.request_limit(args(body)?).await?),
1370 "limit_requests" => reply(&billing.limit_requests(args(body)?).await?),
1371 "confirm_spike" => reply(&billing.confirm_spike(args(body)?).await?),
1372 "set_caps" => reply(&billing.set_caps(args(body)?).await?),
1373 "admin_limit_requests" => reply(&billing.admin_limit_requests(args(body)?).await?),
1374 "admin_decide_limit_request" => reply(&billing.admin_decide_limit_request(args(body)?).await?),
1375 "admin_overages" => reply(&billing.admin_overages(args(body)?).await?),
1376 "admin_goodwill" => reply(&billing.admin_goodwill(args(body)?).await?),
1377 "admin_velocity" => reply(&billing.admin_velocity(args(body)?).await?),
1378 "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 daily1379 "admin_costs" => reply(&billing.admin_costs(args(body)?, keeper::Keeper::from_env(&env).can_read_bill()).await?),
1380 "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 pays1381 "admin_spend_caps" => reply(&billing.spend_caps().await?),
1382 "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 daily1383 "admin_decide_proposal" => reply(&billing.admin_decide_proposal(args(body)?).await?),
1384 "admin_set_cost_settings" => reply(&billing.admin_set_cost_settings(args(body)?).await?),
1385 "admin_set_cost_mapping" => reply(&billing.admin_set_cost_mapping(args(body)?).await?),
1386 "admin_run_costs" => reply(&billing.admin_run_costs(&env, args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1387 _ => Response::error("Unknown method", 404),
Fast pages, required checks on the branch, self-hosted runners, honest incidents1388 };
1389 served.finish(answered)
Agents as a team: lifecycle, merge queue, billing and a new shell1390}
1391
1392#[cfg(test)]
1393mod tests {
1394 use super::*;
1395
1396 #[test]
1397 fn a_run_is_charged_its_cost_plus_the_margin() {
1398 // $0.05 at 20% is six cents.
1399 assert_eq!(charge_micros(0.05, 20), 60_000);
1400 assert_eq!(charge_micros(1.0, 20), 1_200_000);
1401 assert_eq!(charge_micros(0.05, 0), 50_000);
1402 }
1403
1404 #[test]
1405 fn fractions_of_a_millionth_round_up_and_nothing_costs_less_than_nothing() {
1406 assert_eq!(charge_micros(0.000_000_4, 20), 2);
1407 assert_eq!(charge_micros(0.0, 20), 0);
1408 assert_eq!(charge_micros(-3.0, 20), 0);
1409 }
1410
1411 #[test]
Prices are what g1t pays plus 20%, from the first second1412 fn sandbox_time_is_charged_from_the_first_second() {
1413 // 21 millionths a second at cost, plus 20%.
1414 let price = Price::price_for(21.0, 20);
1415 assert_eq!(sandbox_charge(1, price), 26);
1416 assert_eq!(sandbox_charge(60, price), 1_512);
1417 assert_eq!(sandbox_charge(0, price), 0);
Every sandbox is metered by the second1418 }
1419
1420 #[test]
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1421 fn prepaying_starts_at_twenty_five_dollars_and_bank_transfers_at_a_thousand() {
1422 assert!(prepay_amount(2_500, false).is_ok());
1423 assert!(prepay_amount(2_499, false).is_err());
1424 assert!(prepay_amount(10_000, false).is_ok());
1425 assert!(prepay_amount(1_000_000, false).is_ok());
1426 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.");
1427 assert!(prepay_amount(99_999, true).is_err());
1428 assert!(prepay_amount(100_000, true).is_ok());
1429 }
1430
1431 #[test]
Every sandbox is metered by the second1432 fn durations_read_plainly() {
1433 assert_eq!(duration(40), "40s");
1434 assert_eq!(duration(192), "3m 12s");
1435 assert_eq!(duration(3720), "1h 2m");
1436 }
1437
1438 #[test]
Agents as a team: lifecycle, merge queue, billing and a new shell1439 fn an_absurd_cost_is_capped() {
1440 assert_eq!(charge_micros(1e9, 20), 120 * MICROS_PER_DOLLAR);
1441 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1442
1443 /// Every migration, in order, as D1 applies them.
1444 const MIGRATIONS: &[&str] = &[
1445 include_str!("../migrations/0001_init.sql"),
1446 include_str!("../migrations/0002_own_provider.sql"),
1447 include_str!("../migrations/0003_subscriptions.sql"),
1448 include_str!("../migrations/0004_sandbox_time.sql"),
1449 include_str!("../migrations/0005_limits.sql"),
1450 include_str!("../migrations/0006_prices.sql"),
1451 include_str!("../migrations/0007_pending_usage.sql"),
1452 include_str!("../migrations/0008_accounts.sql"),
1453 include_str!("../migrations/0009_autopay.sql"),
1454 include_str!("../migrations/0010_month_close.sql"),
1455 include_str!("../migrations/0011_limit_warnings.sql"),
1456 include_str!("../migrations/0012_stripe_webhooks.sql"),
1457 include_str!("../migrations/0013_invoices_trust_sales.sql"),
1458 include_str!("../migrations/0014_custom_domain_price.sql"),
1459 include_str!("../migrations/0015_sandbox_at_cost.sql"),
1460 include_str!("../migrations/0016_plans_and_pools.sql"),
1461 include_str!("../migrations/0017_flagon_comped.sql"),
1462 include_str!("../migrations/0018_one_plan.sql"),
1463 include_str!("../migrations/0019_closed_workspaces.sql"),
1464 include_str!("../migrations/0020_syntaqx_standard.sql"),
1465 include_str!("../migrations/0021_no_quotas.sql"),
1466 include_str!("../migrations/0022_costs_and_margin.sql"),
1467 include_str!("../migrations/0023_one_operation_mapping.sql"),
1468 include_str!("../migrations/0024_spend_caps.sql"),
1469 include_str!("../migrations/0025_run_tier.sql"),
1470 include_str!("../migrations/0026_ledger_by_workspace_time.sql"),
1471 include_str!("../migrations/0027_stripe_cache.sql"),
1472 include_str!("../migrations/0028_drop_stripe_webhooks.sql"),
1473 include_str!("../migrations/0029_audit_retention.sql"),
1474 include_str!("../migrations/0030_token_usage.sql"),
1475 include_str!("../migrations/0031_package_storage.sql"),
1476 include_str!("../migrations/0032_workspace_value.sql"),
1477 include_str!("../migrations/0033_given_away.sql"),
1478 include_str!("../migrations/0034_given_by_why.sql"),
1479 include_str!("../migrations/0035_cf_subscriptions.sql"),
1480 include_str!("../migrations/0036_model_costs_in_full.sql"),
1481 include_str!("../migrations/0037_security_activation.sql"),
1482 include_str!("../migrations/0038_staff_credits.sql"),
1483 include_str!("../migrations/0039_discounts_not_comped.sql"),
1484 include_str!("../migrations/0040_ai_credit.sql"),
1485 ];
1486
1487 /// The columns of `table` after the migrations: each with whether an
1488 /// insert must give it (NOT NULL, no default).
1489 fn columns(table: &str) -> Vec<(String, bool)> {
1490 let mut out = vec![];
1491 for sql in MIGRATIONS {
1492 let sql: String = sql.lines().map(|l| l.split("--").next().unwrap_or("")).collect::<Vec<_>>().join("\n");
1493 if let Some(start) = sql.find(&format!("CREATE TABLE {table} (")) {
1494 let body = &sql[start + format!("CREATE TABLE {table} (").len()..];
1495 let body = &body[..body.find(");").unwrap()];
1496 for column in body.split(",\n") {
1497 let column = column.trim();
1498 let name = column.split_whitespace().next().unwrap_or("").to_owned();
1499 if name.is_empty() || name == "PRIMARY" {
1500 continue;
1501 }
1502 let required = column.contains("NOT NULL") && !column.contains("DEFAULT") && !column.contains("PRIMARY KEY");
1503 out.push((name, required || column.contains("PRIMARY KEY")));
1504 }
1505 }
1506 for statement in sql.split(';') {
1507 let s = statement.trim();
1508 if let Some(rest) = s.strip_prefix(&format!("ALTER TABLE {table} ADD COLUMN ")) {
1509 let name = rest.split_whitespace().next().unwrap().to_owned();
1510 out.push((name, rest.contains("NOT NULL") && !rest.contains("DEFAULT")));
1511 }
1512 }
1513 }
1514 out
1515 }
1516
1517 /// The columns an `INSERT INTO table (…)` names.
1518 fn inserted(sql: &str, table: &str) -> Vec<String> {
1519 let start = sql.find(&format!("INSERT INTO {table} (")).unwrap() + format!("INSERT INTO {table} (").len();
1520 sql[start..start + sql[start..].find(')').unwrap()].split(',').map(|c| c.trim().to_owned()).collect()
1521 }
1522
1523
1524 #[test]
1525 fn ai_prices_are_price_book_data_with_dated_versions() {
1526 let sql = include_str!("../migrations/0040_ai_credit.sql");
1527 let row = |needle: &str| sql.lines().find(|l| l.contains(needle)).unwrap_or_else(|| panic!("no {needle}")).to_owned();
1528 // AI Gateway: the provider's price, no markup while in beta.
1529 assert!(row("('gateway_models', 'AI Gateway models'").contains("1000000, 0, 'list'"));
1530 // Models lose their markup from 2026-10-08, a fall that applies at once…
1531 assert!(row("('pv_agent_models_2'").contains("1000000, 0, '2026-10-08"));
1532 // …and the agent rate is $0.25 a million tokens after 14 days' notice.
1533 assert!(row("('pv_agent_tokens_2'").contains("250000, 0, '2026-10-22"));
1534 // The card fee is 2.9% + 30¢, switchable.
1535 assert!(row("('card_fee_percent'").contains("29000"));
1536 assert!(row("('card_fee_fixed'").contains("300000"));
1537 assert!(row("('card_fee', 'on'").contains("'on'"));
1538 }
1539 #[test]
1540 fn every_checkout_insert_fills_the_table() {
1541 // The plan's, the activation's, a card check's, a prepayment's and
1542 // AI credit's pages all go through one insert, and it names every
1543 // column the table needs and none it lacks: a missing NOT NULL
1544 // column, or one from a migration not yet applied, was a 500.
1545 let table = columns("checkouts");
1546 let names: Vec<&str> = table.iter().map(|(n, _)| n.as_str()).collect();
1547 assert_eq!(names, ["id", "workspace", "amount_cents", "created_by", "status", "created_at", "feature", "fee_cents"]);
1548 let given = inserted(CHECKOUT_INSERT, "checkouts");
1549 for column in &given {
1550 assert!(names.contains(&column.as_str()), "the insert names {column}, which checkouts does not have");
1551 }
1552 for (column, required) in &table {
1553 assert!(!required || given.contains(column), "checkouts needs {column}, which the insert leaves out");
1554 }
1555 // As many values as columns.
1556 let values = CHECKOUT_INSERT.split("VALUES").nth(1).unwrap();
1557 assert_eq!(values.matches('?').count() + values.matches("'open'").count(), given.len());
1558 // And no page writes a row of its own any more.
1559 for (file, source) in [
1560 ("lib.rs", include_str!("lib.rs")),
1561 ("features.rs", include_str!("features.rs")),
1562 ("cards.rs", include_str!("cards.rs")),
1563 ("ai.rs", include_str!("ai.rs")),
1564 ] {
1565 let inserts = source.matches(concat!("INSERT INTO ", "checkouts")).count();
1566 assert!(inserts <= usize::from(file == "lib.rs"), "{file} inserts into checkouts on its own");
1567 }
1568 }
1569
1570 #[test]
1571 fn a_new_ledger_column_has_a_default() {
1572 // The ledger is written from a dozen places; a column without a
1573 // default would break every one that does not name it.
1574 for (column, required) in columns("ledger") {
1575 assert!(!required || ["id", "workspace", "kind", "amount_micros", "description", "reference", "created_at"].contains(&column.as_str()), "{column}");
1576 }
1577 }
Agents as a team: lifecycle, merge queue, billing and a new shell1578}

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