Skip to content

g1t/services/billing/src/lib.rs

1,607 lines73,718 bytesCodeBlame

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

Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1//! The billing service: what g1t's compute costs, charged to the workspace
2//! it ran for at what g1t pays plus 20%.
Agents as a team: lifecycle, merge queue, billing and a new shell3//!
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look4//! One paid plan, "g1t" (see `features`): $20 a month per workspace, never
5//! per person, with $10 of usage included, deployments, and more private
6//! storage. The forge is free for everyone; compute needs the plan or a
7//! card check (see `compute` and `cards`). Before anything that costs money
8//! starts, the service that starts it reserves its estimate here; when it
9//! is done, what it cost goes on the ledger plus the margin, drawn first
10//! from what the plan includes, a trial or g1t's pools (see `credits`).
11//! Every change is a ledger entry, and a balance is always the sum of its
12//! ledger.
Paid features: a workspace turns on Deployments with a monthly plan13//!
Agents as a team: lifecycle, merge queue, billing and a new shell14//! Without a card processor configured the service says so and charges
15//! nothing, so that g1t still runs where billing has not been set up.
16//!
17//! Reached only through service bindings; see `g1t_contracts::billing` for
18//! the methods and their arguments.
19
Billing accounts, terms and enterprises; g1t is no longer free20mod accounts;
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;
Merge Stripe Tax, the card fee on card payments, and one free workspace per person49mod 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
Merge branch 'model-routing'161#[derive(Clone, Deserialize)]
Agents as a team: lifecycle, merge queue, billing and a new shell162struct 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,
Merge Stripe Tax, the card fee on card payments, and one free workspace per person182 #[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 };
Merge Stripe Tax, the card fee on card payments, and one free workspace per person594 // 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 };
Merge Stripe Tax, the card fee on card payments, and one free workspace per person601 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 };
Merge Stripe Tax, the card fee on card payments, and one free workspace per person605 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.
Merge Stripe Tax, the card fee on card payments, and one free workspace per person655 "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 };
Merge Stripe Tax, the card fee on card payments, and one free workspace per person669 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() {
Merge Stripe Tax, the card fee on card payments, and one free workspace per person681 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
Merge Stripe Tax, the card fee on card payments, and one free workspace per person687 /// 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(),
Merge branch 'model-routing'806 // On the workspace's own provider too: the proxy counts the
807 // run's tokens under it, and the agent rate is charged on them.
808 optional(a.session.as_deref()),
809 optional(a.tier.as_deref().filter(|tier| tokens::is_tier(tier))),
Agents as a team: lifecycle, merge queue, billing and a new shell810 ])?
811 .run()
812 .await?;
813 Ok(Outcome::Ok(Some(RunTicket { run_id, token })))
814 }
815
816 async fn finish_run(&self, a: FinishRunArgs) -> Result<Outcome<bool>> {
817 let run = self
818 .db
819 .prepare(
Integrations: your own model provider, alerts that open issues, tickets agents read820 "SELECT workspace, repo, number, task, model, token_hash, billed_to FROM runs
Agents as a team: lifecycle, merge queue, billing and a new shell821 WHERE id = ? AND finished_at IS NULL",
822 )
823 .bind(&[a.run_id.as_str().into()])?
824 .first::<RunRow>(None)
825 .await?;
826 let Some(run) = run.filter(|run| run.token_hash == hash(&a.token)) else {
827 return Ok(Outcome::fail(FailureCode::NotFound, "Run not found."));
828 };
829 if !a.cost_usd.is_finite() || a.cost_usd < 0.0 {
830 return Ok(Outcome::fail(FailureCode::Invalid, "That is not a cost."));
831 }
832 // Only whoever closes the run charges for it.
833 let claimed = self
834 .db
835 .prepare(
836 "UPDATE runs SET finished_at = ? WHERE id = ? AND finished_at IS NULL RETURNING id",
837 )
838 .bind(&[rfc3339(now_ms()).into(), a.run_id.as_str().into()])?
839 .first::<Touched>(None)
840 .await?;
841 if claimed.is_none() {
842 return Ok(Outcome::Ok(false));
843 }
Merge branch 'model-routing'844 // On the workspace's own provider, the model was paid for there and
845 // the run's sandbox time is recorded on its own: only the agent rate
846 // is charged, on its own meter.
Prices are what g1t pays plus 20%, from the first second847 if run.own_provider() {
Merge branch 'model-routing'848 self.charge_agent_rate(&a.run_id, &run, a.tokens).await?;
Prices are what g1t pays plus 20%, from the first second849 return Ok(Outcome::Ok(true));
850 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look851 // Its cost plus the margin, on the account's terms; then the plan's
852 // included usage and the trial credit pay what they can, and g1t
853 // covers a free workspace's overrun (see `credits`). Agents are
854 // never the open-source pool's.
Usage, Billing settings and prepaid AI credit; fixes from the UX audit855 // The model at the provider's price and the price book's markup on it
856 // (`agent_models`: none from 2026-10-08); g1t's own part is the agent
857 // rate, charged on a line of its own below.
858 let base = charge_micros(a.cost_usd, self.model_markup().await?);
Merge branch 'worktree-agent-a633ac0f7f66d419d'859 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 put860 let month = credits::month_of(&rfc3339(now_ms()));
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look861 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 put862 let drawn = self.draw(&run.workspace, charge, &month, &eligible).await?;
Integrations: your own model provider, alerts that open issues, tickets agents read863 let mut description = match run.task.as_str() {
Agents as a team: lifecycle, merge queue, billing and a new shell864 "plan" => format!("Planning for {}", run.repo),
865 "review" => format!("Review of {}#{}", run.repo, run.number),
866 "update" => format!("Catching up {}#{}", run.repo, run.number),
867 _ => format!("Work on {}#{}", run.repo, run.number),
868 };
Billing accounts, terms and enterprises; g1t is no longer free869 description.push_str(&terms_note);
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put870 description.push_str(&drawn.note());
Agents as a team: lifecycle, merge queue, billing and a new shell871 self.enter(
872 &run.workspace,
873 EntryKind::Usage,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put874 -(charge - drawn.total()),
Agents as a team: lifecycle, merge queue, billing and a new shell875 &description,
876 &a.run_id,
877 Some(&run),
878 Some(charge_micros(a.cost_usd, 0)),
879 None,
880 None,
881 )
882 .await?;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put883 self.record_drawn(&a.run_id, &drawn).await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'884 self.record_discount(&a.run_id, discount).await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays885 self.count_spend(&run.workspace, charge_micros(a.cost_usd, 0), charge - drawn.total(), &drawn).await;
Merge branch 'model-routing'886 self.charge_agent_rate(&a.run_id, &run, a.tokens).await?;
Agents as a team: lifecycle, merge queue, billing and a new shell887 Ok(Outcome::Ok(true))
888 }
889}
890
Every sandbox is metered by the second891impl Billing {
Prices are what g1t pays plus 20%, from the first second892 /// 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 look893 /// second, from the first, at the price book's price; on its own CPU
894 /// when it reports it. Settles its reservation, if it names one.
Every sandbox is metered by the second895 async fn record_sandbox(&self, a: RecordSandboxArgs) -> Result<Outcome<bool>> {
Fast pages, required checks on the branch, self-hosted runners, honest incidents896 // Self-hosted time is recorded wherever g1t runs, for its minutes;
897 // anything else only where there is a bill to put it on.
898 if (self.stripe.is_none() && !a.self_hosted) || a.seconds == 0 {
Every sandbox is metered by the second899 return Ok(Outcome::Ok(false));
900 }
901 let workspace = a.workspace.to_lowercase();
902 let seen = self
903 .db
904 .prepare("SELECT id FROM ledger WHERE reference = ?")
905 .bind(&[a.reference.as_str().into()])?
906 .first::<Touched>(None)
907 .await?;
908 if seen.is_some() {
909 return Ok(Outcome::Ok(false));
910 }
911 let now = now_ms();
912 let timestamp = rfc3339(now);
913 let seconds = i64::from(a.seconds);
Fast pages, required checks on the branch, self-hosted runners, honest incidents914 // On the workspace's own machine: its minutes go on usage, at $0,
915 // and whatever was reserved for it is given back.
916 if a.self_hosted {
917 let description = format!("{}: {} of self-hosted runner time, $0", a.description, duration(seconds));
918 self.db
919 .prepare(
920 "INSERT INTO ledger
921 (id, workspace, kind, amount_micros, description, repo, task,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit922 cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros, quantity)
923 VALUES (?, ?, 'usage', 0, ?, ?, 'self_hosted', 0, ?, ?, 'workspace', 0, 0, 0, 0, ?)",
Fast pages, required checks on the branch, self-hosted runners, honest incidents924 )
925 .bind(&[
926 new_id("led", now).into(),
927 workspace.as_str().into(),
928 description.as_str().into(),
929 optional(a.repo.as_deref()),
930 a.reference.as_str().into(),
931 timestamp.as_str().into(),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit932 (seconds as f64).into(),
Fast pages, required checks on the branch, self-hosted runners, honest incidents933 ])?
934 .run()
935 .await?;
936 if let Some(reservation) = &a.reservation_id {
937 self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: 0 }).await?;
938 }
939 return Ok(Outcome::Ok(true));
940 }
Prices are what g1t pays plus 20%, from the first second941 // From the price book, which follows what Cloudflare bills g1t. A
942 // sandbox is the same container as a build, so without a row it is
943 // a build second's cost plus the margin.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look944 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 quotas945 let cost = deployment_costs::MICROS_PER_BUILD_SECOND as f64;
Prices are what g1t pays plus 20%, from the first second946 (cost, Price::price_for(cost, self.margin_percent))
947 });
Fast pages, required checks on the branch, self-hosted runners, honest incidents948 // A larger machine (`runs-on: g1t-4core`): its memory and disk
949 // cost more each second, and without its own CPU it is priced at
950 // its vCPUs as busy as the standard machine's.
951 let instance = a.instance.as_deref().and_then(g1t_contracts::actions::instance_named);
952 let base_scale = instance.map_or(1.0, |i| keeper::base_scale(i.memory_gib, i.disk_gb));
953 let price_scale = instance.map_or(1.0, |i| i.price_scale);
954 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 look955 // Its own CPU when the sandbox reports it; otherwise the average.
956 let parts = match a.cpu_seconds.filter(|cpu| cpu.is_finite() && *cpu >= 0.0) {
957 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 incidents958 (Some((base, _)), Some((vcpu, _))) => {
959 Some((keeper::run_cost(seconds, cpu.min(seconds as f64 * vcpus), base * base_scale, vcpu), cpu))
960 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look961 _ => None,
962 },
963 None => None,
964 };
Fast pages, required checks on the branch, self-hosted runners, honest incidents965 let cost = parts.map_or(seconds as f64 * cost_per_second * price_scale, |(cost, _)| cost).ceil() as i64;
Merge branch 'worktree-agent-a633ac0f7f66d419d'966 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 look967 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 put968 let drawn = self.draw(&workspace, charge, &credits::month_of(&timestamp), &eligible).await?;
969 let charge = charge - drawn.total();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look970 let cpu_note = parts.map_or(String::new(), |(_, cpu)| format!(", {cpu:.0} vCPU-seconds"));
971 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 daily972 // The price versions it was charged at (pricing.rs).
973 let meters: &[&str] = if parts.is_some() { &["sandbox_base_second", "sandbox_cpu_second"] } else { &["sandbox_second"] };
974 let mut versions = Vec::new();
975 for meter in meters {
976 versions.extend(self.version_now(meter).await?);
977 }
978 let price_version = versions.join(",");
Every sandbox is metered by the second979 self.db
980 .batch(vec![
981 self.db
982 .prepare(
983 "INSERT INTO ledger
984 (id, workspace, kind, amount_micros, description, repo, task,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit985 cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros, price_version, quantity, compute)
986 VALUES (?, ?, 'usage', ?, ?, ?, 'sandbox', ?, ?, ?, 'g1t', ?, ?, ?, ?, ?, ?, ?)",
Every sandbox is metered by the second987 )
988 .bind(&[
989 new_id("led", now).into(),
990 workspace.as_str().into(),
991 (-(charge as f64)).into(),
992 description.as_str().into(),
993 optional(a.repo.as_deref()),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look994 (cost as f64).into(),
Every sandbox is metered by the second995 a.reference.as_str().into(),
996 timestamp.as_str().into(),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put997 (drawn.credit as f64).into(),
998 (drawn.trial as f64).into(),
999 (drawn.oss as f64).into(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1000 (drawn.given as f64).into(),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1001 optional(Some(price_version.as_str()).filter(|v| !v.is_empty())),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1002 (seconds as f64).into(),
1003 optional(a.kind.map(ComputeKind::as_str)),
Every sandbox is metered by the second1004 ])?,
1005 self.db
1006 .prepare(
1007 "INSERT INTO accounts (workspace, balance_micros, created_at)
1008 VALUES (?1, ?2, ?3)
1009 ON CONFLICT (workspace) DO UPDATE SET balance_micros = balance_micros + ?2",
1010 )
1011 .bind(&[
1012 workspace.as_str().into(),
1013 (-(charge as f64)).into(),
1014 timestamp.as_str().into(),
1015 ])?,
1016 ])
1017 .await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'1018 self.record_discount(&a.reference, discount).await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays1019 self.count_spend(&workspace, cost, charge, &drawn).await;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1020 if let Some(reservation) = &a.reservation_id {
1021 self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: cost }).await?;
1022 }
Every sandbox is metered by the second1023 Ok(Outcome::Ok(true))
1024 }
1025}
1026
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1027/// Whether an amount may be prepaid: $25 at the least by card, and from
1028/// $1,000 by bank transfer.
1029pub(crate) fn prepay_amount(cents: u32, bank_transfer: bool) -> std::result::Result<(), String> {
1030 let (min, max) = if bank_transfer { (MIN_BANK_TRANSFER_CENTS, MAX_BANK_TRANSFER_CENTS) } else { (MIN_TOP_UP_CENTS, MAX_TOP_UP_CENTS) };
1031 if (min..=max).contains(&cents) {
1032 return Ok(());
1033 }
1034 Err(if bank_transfer {
1035 format!("Prepay between ${} and ${} by bank transfer.", min / 100, group(max / 100))
1036 } else {
1037 format!("Prepay between ${} and ${} by card; from $1,000, a bank transfer works too.", min / 100, group(max / 100))
1038 })
1039}
1040
1041/// `10,000` for 10000.
1042fn group(n: u32) -> String {
1043 let digits = n.to_string();
1044 let mut out = String::new();
1045 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 kept1046 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 look1047 out.push(',');
1048 }
1049 out.push(c);
1050 }
1051 out
1052}
1053
1054#[cfg(test)]
Prices are what g1t pays plus 20%, from the first second1055/// What `seconds` of sandbox time are charged at `price_per_second`, in
1056/// millionths of a dollar: every second, rounded up to the next millionth.
1057fn sandbox_charge(seconds: i64, price_per_second: f64) -> i64 {
1058 (seconds as f64 * price_per_second).ceil() as i64
Every sandbox is metered by the second1059}
1060
1061/// `1h 2m`, `3m 12s` or `40s`.
1062fn duration(seconds: i64) -> String {
1063 let (h, m, s) = (seconds / 3600, seconds % 3600 / 60, seconds % 60);
1064 if h > 0 {
1065 format!("{h}h {m}m")
1066 } else if m > 0 {
1067 format!("{m}m {s}s")
1068 } else {
1069 format!("{s}s")
1070 }
1071}
1072
Billing accounts, terms and enterprises; g1t is no longer free1073impl Billing {
1074 /// What a workspace is charged for something that would be `base`:
1075 /// nothing while g1t is free, or as its account's terms say. With a
1076 /// note for the statement when it differs.
Merge branch 'worktree-agent-a633ac0f7f66d419d'1077 /// A charge at cost plus the margin (`base`) on the account's terms:
1078 /// what is charged, the note for the statement, and what a discount
1079 /// gave away below `base`. That last is written on the entry
1080 /// (`record_discount`) so the reconciliation counts it as given, never
1081 /// as margin lost: a sold charge is worth at least its cost plus the
1082 /// margin.
1083 pub(crate) async fn charged(&self, workspace: &str, base: i64) -> Result<(i64, String, i64)> {
Billing accounts, terms and enterprises; g1t is no longer free1084 if self.free {
Merge branch 'worktree-agent-a633ac0f7f66d419d'1085 return Ok((0, " (free while g1t is being built out)".to_owned(), 0));
Billing accounts, terms and enterprises; g1t is no longer free1086 }
1087 let terms = self.terms_of(workspace).await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'1088 let (charge, discount) = terms.discounted(base);
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging1089 let note = match terms.discount_label() {
1090 Some(label) if base > 0 => format!(" ({label})"),
Billing accounts, terms and enterprises; g1t is no longer free1091 _ => String::new(),
1092 };
Merge branch 'worktree-agent-a633ac0f7f66d419d'1093 Ok((charge, note, discount))
1094 }
1095
1096 /// What a discount gave away on an entry, below cost plus the margin
1097 /// (less than nothing on a correction down).
1098 pub(crate) async fn record_discount(&self, reference: &str, micros: i64) -> Result<()> {
1099 if micros == 0 {
1100 return Ok(());
1101 }
1102 self.db
1103 .prepare("UPDATE ledger SET discount_micros = ? WHERE reference = ?")
1104 .bind(&[(micros as f64).into(), reference.into()])?
1105 .run()
1106 .await?;
1107 Ok(())
Billing accounts, terms and enterprises; g1t is no longer free1108 }
1109}
1110
Agents as a team: lifecycle, merge queue, billing and a new shell1111fn members_only<T>() -> Outcome<T> {
1112 Outcome::fail(
1113 FailureCode::Forbidden,
1114 "Only members can see a workspace's billing.",
1115 )
1116}
1117
Prices keep themselves current with what g1t pays1118impl Billing {
1119 fn from_env(env: &Env) -> Result<Self> {
1120 Ok(Billing {
1121 db: env.d1("DB")?,
1122 stripe: env
1123 .secret("STRIPE_SECRET_KEY")
1124 .ok()
1125 .map(|key| key.to_string())
1126 .filter(|key| !key.is_empty())
1127 .map(Stripe::new),
Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard1128 webhook_secret: env
1129 .secret("STRIPE_WEBHOOK_SECRET")
1130 .ok()
1131 .map(|secret| secret.to_string().trim().to_owned())
1132 .filter(|secret| !secret.is_empty()),
Prices keep themselves current with what g1t pays1133 margin_percent: env
1134 .var("MARGIN_PERCENT")
1135 .ok()
1136 .and_then(|percent| percent.to_string().parse().ok())
1137 .unwrap_or(20),
1138 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 kept1139 ceilings: limits::Ceilings::from_env(env),
Billing accounts, terms and enterprises; g1t is no longer free1140 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 put1141 trials_on: {
1142 let plans = credits::Config::from_env(env);
1143 plans.trial_workspace_micros > 0 && plans.trial_monthly_pool_micros > 0
Prices keep themselves current with what g1t pays1144 },
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1145 plans: credits::Config::from_env(env),
1146 repos: env.service("REPOS").ok(),
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member1147 packages: env.service("PACKAGES").ok(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1148 identity: env.service("IDENTITY").ok(),
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays1149 caps: budget::Caps::from_env(env),
1150 env: env.clone(),
Prices keep themselves current with what g1t pays1151 })
1152 }
1153}
1154
1155#[event(scheduled)]
1156async fn scheduled(event: ScheduledEvent, env: Env, _ctx: ScheduleContext) {
1157 let Ok(billing) = Billing::from_env(&env) else {
1158 return;
1159 };
1160 let keeper = keeper::Keeper::from_env(&env);
1161 if let Err(error) = billing.settle_runs(&keeper).await {
1162 worker::console_error!("settling runs failed: {error}");
1163 }
Merge branch 'model-routing'1164 if let Err(error) = billing.settle_own_runs().await {
1165 worker::console_error!("closing runs on own providers failed: {error}");
1166 }
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1167 // Stripe events billing never received, handled now.
1168 match billing.replay_events().await {
1169 Ok(done) => worker::console_log!("stripe replay: {done}"),
1170 Err(error) => worker::console_error!("replaying Stripe events failed: {error}"),
1171 }
Billing accounts, terms and enterprises; g1t is no longer free1172 if let Err(error) = billing.autopay().await {
1173 worker::console_error!("paying at the limit failed: {error}");
1174 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1175 // AI credit below a workspace's auto-reload threshold, reloaded (ai.rs).
1176 match billing.reload_ai_credit().await {
1177 Ok(0) => {}
1178 Ok(done) => worker::console_log!("auto-reloaded AI credit for {done} workspaces"),
1179 Err(error) => worker::console_error!("auto-reloading AI credit failed: {error}"),
1180 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1181 // Last month's metered usage (scans, embeddings, storage) goes on the
1182 // ledger before the month is closed and invoiced.
1183 if let Err(error) = billing.charge_pending().await {
1184 worker::console_error!("charging last month's metered usage failed: {error}");
1185 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1186 if let Err(error) = billing.close_months().await {
1187 worker::console_error!("closing the month failed: {error}");
1188 }
Stripe webhooks, enterprise invoices, and sudo for both1189 if let Err(error) = billing.invoice_enterprises().await {
1190 worker::console_error!("invoicing enterprises failed: {error}");
1191 }
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays1192 // Comped budgets' alerts, and a tripped breaker staff were not told of.
1193 if let Err(error) = billing.watch_spend().await {
1194 worker::console_error!("watching g1t's own spend failed: {error}");
1195 }
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1196 if let Ok(identity) = env.service("IDENTITY")
1197 && let Err(error) = billing.warn_limits(&identity).await {
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1198 worker::console_error!("warning owners failed: {error}");
1199 }
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1200 // Once a day: Stripe's endpoint kept listening to billing's events and
1201 // enabled, and saved cards and plans not read in a while read again.
1202 if event.cron() == keeper::DAILY {
Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard1203 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 kept1204 Ok(done) => worker::console_log!("stripe endpoint: {done}"),
1205 Err(error) => worker::console_error!("keeping Stripe's endpoint failed: {error}"),
1206 }
1207 match billing.refresh_from_stripe().await {
1208 Ok(done) => worker::console_log!("stripe refresh: {done}"),
1209 Err(error) => worker::console_error!("refreshing from Stripe failed: {error}"),
1210 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1211 }
The keeper reads Cloudflare as it really answers1212 // Once a day, and at once if the costs were never checked: check every
1213 // 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 kept1214 if (event.cron() == keeper::DAILY || billing.never_checked().await.unwrap_or(false))
1215 && let Err(error) = billing.reconcile(&keeper).await {
Prices keep themselves current with what g1t pays1216 worker::console_error!("checking costs against Cloudflare failed: {error}");
1217 }
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging1218 // Once a day: credit from g1t past its expiry stops counting
1219 // (grants.rs), before the day is reconciled.
1220 if event.cron() == keeper::DAILY {
1221 match billing.expire_credits().await {
1222 Ok(closed) => worker::console_log!("credits expired: {closed}"),
1223 Err(error) => worker::console_error!("expiring credits failed: {error}"),
1224 }
1225 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1226 // Once a day: what Cloudflare charged, reconciled against what g1t
1227 // counted and charged; prices whose day has come; margin alerts
1228 // (margin.rs). After the keeper, so its proposals are in.
1229 if event.cron() == keeper::DAILY {
1230 match billing.costs_daily(&env, &keeper).await {
1231 Ok(run) => worker::console_log!("costs: {} lines, {} days, {} proposals, {} alerts", run.lines, run.days, run.proposals, run.alerts),
1232 Err(error) => worker::console_error!("reconciling costs failed: {error}"),
1233 }
1234 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1235 // Once a day: what each workspace's private repositories hold, its git
1236 // operations, Deployments plans from before the g1t plan set to end,
1237 // and old reservations cleared.
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1238 if event.cron() == keeper::DAILY {
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member1239 if let Err(error) = billing.measure_packages().await {
1240 worker::console_error!("measuring package storage failed: {error}");
1241 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1242 if let Err(error) = billing.measure_storage().await {
1243 worker::console_error!("measuring storage failed: {error}");
1244 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1245 if let Err(error) = billing.measure_git().await {
1246 worker::console_error!("measuring git operations failed: {error}");
1247 }
1248 if let Err(error) = billing.retire_deployments_plans().await {
1249 worker::console_error!("ending Deployments plans failed: {error}");
1250 }
1251 if let Err(error) = billing.sweep_reservations().await {
1252 worker::console_error!("clearing reservations failed: {error}");
1253 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1254 }
Prices keep themselves current with what g1t pays1255}
1256
Agents and memory, checks and conflicts, profiles, slug renames, custom domains1257/// Events from the bus, on billing's own queue: only a workspace's rename
1258/// matters here (see `rename`).
1259#[event(queue)]
1260async fn queue(batch: MessageBatch<g1t_contracts::events::Event>, env: Env, _ctx: Context) -> Result<()> {
1261 let billing = Billing::from_env(&env)?;
1262 let identity = env.service("IDENTITY").ok();
1263 for message in batch.messages()? {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1264 // A repository transferred: its share of the open-source pool this
1265 // month follows it. What it was charged stays with the workspace
1266 // it was charged to; usage from now on is charged to the new one.
1267 if g1t_kit::transfer::on_event(&env, &billing.db, message.body(), closing::TRANSFERRED).await? {
1268 message.ack();
1269 continue;
1270 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains1271 billing.on_event(identity.as_ref(), message.body()).await?;
1272 message.ack();
1273 }
1274 Ok(())
1275}
1276
Agents as a team: lifecycle, merge queue, billing and a new shell1277#[event(fetch)]
1278async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> {
1279 let Some(method) = rpc_method(&request) else {
1280 return Response::error("Not found", 404);
1281 };
Fast pages, required checks on the branch, self-hosted runners, honest incidents1282 // A replica near the caller when it asks for one (crates/kit/src/d1.rs);
1283 // what other services call (can_start, start_run) asks for none.
1284 let (db, served) = g1t_kit::d1::open(&env, "DB", &request)?;
Agents as a team: lifecycle, merge queue, billing and a new shell1285 let body: serde_json::Value = request.json().await?;
Fast pages, required checks on the branch, self-hosted runners, honest incidents1286 let mut billing = Billing::from_env(&env)?;
1287 billing.db = db;
1288 let answered = match method.as_str() {
Agents as a team: lifecycle, merge queue, billing and a new shell1289 "status" => reply(&billing.status()),
1290 "account" => reply(&billing.account(args(body)?).await?),
1291 "ledger" => reply(&billing.ledger(args(body)?).await?),
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging1292 "credits" => reply(&billing.credits(args(body)?).await?),
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request1293 "usage" => reply(&billing.usage(args(body)?).await?),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1294 "usage_report" => reply(&billing.usage_report(args(body)?).await?),
1295 "ai_credit" => reply(&billing.ai_credit(args(body)?).await?),
1296 "buy_ai_credit" => reply(&billing.buy_ai_credit(args(body)?).await?),
1297 "confirm_ai_credit" => reply(&billing.confirm_ai_credit(args(body)?).await?),
1298 "set_ai_reload" => reply(&billing.set_ai_reload(args(body)?).await?),
1299 "set_budget" => reply(&billing.set_budget(args(body)?).await?),
1300 "billing_details" => reply(&billing.billing_details(args(body)?).await?),
1301 "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 mix1302 "record_tokens" => reply(&billing.record_tokens(args(body)?).await?),
1303 "token_usage" => reply(&billing.token_usage(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1304 "checkout" => reply(&billing.checkout(args(body)?).await?),
1305 "confirm" => reply(&billing.confirm(args(body)?).await?),
1306 "can_start" => reply(&billing.can_start(args(body)?).await?),
A free allowance on g1t's models, so anyone can try its agents1307 "trial" => reply(&billing.trial(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1308 "start_run" => reply(&billing.start_run(args(body)?).await?),
1309 "finish_run" => reply(&billing.finish_run(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan1310 "features" => reply(&billing.features(args(body)?).await?),
1311 "subscribe" => reply(&billing.subscribe(args(body)?).await?),
1312 "confirm_subscription" => reply(&billing.confirm_subscription(args(body)?).await?),
1313 "cancel_subscription" => reply(&billing.cancel_subscription(args(body)?).await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1314 "close_workspace" => reply(&billing.close_workspace(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan1315 "has_feature" => reply(&billing.has_feature(args(body)?).await?),
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1316 "free_workspaces" => reply(&billing.free_workspaces(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan1317 "charge_feature" => reply(&billing.charge_feature(args(body)?).await?),
Every sandbox is metered by the second1318 "record_sandbox" => reply(&billing.record_sandbox(args(body)?).await?),
Usage limits: unpaid usage can only go so far1319 "limit" => reply(&billing.limit(args(body)?).await?),
1320 "check_limit" => reply(&billing.check_limit(args(body)?).await?),
1321 "set_spend_limit" => reply(&billing.set_spend_limit(args(body)?).await?),
Prices keep themselves current with what g1t pays1322 "prices" => reply(&billing.prices().await?),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1323 "billing_portal" => reply(&billing.billing_portal(args(body)?).await?),
1324 "admin_billing_link" => reply(&billing.admin_billing_link(args(body)?).await?),
Stripe webhooks, enterprise invoices, and sudo for both1325 "admin_stripe" => reply(&billing.admin_stripe(args(body)?).await?),
1326 "admin_enterprise_billing" => reply(&billing.admin_enterprise_billing(args(body)?).await?),
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1327 "admin_enterprise_address" => reply(&billing.admin_enterprise_address(args(body)?).await?),
Stripe webhooks, enterprise invoices, and sudo for both1328 "admin_invoice_enterprise" => reply(&billing.admin_invoice_enterprise(args(body)?).await?),
1329 "stripe_webhook" => reply(&billing.stripe_webhook(args(body)?).await?),
Two limits, real invoices, trust that grows by itself, sales signals1330 "invoices" => reply(&billing.invoices(args(body)?).await?),
The statement is a month at a time, a line per kind of charge1331 "statement" => reply(&billing.statement(args(body)?).await?),
1332 "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 quotas1333 "usage_meters" => reply(&billing.usage_meters(args(body)?).await?),
Two limits, real invoices, trust that grows by itself, sales signals1334 "admin_workspace_invoices" => {
1335 let a: AdminWorkspaceInvoicesArgs = args(body)?;
1336 reply(&billing.workspace_invoices(&a.workspace.to_lowercase()).await?)
1337 }
1338 "admin_signals" => reply(&billing.admin_signals(args(body)?).await?),
1339 "admin_overview" => reply(&billing.admin_overview(args(body)?).await?),
1340 "admin_sales" => reply(&billing.admin_sales(args(body)?).await?),
1341 "admin_set_sales" => reply(&billing.admin_set_sales(args(body)?).await?),
1342 "admin_add_note" => reply(&billing.admin_add_note(args(body)?).await?),
Billing lists every invoice and every staff change; signals carry follow-ups1343 "admin_invoices" => reply(&billing.admin_invoices(args(body)?).await?),
1344 "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 member1345 // A staff change made in another service, for sudo's audit log:
1346 // identity's restores and purges of deleted workspaces.
1347 "admin_log" => {
1348 let a: AdminLogArgs = args(body)?;
1349 billing
1350 .audit(&accounts::own_account(&a.workspace), &a.action, &a.detail, &a.by)
1351 .await?;
1352 reply(&true)
1353 }
Prices keep themselves current with what g1t pays1354 "note_pending" => reply(&billing.note_pending(args(body)?).await?),
Billing accounts, terms and enterprises; g1t is no longer free1355 "admin_accounts" => reply(&billing.admin_accounts(args(body)?).await?),
1356 "admin_account" => reply(&billing.admin_account(args(body)?).await?),
1357 "admin_set_terms" => reply(&billing.admin_set_terms(args(body)?).await?),
1358 "admin_create_enterprise" => reply(&billing.admin_create_enterprise(args(body)?).await?),
1359 "admin_attach" => reply(&billing.admin_attach(args(body)?).await?),
1360 "admin_credit" => reply(&billing.admin_credit(args(body)?).await?),
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging1361 "admin_credits" => reply(&billing.admin_credits(args(body)?).await?),
1362 "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 sold1363 "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 put1364 "admin_set_allowances" => reply(&billing.admin_set_allowances(args(body)?).await?),
1365 "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 sudo1366 "audit_retention" => reply(&billing.audit_retention(args(body)?).await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1367 "reserve" => reply(&billing.reserve(args(body)?).await?),
1368 "settle" => reply(&billing.settle_reservation(args(body)?).await?),
1369 "card_check" => reply(&billing.card_check(args(body)?).await?),
1370 "confirm_card_check" => reply(&billing.confirm_card_check(args(body)?).await?),
1371 "request_limit" => reply(&billing.request_limit(args(body)?).await?),
1372 "limit_requests" => reply(&billing.limit_requests(args(body)?).await?),
1373 "confirm_spike" => reply(&billing.confirm_spike(args(body)?).await?),
1374 "set_caps" => reply(&billing.set_caps(args(body)?).await?),
1375 "admin_limit_requests" => reply(&billing.admin_limit_requests(args(body)?).await?),
1376 "admin_decide_limit_request" => reply(&billing.admin_decide_limit_request(args(body)?).await?),
1377 "admin_overages" => reply(&billing.admin_overages(args(body)?).await?),
1378 "admin_goodwill" => reply(&billing.admin_goodwill(args(body)?).await?),
1379 "admin_velocity" => reply(&billing.admin_velocity(args(body)?).await?),
1380 "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 daily1381 "admin_costs" => reply(&billing.admin_costs(args(body)?, keeper::Keeper::from_env(&env).can_read_bill()).await?),
1382 "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 pays1383 "admin_spend_caps" => reply(&billing.spend_caps().await?),
1384 "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 daily1385 "admin_decide_proposal" => reply(&billing.admin_decide_proposal(args(body)?).await?),
1386 "admin_set_cost_settings" => reply(&billing.admin_set_cost_settings(args(body)?).await?),
1387 "admin_set_cost_mapping" => reply(&billing.admin_set_cost_mapping(args(body)?).await?),
1388 "admin_run_costs" => reply(&billing.admin_run_costs(&env, args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell1389 _ => Response::error("Unknown method", 404),
Fast pages, required checks on the branch, self-hosted runners, honest incidents1390 };
1391 served.finish(answered)
Agents as a team: lifecycle, merge queue, billing and a new shell1392}
1393
1394#[cfg(test)]
1395mod tests {
1396 use super::*;
1397
1398 #[test]
1399 fn a_run_is_charged_its_cost_plus_the_margin() {
1400 // $0.05 at 20% is six cents.
1401 assert_eq!(charge_micros(0.05, 20), 60_000);
1402 assert_eq!(charge_micros(1.0, 20), 1_200_000);
1403 assert_eq!(charge_micros(0.05, 0), 50_000);
1404 }
1405
1406 #[test]
1407 fn fractions_of_a_millionth_round_up_and_nothing_costs_less_than_nothing() {
1408 assert_eq!(charge_micros(0.000_000_4, 20), 2);
1409 assert_eq!(charge_micros(0.0, 20), 0);
1410 assert_eq!(charge_micros(-3.0, 20), 0);
1411 }
1412
1413 #[test]
Prices are what g1t pays plus 20%, from the first second1414 fn sandbox_time_is_charged_from_the_first_second() {
1415 // 21 millionths a second at cost, plus 20%.
1416 let price = Price::price_for(21.0, 20);
1417 assert_eq!(sandbox_charge(1, price), 26);
1418 assert_eq!(sandbox_charge(60, price), 1_512);
1419 assert_eq!(sandbox_charge(0, price), 0);
Every sandbox is metered by the second1420 }
1421
1422 #[test]
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1423 fn prepaying_starts_at_twenty_five_dollars_and_bank_transfers_at_a_thousand() {
1424 assert!(prepay_amount(2_500, false).is_ok());
1425 assert!(prepay_amount(2_499, false).is_err());
1426 assert!(prepay_amount(10_000, false).is_ok());
1427 assert!(prepay_amount(1_000_000, false).is_ok());
1428 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.");
1429 assert!(prepay_amount(99_999, true).is_err());
1430 assert!(prepay_amount(100_000, true).is_ok());
1431 }
1432
1433 #[test]
Every sandbox is metered by the second1434 fn durations_read_plainly() {
1435 assert_eq!(duration(40), "40s");
1436 assert_eq!(duration(192), "3m 12s");
1437 assert_eq!(duration(3720), "1h 2m");
1438 }
1439
1440 #[test]
Agents as a team: lifecycle, merge queue, billing and a new shell1441 fn an_absurd_cost_is_capped() {
1442 assert_eq!(charge_micros(1e9, 20), 120 * MICROS_PER_DOLLAR);
1443 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1444
1445 /// Every migration, in order, as D1 applies them.
1446 const MIGRATIONS: &[&str] = &[
1447 include_str!("../migrations/0001_init.sql"),
1448 include_str!("../migrations/0002_own_provider.sql"),
1449 include_str!("../migrations/0003_subscriptions.sql"),
1450 include_str!("../migrations/0004_sandbox_time.sql"),
1451 include_str!("../migrations/0005_limits.sql"),
1452 include_str!("../migrations/0006_prices.sql"),
1453 include_str!("../migrations/0007_pending_usage.sql"),
1454 include_str!("../migrations/0008_accounts.sql"),
1455 include_str!("../migrations/0009_autopay.sql"),
1456 include_str!("../migrations/0010_month_close.sql"),
1457 include_str!("../migrations/0011_limit_warnings.sql"),
1458 include_str!("../migrations/0012_stripe_webhooks.sql"),
1459 include_str!("../migrations/0013_invoices_trust_sales.sql"),
1460 include_str!("../migrations/0014_custom_domain_price.sql"),
1461 include_str!("../migrations/0015_sandbox_at_cost.sql"),
1462 include_str!("../migrations/0016_plans_and_pools.sql"),
1463 include_str!("../migrations/0017_flagon_comped.sql"),
1464 include_str!("../migrations/0018_one_plan.sql"),
1465 include_str!("../migrations/0019_closed_workspaces.sql"),
1466 include_str!("../migrations/0020_syntaqx_standard.sql"),
1467 include_str!("../migrations/0021_no_quotas.sql"),
1468 include_str!("../migrations/0022_costs_and_margin.sql"),
1469 include_str!("../migrations/0023_one_operation_mapping.sql"),
1470 include_str!("../migrations/0024_spend_caps.sql"),
1471 include_str!("../migrations/0025_run_tier.sql"),
1472 include_str!("../migrations/0026_ledger_by_workspace_time.sql"),
1473 include_str!("../migrations/0027_stripe_cache.sql"),
1474 include_str!("../migrations/0028_drop_stripe_webhooks.sql"),
1475 include_str!("../migrations/0029_audit_retention.sql"),
1476 include_str!("../migrations/0030_token_usage.sql"),
1477 include_str!("../migrations/0031_package_storage.sql"),
1478 include_str!("../migrations/0032_workspace_value.sql"),
1479 include_str!("../migrations/0033_given_away.sql"),
1480 include_str!("../migrations/0034_given_by_why.sql"),
1481 include_str!("../migrations/0035_cf_subscriptions.sql"),
1482 include_str!("../migrations/0036_model_costs_in_full.sql"),
1483 include_str!("../migrations/0037_security_activation.sql"),
1484 include_str!("../migrations/0038_staff_credits.sql"),
1485 include_str!("../migrations/0039_discounts_not_comped.sql"),
1486 include_str!("../migrations/0040_ai_credit.sql"),
Merge branch 'model-routing'1487 include_str!("../migrations/0041_agent_rate_own_key.sql"),
1488 include_str!("../migrations/0042_agent_rate_weights.sql"),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1489 ];
1490
1491 /// The columns of `table` after the migrations: each with whether an
1492 /// insert must give it (NOT NULL, no default).
1493 fn columns(table: &str) -> Vec<(String, bool)> {
1494 let mut out = vec![];
1495 for sql in MIGRATIONS {
1496 let sql: String = sql.lines().map(|l| l.split("--").next().unwrap_or("")).collect::<Vec<_>>().join("\n");
1497 if let Some(start) = sql.find(&format!("CREATE TABLE {table} (")) {
1498 let body = &sql[start + format!("CREATE TABLE {table} (").len()..];
1499 let body = &body[..body.find(");").unwrap()];
1500 for column in body.split(",\n") {
1501 let column = column.trim();
1502 let name = column.split_whitespace().next().unwrap_or("").to_owned();
1503 if name.is_empty() || name == "PRIMARY" {
1504 continue;
1505 }
1506 let required = column.contains("NOT NULL") && !column.contains("DEFAULT") && !column.contains("PRIMARY KEY");
1507 out.push((name, required || column.contains("PRIMARY KEY")));
1508 }
1509 }
1510 for statement in sql.split(';') {
1511 let s = statement.trim();
1512 if let Some(rest) = s.strip_prefix(&format!("ALTER TABLE {table} ADD COLUMN ")) {
1513 let name = rest.split_whitespace().next().unwrap().to_owned();
1514 out.push((name, rest.contains("NOT NULL") && !rest.contains("DEFAULT")));
1515 }
1516 }
1517 }
1518 out
1519 }
1520
1521 /// The columns an `INSERT INTO table (…)` names.
1522 fn inserted(sql: &str, table: &str) -> Vec<String> {
1523 let start = sql.find(&format!("INSERT INTO {table} (")).unwrap() + format!("INSERT INTO {table} (").len();
1524 sql[start..start + sql[start..].find(')').unwrap()].split(',').map(|c| c.trim().to_owned()).collect()
1525 }
1526
1527
1528 #[test]
1529 fn ai_prices_are_price_book_data_with_dated_versions() {
1530 let sql = include_str!("../migrations/0040_ai_credit.sql");
1531 let row = |needle: &str| sql.lines().find(|l| l.contains(needle)).unwrap_or_else(|| panic!("no {needle}")).to_owned();
1532 // AI Gateway: the provider's price, no markup while in beta.
1533 assert!(row("('gateway_models', 'AI Gateway models'").contains("1000000, 0, 'list'"));
1534 // Models lose their markup from 2026-10-08, a fall that applies at once…
1535 assert!(row("('pv_agent_models_2'").contains("1000000, 0, '2026-10-08"));
1536 // …and the agent rate is $0.25 a million tokens after 14 days' notice.
1537 assert!(row("('pv_agent_tokens_2'").contains("250000, 0, '2026-10-22"));
1538 // The card fee is 2.9% + 30¢, switchable.
1539 assert!(row("('card_fee_percent'").contains("29000"));
1540 assert!(row("('card_fee_fixed'").contains("300000"));
1541 assert!(row("('card_fee', 'on'").contains("'on'"));
1542 }
Merge branch 'model-routing'1543
1544 #[test]
1545 fn the_agent_rate_on_an_own_model_key_is_its_own_dated_meter() {
1546 let sql = include_str!("../migrations/0041_agent_rate_own_key.sql");
1547 let row = |needle: &str| sql.lines().find(|l| l.contains(needle)).unwrap_or_else(|| panic!("no {needle}")).to_owned();
1548 // Nothing until the notice has run…
1549 assert!(row("('pv_agent_tokens_own_1'").contains("0, 0, '2026-10-08"));
1550 // …then $0.25 a million tokens, as on g1t's models, 14 days after.
1551 assert!(row("('pv_agent_tokens_own_2'").contains("250000, 0, '2026-10-22"));
1552 assert!(row("('agent_tokens_own',").contains("'million tokens', 0, 0, 'list'"));
1553 assert_eq!(ai::agent_rate_meter(true), "agent_tokens_own");
1554 }
1555
1556 #[test]
1557 fn the_agent_rate_counts_every_token_once_until_a_weight_is_decided() {
1558 let sql = include_str!("../migrations/0042_agent_rate_weights.sql");
1559 for kind in ["input", "output", "cache_read", "cache_write"] {
1560 let meter = format!("('agent_token_weight_{kind}', 'Agent rate weight");
1561 let row = sql.lines().find(|l| l.contains(&meter)).unwrap_or_else(|| panic!("no {kind} weight"));
1562 assert!(row.contains("'weight', 1000000, 0, 'list'"), "{kind}: {row}");
1563 let version = format!("('pv_agent_token_weight_{kind}_1', 'agent_token_weight_{kind}', 1, 1000000,");
1564 assert!(sql.contains(&version), "{kind} has no applied version");
1565 }
1566 assert_eq!(ai::weight_of(1_000_000.0), 1.0);
1567 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1568 #[test]
1569 fn every_checkout_insert_fills_the_table() {
1570 // The plan's, the activation's, a card check's, a prepayment's and
1571 // AI credit's pages all go through one insert, and it names every
1572 // column the table needs and none it lacks: a missing NOT NULL
1573 // column, or one from a migration not yet applied, was a 500.
1574 let table = columns("checkouts");
1575 let names: Vec<&str> = table.iter().map(|(n, _)| n.as_str()).collect();
1576 assert_eq!(names, ["id", "workspace", "amount_cents", "created_by", "status", "created_at", "feature", "fee_cents"]);
1577 let given = inserted(CHECKOUT_INSERT, "checkouts");
1578 for column in &given {
1579 assert!(names.contains(&column.as_str()), "the insert names {column}, which checkouts does not have");
1580 }
1581 for (column, required) in &table {
1582 assert!(!required || given.contains(column), "checkouts needs {column}, which the insert leaves out");
1583 }
1584 // As many values as columns.
1585 let values = CHECKOUT_INSERT.split("VALUES").nth(1).unwrap();
1586 assert_eq!(values.matches('?').count() + values.matches("'open'").count(), given.len());
1587 // And no page writes a row of its own any more.
1588 for (file, source) in [
1589 ("lib.rs", include_str!("lib.rs")),
1590 ("features.rs", include_str!("features.rs")),
1591 ("cards.rs", include_str!("cards.rs")),
1592 ("ai.rs", include_str!("ai.rs")),
1593 ] {
1594 let inserts = source.matches(concat!("INSERT INTO ", "checkouts")).count();
1595 assert!(inserts <= usize::from(file == "lib.rs"), "{file} inserts into checkouts on its own");
1596 }
1597 }
1598
1599 #[test]
1600 fn a_new_ledger_column_has_a_default() {
1601 // The ledger is written from a dozen places; a column without a
1602 // default would break every one that does not name it.
1603 for (column, required) in columns("ledger") {
1604 assert!(!required || ["id", "workspace", "kind", "amount_micros", "description", "reference", "created_at"].contains(&column.as_str()), "{column}");
1605 }
1606 }
Agents as a team: lifecycle, merge queue, billing and a new shell1607}

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