Skip to content
1,710 linesCodeBlameRaw

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

Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1//! The billing service: what g1t's compute costs, charged to the workspace
2//! it ran for at what g1t pays plus 20%.
Account settings in the same shape as a workspace's3//!
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//!
Account settings in the same shape as a workspace's14//! 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;
Merge branch 'main' into actions-toolkit-oidc-artifacts23mod catalogue;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look24mod cards;
25mod closing;
26mod compute;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily27mod costs;
Merge Cloudflare's usage over its billing cycle: every page read, included amounts once a cycle, a projection, test-mode charges never money in (billing 0052)28mod cycle;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily29mod margin;
Merge platform pause and the hourly usage watcher: staff can pause compute, schedules, indexing or renders for everyone, the watcher emails on a breach and is never blind quietly, and the models proxy holds each run to its cap (billing 0051, integrations 0006)30mod platform;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily31mod pricing;
Usage, Billing settings and prepaid AI credit; fixes from the UX audit32mod report;
33mod details;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put34mod credits;
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging35mod grants;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look36mod overages;
37mod requests;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put38mod storage;
Two limits, real invoices, trust that grows by itself, sales signals39mod invoices;
40mod sales;
The statement is a month at a time, a line per kind of charge41mod statement;
Stripe webhooks, enterprise invoices, and sudo for both42mod webhooks;
Paid features: a workspace turns on Deployments with a monthly plan43mod features;
Merge the AI Gateway: Anthropic's Messages API on a workspace's tokens44mod gateway;
Prices keep themselves current with what g1t pays45mod keeper;
Usage limits: unpaid usage can only go so far46mod limits;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains47mod 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's48mod reset;
Audit logs are kept by plan: a week on free, 90 days on the plan, and what staff set for an account in sudo49mod retention;
Account settings in the same shape as a workspace's50mod stripe;
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept51mod 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 & pricing52mod subscriptions;
Merge Stripe Tax, the card fee on card payments, and one free workspace per person53mod tax;
Mission control shows model usage, yours and the workspace's: tokens, cost, active days, cache share, each day, and the mix54mod tokens;
Account settings in the same shape as a workspace's55
56use g1t_contracts::billing::*;
57use g1t_contracts::time::rfc3339;
Merge main (membership, two-factor, GitHub repo roles) into tokens58use g1t_contracts::{FailureCode, Outcome, new_id};
Account settings in the same shape as a workspace's59use g1t_kit::{args, now_ms, reply, rpc_method};
60use serde::Deserialize;
61use sha2::{Digest, Sha256};
62use worker::wasm_bindgen::JsValue;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains63use 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 index64use futures_util::future::{try_join, try_join5};
Account settings in the same shape as a workspace's65
66use stripe::Stripe;
67
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look68/// Prepaying: $25 at the least; by card up to $10,000 at a time, and by
69/// bank transfer from $1,000 to $100,000.
70const MIN_TOP_UP_CENTS: u32 = 2_500;
71const MAX_TOP_UP_CENTS: u32 = 1_000_000;
72const MIN_BANK_TRANSFER_CENTS: u32 = 100_000;
73const MAX_BANK_TRANSFER_CENTS: u32 = 10_000_000;
Account settings in the same shape as a workspace's74const LEDGER_PAGE: u32 = 100;
75/// A run's reported cost is believed up to this much. A sandbox cannot
76/// spend more in the time it has, so anything above is a fault.
77const MAX_RUN_COST_USD: f64 = 100.0;
78
79/// What a run is charged: its cost plus the margin, rounded up to a whole
80/// millionth of a dollar.
81pub fn charge_micros(cost_usd: f64, margin_percent: u32) -> i64 {
82 let cost_micros = (cost_usd.clamp(0.0, MAX_RUN_COST_USD) * MICROS_PER_DOLLAR as f64).ceil();
83 (cost_micros * f64::from(100 + margin_percent) / 100.0).ceil() as i64
84}
85
Merge branch 'worktree-agent-a633ac0f7f66d419d'86/// What a cost g1t trusts (the price book's, or what AI Gateway priced a
87/// run at) is charged at: plus the margin, rounded up to a whole millionth.
88/// Unlike `charge_micros`, never capped: only a sandbox's own report is
89/// held to `MAX_RUN_COST_USD`, so a run that really cost more is charged
90/// for all of it once it is settled.
91pub fn margin_on(cost_micros: i64, margin_percent: u32) -> i64 {
92 let cost = i128::from(cost_micros.max(0));
93 let charge = (cost * i128::from(100 + margin_percent) + 99) / 100;
94 i64::try_from(charge).unwrap_or(i64::MAX)
95}
96
Account settings in the same shape as a workspace's97fn hash(token: &str) -> String {
98 hex::encode(Sha256::digest(token.as_bytes()))
99}
100
101fn optional(value: Option<&str>) -> JsValue {
102 value.map_or(JsValue::NULL, JsValue::from)
103}
104
105#[derive(Deserialize)]
106struct AccountRow {
107 balance_micros: i64,
108 customer_id: Option<String>,
109}
110
111#[derive(Deserialize)]
112struct LedgerRow {
113 id: String,
114 kind: EntryKind,
115 amount_micros: i64,
116 description: String,
117 repo: Option<String>,
118 number: Option<u32>,
119 task: Option<String>,
120 model: Option<String>,
121 created_by: Option<String>,
122 created_at: String,
123 billed_to: Option<String>,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace124 #[serde(default)]
125 workspace: Option<String>,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put126 #[serde(default)]
127 credit_micros: Option<i64>,
128 #[serde(default)]
129 trial_micros: Option<i64>,
130 #[serde(default)]
131 oss_micros: Option<i64>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look132 #[serde(default)]
133 given_micros: Option<i64>,
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging134 #[serde(default)]
135 credit_kind: Option<String>,
136 #[serde(default)]
137 discount_micros: Option<i64>,
Account settings in the same shape as a workspace's138}
139
140impl From<LedgerRow> for LedgerEntry {
141 fn from(row: LedgerRow) -> Self {
142 LedgerEntry {
143 id: row.id,
144 kind: row.kind,
145 amount_micros: row.amount_micros,
146 description: row.description,
147 repo: row.repo,
148 number: row.number,
149 task: row.task,
150 model: row.model,
151 billed_to: row.billed_to.unwrap_or_else(|| "g1t".to_owned()),
152 created_by: row.created_by,
153 created_at: row.created_at,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace154 workspace: row.workspace,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put155 credit_micros: row.credit_micros.unwrap_or(0),
156 trial_micros: row.trial_micros.unwrap_or(0),
157 oss_micros: row.oss_micros.unwrap_or(0),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look158 given_micros: row.given_micros.unwrap_or(0),
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging159 credit_kind: row.credit_kind.as_deref().and_then(CreditKind::parse),
160 discount_micros: row.discount_micros.unwrap_or(0),
Account settings in the same shape as a workspace's161 }
162 }
163}
164
Merge branch 'model-routing'165#[derive(Clone, Deserialize)]
Account settings in the same shape as a workspace's166struct RunRow {
167 workspace: String,
168 repo: String,
169 number: u32,
170 task: String,
171 model: String,
172 token_hash: String,
173 billed_to: Option<String>,
174}
175
176impl RunRow {
177 fn own_provider(&self) -> bool {
178 self.billed_to.as_deref() == Some("workspace")
179 }
180}
181
182#[derive(Deserialize)]
183struct CheckoutRow {
184 workspace: String,
185 created_by: String,
Merge Stripe Tax, the card fee on card payments, and one free workspace per person186 #[serde(default)]
187 fee_cents: Option<u32>,
Account settings in the same shape as a workspace's188}
189
Usage, Billing settings and prepaid AI credit; fixes from the UX audit190/// A payment page started, as `checkouts` keeps it.
191pub(crate) struct NewCheckout<'a> {
192 pub id: &'a str,
193 pub workspace: &'a str,
194 /// What it pays for, in cents: the prepayment, the plan's price, the AI
195 /// credit; 0 for a card check.
196 pub amount_cents: u32,
197 /// The card fee on top, for AI credit.
198 pub fee_cents: u32,
199 pub created_by: &'a str,
200 /// None for a prepayment; `plan`, `security`, `card_check` or
201 /// `ai_credit` otherwise.
202 pub feature: Option<&'a str>,
203}
204
205/// The one insert every payment page goes through, every column named, so
206/// a column added to `checkouts` with no default is caught by
207/// `tests::every_checkout_insert_fills_the_table` rather than by a 500.
208pub(crate) const CHECKOUT_INSERT: &str = "INSERT INTO checkouts (id, workspace, amount_cents, fee_cents, created_by, created_at, feature, status)
209 VALUES (?, ?, ?, ?, ?, ?, ?, 'open')";
210
211impl Billing {
212 pub(crate) async fn record_checkout(&self, c: &NewCheckout<'_>) -> Result<()> {
213 self.db
214 .prepare(CHECKOUT_INSERT)
215 .bind(&[
216 c.id.into(),
217 c.workspace.into(),
218 c.amount_cents.into(),
219 c.fee_cents.into(),
220 c.created_by.into(),
221 rfc3339(now_ms()).into(),
222 optional(c.feature),
223 ])?
224 .run()
225 .await?;
226 Ok(())
227 }
228}
229
Account settings in the same shape as a workspace's230/// A row an `UPDATE … RETURNING` touched.
231#[derive(Deserialize)]
232struct Touched {
233 #[allow(dead_code)]
234 id: String,
235}
236
237struct Billing {
238 db: D1Database,
239 /// Absent when no card processor is configured.
240 stripe: Option<Stripe>,
Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard241 /// The destination's signing secret from Stripe (`STRIPE_WEBHOOK_SECRET`);
242 /// without it no event is believed.
243 webhook_secret: Option<String>,
Account settings in the same shape as a workspace's244 margin_percent: u32,
Free while g1t is being built out; agents can check out their own forks245 /// While g1t is being built out, nothing is charged (`FREE_WHILE_BUILDING`).
246 free: bool,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put247 /// Whether new workspaces get trial credit (`TRIAL_WORKSPACE_MICROS`
248 /// and `TRIAL_MONTHLY_POOL_MICROS` both above zero).
249 trials_on: bool,
250 /// The plans' and pools' numbers; see `credits`.
251 plans: credits::Config,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look252 /// The repos service: which repositories are public, what private ones
253 /// 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 put254 repos: Option<worker::Fetcher>,
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member255 /// The packages service: what each workspace's packages hold.
256 packages: Option<worker::Fetcher>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look257 /// The identity service, which emails owners. Absent where it is not
258 /// bound.
259 identity: Option<worker::Fetcher>,
Usage limits: unpaid usage can only go so far260 /// How far unpaid usage may go; see `limits`.
261 ceilings: limits::Ceilings,
Billing accounts, terms and enterprises; g1t is no longer free262 /// `PREPAID_ONLY`: the old rule, that agents need credit first.
263 prepaid_only: bool,
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays264 /// The caps on what g1t pays for itself; see `budget`.
265 caps: budget::Caps,
266 /// The worker's bindings, for emailing staff (`EMAIL`).
267 env: Env,
A free allowance on g1t's models, so anyone can try its agents268}
269
Account settings in the same shape as a workspace's270impl Billing {
271 fn status(&self) -> Status {
272 Status {
273 enabled: self.stripe.is_some(),
274 live: self.stripe.as_ref().is_some_and(Stripe::live),
Free while g1t is being built out; agents can check out their own forks275 free: self.free,
Account settings in the same shape as a workspace's276 }
277 }
278
279 async fn row(&self, workspace: &str) -> Result<Option<AccountRow>> {
280 self.db
281 .prepare("SELECT balance_micros, customer_id FROM accounts WHERE workspace = ?")
282 .bind(&[workspace.into()])?
283 .first::<AccountRow>(None)
284 .await
285 }
286
287 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 kept288 // The card as last synced (stripe_sync.rs), not asked of Stripe.
289 let (row, card) = try_join(self.row(workspace), self.saved_card(workspace)).await?;
Account settings in the same shape as a workspace's290 Ok(Account {
291 workspace: workspace.to_owned(),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace292 balance_micros: row.map_or(0, |row| row.balance_micros),
Account settings in the same shape as a workspace's293 status: self.status(),
294 margin_percent: self.margin_percent,
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace295 card,
Account settings in the same shape as a workspace's296 })
297 }
298
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace299 /// The workspace's customer at Stripe, made the first time one is needed.
300 pub(crate) async fn customer_for(&self, workspace: &str) -> Result<String> {
301 let Some(stripe) = &self.stripe else {
302 return Err(worker::Error::RustError("payments are not set up".into()));
303 };
304 if let Some(customer) = self.row(workspace).await?.and_then(|row| row.customer_id) {
305 return Ok(customer);
306 }
307 let customer = stripe.create_customer(workspace).await?;
308 self.db
309 .prepare(
310 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at) VALUES (?1, 0, ?2, ?3)
311 ON CONFLICT (workspace) DO UPDATE SET customer_id = ?2",
312 )
313 .bind(&[workspace.into(), customer.as_str().into(), rfc3339(now_ms()).into()])?
314 .run()
315 .await?;
316 Ok(customer)
317 }
318
319 /// Stripe's hosted billing page for the workspace. Owners only.
320 async fn billing_portal(&self, a: BillingPortalArgs) -> Result<Outcome<Checkout>> {
321 let workspace = a.workspace.to_lowercase();
Merge main (membership, two-factor, GitHub repo roles) into tokens322 if !a.actor.manages_billing(&workspace) {
323 return Ok(Outcome::fail(FailureCode::Forbidden, "Only an owner or a billing manager can manage the workspace's billing."));
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace324 }
325 let Some(stripe) = &self.stripe else {
326 return Ok(Outcome::fail(FailureCode::Conflict, "Payments are not set up on this g1t."));
327 };
328 let customer = match self.customer_for(&workspace).await {
329 Ok(customer) => customer,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit330 Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, crate::stripe::friendly(&error))),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace331 };
332 match stripe.portal_session(&customer, &a.return_url).await {
333 Ok(url) => Ok(Outcome::Ok(Checkout { url })),
334 Err(error) if stripe::is_missing(&error) => {
335 // The customer was removed at Stripe: a new one next time.
336 self.forget_customer(&workspace).await?;
337 Ok(Outcome::fail(FailureCode::Conflict, "Stripe no longer had this workspace's customer. Try again."))
338 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit339 Err(error) => Ok(Outcome::fail(FailureCode::Conflict, crate::stripe::friendly(&error))),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace340 }
341 }
342
Account settings in the same shape as a workspace's343 /// Adds a ledger entry and moves the balance by the same amount, as
344 /// one write.
345 #[allow(clippy::too_many_arguments)]
346 async fn enter(
347 &self,
348 workspace: &str,
349 kind: EntryKind,
350 amount_micros: i64,
351 description: &str,
352 reference: &str,
353 run: Option<&RunRow>,
354 cost_micros: Option<i64>,
355 created_by: Option<&str>,
356 customer: Option<&str>,
357 ) -> Result<()> {
358 let now = now_ms();
359 let timestamp = rfc3339(now);
360 let kind = match kind {
361 EntryKind::TopUp => "top_up",
362 EntryKind::Usage => "usage",
363 };
364 self.db
365 .batch(vec![
366 self.db
367 .prepare(
368 "INSERT INTO ledger
369 (id, workspace, kind, amount_micros, description, repo, number, task,
370 model, cost_micros, reference, created_by, created_at, billed_to)
371 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
372 )
373 .bind(&[
374 new_id("led", now).into(),
375 workspace.into(),
376 kind.into(),
377 // D1 takes numbers as doubles, which hold every
378 // amount this service will see exactly.
379 (amount_micros as f64).into(),
380 description.into(),
381 optional(run.map(|run| run.repo.as_str())),
382 run.map_or(JsValue::NULL, |run| run.number.into()),
383 optional(run.map(|run| run.task.as_str())),
384 optional(run.map(|run| run.model.as_str())),
385 cost_micros.map_or(JsValue::NULL, |cost| (cost as f64).into()),
386 reference.into(),
387 optional(created_by),
388 timestamp.as_str().into(),
389 run.map_or("g1t", |run| if run.own_provider() { "workspace" } else { "g1t" }).into(),
390 ])?,
391 self.db
392 .prepare(
393 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at)
394 VALUES (?1, ?2, ?3, ?4)
395 ON CONFLICT (workspace) DO UPDATE SET
396 balance_micros = balance_micros + ?2,
397 customer_id = COALESCE(?3, customer_id)",
398 )
399 .bind(&[
400 workspace.into(),
401 (amount_micros as f64).into(),
402 optional(customer),
403 timestamp.as_str().into(),
404 ])?,
405 ])
406 .await?;
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging407 // Money in clears a card declined at the limit. A refund or a lost
408 // dispute is a top-up of less than nothing: money out, which never
409 // clears it.
410 if kind == "top_up" && amount_micros > 0 {
Billing accounts, terms and enterprises; g1t is no longer free411 self.db
412 .prepare("UPDATE limits SET autopay_failed_at = NULL, autopay_error = NULL WHERE workspace = ?")
413 .bind(&[workspace.into()])?
414 .run()
415 .await?;
416 }
Account settings in the same shape as a workspace's417 Ok(())
418 }
419
420 async fn account(&self, a: AccountArgs) -> Result<Outcome<Account>> {
421 let workspace = a.workspace.to_lowercase();
422 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
423 return Ok(members_only());
424 }
425 Ok(Outcome::Ok(self.standing(&workspace).await?))
426 }
427
428 async fn ledger(&self, a: AccountArgs) -> Result<Outcome<Vec<LedgerEntry>>> {
429 let workspace = a.workspace.to_lowercase();
430 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
431 return Ok(members_only());
432 }
433 let rows = self
434 .db
435 .prepare("SELECT * FROM ledger WHERE workspace = ? ORDER BY id DESC LIMIT ?")
436 .bind(&[workspace.into(), LEDGER_PAGE.into()])?
437 .all()
438 .await?
439 .results::<LedgerRow>()?;
440 Ok(Outcome::Ok(
441 rows.into_iter().map(LedgerEntry::from).collect(),
442 ))
443 }
444
445 async fn usage(&self, a: UsageArgs) -> Result<Outcome<Usage>> {
446 let workspace = a.workspace.to_lowercase();
447 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
448 return Ok(members_only());
449 }
450 #[derive(serde::Deserialize)]
451 struct SliceRow {
452 key: Option<String>,
453 micros: Option<i64>,
454 runs: Option<u32>,
455 }
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging456 // While g1t is free, what was used at cost is what there is to show.
457 // With a discount, usage at its price, so a 100% discount still
458 // shows what the workspace would pay.
Usage, Billing settings and prepaid AI credit; fixes from the UX audit459 // Every slice measures usage at price (statement::PRICE_SQL), the one
460 // figure every page shows as usage, whatever paid for it.
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging461 let discount_percent = self.terms_of(&workspace).await?.percent_off();
Usage, Billing settings and prepaid AI credit; fixes from the UX audit462 let measure = if self.free { "COALESCE(cost_micros, 0)" } else { crate::statement::PRICE_SQL };
Account settings in the same shape as a workspace's463 let slices = |key: &str, limit: u32| {
464 format!(
Usage while free is shown at cost; agents get rustfmt and clippy465 "SELECT {key} AS key, SUM({measure}) AS micros, COUNT(*) AS runs FROM ledger
Account settings in the same shape as a workspace's466 WHERE workspace = ?1 AND kind = 'usage' AND created_at >= ?2
467 GROUP BY 1 ORDER BY micros DESC LIMIT {limit}"
468 )
469 };
470 let query = |sql: String| {
471 let db = &self.db;
472 let workspace = workspace.clone();
473 let since = a.since.clone();
474 async move {
475 let rows = db
476 .prepare(sql)
477 .bind(&[workspace.into(), since.into()])?
478 .all()
479 .await?
480 .results::<SliceRow>()?;
481 Ok::<Vec<UsageSlice>, worker::Error>(
482 rows.into_iter()
483 .map(|row| UsageSlice {
484 key: row.key.unwrap_or_else(|| "other".to_owned()),
485 micros: row.micros.unwrap_or_default(),
486 runs: row.runs.unwrap_or_default(),
487 })
488 .collect(),
489 )
490 }
491 };
492 #[derive(serde::Deserialize)]
493 struct Totals {
494 spent: Option<i64>,
495 cost: Option<i64>,
496 provider: Option<i64>,
497 runs: Option<u32>,
498 added: Option<i64>,
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging499 discount: Option<i64>,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit500 covered: Option<i64>,
501 price: Option<i64>,
Account settings in the same shape as a workspace's502 }
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 index503 let totals = async {
504 self.db
Usage, Billing settings and prepaid AI credit; fixes from the UX audit505 .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 index506 "SELECT
507 -SUM(CASE WHEN kind = 'usage' THEN amount_micros END) AS spent,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit508 SUM(CASE WHEN kind = 'usage' THEN COALESCE(credit_micros, 0) + COALESCE(trial_micros, 0)
509 + COALESCE(oss_micros, 0) + COALESCE(given_micros, 0) END) AS covered,
510 SUM(CASE WHEN kind = 'usage' THEN {price} END) AS price,",
511 price = crate::statement::PRICE_SQL
512 ) + "
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 index513 SUM(CASE WHEN kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' THEN cost_micros END) AS cost,
514 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 audit515 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 charging516 SUM(CASE WHEN kind = 'top_up' THEN amount_micros END) AS added,
517 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 index518 FROM ledger WHERE workspace = ?1 AND created_at >= ?2",
519 )
520 .bind(&[workspace.as_str().into(), a.since.as_str().into()])?
521 .first::<Totals>(None)
522 .await
523 };
524 // The totals and the five slices read the same rows independently,
525 // so they go to D1 at once: one round trip of waiting, not six.
526 let (totals, (by_day, by_task, by_repo, by_pull, by_model)) = try_join(
527 totals,
528 try_join5(
529 query(slices("substr(created_at, 1, 10) || '/' || COALESCE(task, 'other')", 400)),
530 query(slices("task", 20)),
531 query(slices("repo", 20)),
532 query(slices("repo || '#' || number", 10)),
533 query(slices("model", 10)),
534 ),
535 )
536 .await?;
Account settings in the same shape as a workspace's537 let totals = totals.unwrap_or(Totals {
538 spent: None,
539 cost: None,
540 provider: None,
541 runs: None,
542 added: None,
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging543 discount: None,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit544 covered: None,
545 price: None,
Account settings in the same shape as a workspace's546 });
547 Ok(Outcome::Ok(Usage {
548 spent_micros: totals.spent.unwrap_or_default(),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit549 // What the included usage, the trial, a pool or g1t paid, as the
550 // entries record it.
551 covered_micros: totals.covered.unwrap_or_default(),
552 price_micros: if self.free { totals.cost.unwrap_or_default() } else { totals.price.unwrap_or_default() },
Account settings in the same shape as a workspace's553 cost_micros: totals.cost.unwrap_or_default(),
554 provider_micros: totals.provider.unwrap_or_default(),
Usage while free is shown at cost; agents get rustfmt and clippy555 used_micros: totals.cost.unwrap_or_default() + totals.provider.unwrap_or_default(),
556 free: self.free,
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging557 discount_micros: totals.discount.unwrap_or_default(),
558 discount_percent: (discount_percent > 0).then_some(discount_percent),
Account settings in the same shape as a workspace's559 runs: totals.runs.unwrap_or_default(),
560 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 index561 by_day,
562 by_task,
563 by_repo,
564 by_pull,
565 by_model,
Account settings in the same shape as a workspace's566 since: a.since,
567 }))
568 }
569
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look570 /// `checkout`: prepays usage, by card or (from $1,000) bank transfer.
Account settings in the same shape as a workspace's571 async fn checkout(&self, a: CheckoutArgs) -> Result<Outcome<Checkout>> {
572 let workspace = a.workspace.to_lowercase();
Merge main (membership, two-factor, GitHub repo roles) into tokens573 if !a.actor.manages_billing(&workspace) {
Account settings in the same shape as a workspace's574 return Ok(Outcome::fail(
575 FailureCode::Forbidden,
Merge main (membership, two-factor, GitHub repo roles) into tokens576 "Only an owner or a billing manager can prepay for a workspace.",
Account settings in the same shape as a workspace's577 ));
578 }
579 let Some(stripe) = &self.stripe else {
580 return Ok(Outcome::fail(
581 FailureCode::Conflict,
582 "Payments are not set up on this g1t yet.",
583 ));
584 };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look585 let bank_transfer = a.method.as_deref() == Some("bank_transfer");
586 if let Err(why) = prepay_amount(a.amount_cents, bank_transfer) {
587 return Ok(Outcome::fail(FailureCode::Invalid, why));
Account settings in the same shape as a workspace's588 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look589 // A bank transfer needs a customer for its account details.
590 let customer = if bank_transfer {
591 match self.customer_for(&workspace).await {
592 Ok(customer) => Some(customer),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit593 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 look594 }
595 } else {
596 self.row(&workspace).await?.and_then(|row| row.customer_id)
597 };
Merge Stripe Tax, the card fee on card payments, and one free workspace per person598 // By card, Stripe's fee is its own line; a bank transfer has none.
599 let fee = if bank_transfer { 0 } else { self.card_fee_on(i64::from(a.amount_cents)).await? as u32 };
600 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 know601 // A customer saved under another Stripe account: start afresh.
602 Err(error) if customer.is_some() && stripe::is_missing(&error) => {
603 self.forget_customer(&workspace).await?;
Usage, Billing settings and prepaid AI credit; fixes from the UX audit604 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 person605 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 know606 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit607 other => other,
Project dependencies: addresses, preview stacks, Affects, and agents who know608 };
Merge Stripe Tax, the card fee on card payments, and one free workspace per person609 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 audit610 }
611
612 /// A payment page Stripe started (or refused), recorded in `checkouts`
613 /// and handed back; any failure as a sentence for the page, never a
614 /// raw error.
615 pub(crate) async fn page_opened(
616 &self,
617 started: Result<stripe::Session>,
618 workspace: &str,
619 amount_cents: u32,
620 fee_cents: u32,
621 created_by: &str,
622 feature: Option<&str>,
623 ) -> Result<Outcome<Checkout>> {
624 let session = match started {
625 Ok(session) => session,
626 Err(error) => {
627 worker::console_error!("{workspace}: Stripe refused a payment page ({}): {error}", feature.unwrap_or("prepay"));
628 return Ok(Outcome::fail(FailureCode::Conflict, stripe::friendly(&error)));
629 }
Account settings in the same shape as a workspace's630 };
Usage, Billing settings and prepaid AI credit; fixes from the UX audit631 let Some(url) = session.url.clone() else {
632 return Ok(Outcome::fail(FailureCode::Conflict, "Stripe returned no payment page. Try again in a minute."));
633 };
634 let recorded = self
635 .record_checkout(&NewCheckout { id: &session.id, workspace, amount_cents, fee_cents, created_by, feature })
636 .await;
637 if let Err(error) = recorded {
638 worker::console_error!("{workspace}: a payment page could not be recorded: {error}");
639 return Ok(Outcome::fail(FailureCode::Conflict, "g1t could not keep track of the payment page. Nothing was charged; try again."));
640 }
Account settings in the same shape as a workspace's641 Ok(Outcome::Ok(Checkout { url }))
642 }
643
644 /// Credits a payment if the processor says it was made and it has not
645 /// been credited before. The amount credited is what the processor
646 /// says was paid, not what anyone here remembers asking for.
647 async fn confirm(&self, a: ConfirmArgs) -> Result<Outcome<Account>> {
648 let workspace = a.workspace.to_lowercase();
649 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
650 return Ok(members_only());
651 }
652 let (Some(stripe), Some(checkout)) = (
653 &self.stripe,
654 self.db
655 .prepare(
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging656 // A prepayment only: a plan's or a card check's page is
657 // settled where it was started, never credited as money
658 // paid in advance.
Merge Stripe Tax, the card fee on card payments, and one free workspace per person659 "SELECT workspace, created_by, fee_cents FROM checkouts
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging660 WHERE id = ? AND workspace = ? AND status = 'open' AND feature IS NULL",
Account settings in the same shape as a workspace's661 )
662 .bind(&[a.session.as_str().into(), workspace.as_str().into()])?
663 .first::<CheckoutRow>(None)
664 .await?,
665 ) else {
666 // Unknown, someone else's, or already credited: nothing to do.
667 return Ok(Outcome::Ok(self.standing(&workspace).await?));
668 };
Usage, Billing settings and prepaid AI credit; fixes from the UX audit669 let session = match stripe.session(&a.session).await {
670 Ok(session) => session,
671 Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, crate::stripe::friendly(&error))),
672 };
Merge Stripe Tax, the card fee on card payments, and one free workspace per person673 if session.payment_status == "paid" && session.amount_total.is_some() {
Account settings in the same shape as a workspace's674 // Only whoever flips it from open to paid enters the credit.
675 let claimed = self
676 .db
677 .prepare(
678 "UPDATE checkouts SET status = 'paid' WHERE id = ? AND status = 'open'
679 RETURNING id",
680 )
681 .bind(&[a.session.as_str().into()])?
682 .first::<Touched>(None)
683 .await?;
684 if claimed.is_some() {
Merge Stripe Tax, the card fee on card payments, and one free workspace per person685 self.credit_prepayment(&checkout.workspace, &session, checkout.fee_cents.unwrap_or(0), &checkout.created_by).await?;
Account settings in the same shape as a workspace's686 }
687 }
688 Ok(Outcome::Ok(self.standing(&workspace).await?))
689 }
690
Merge Stripe Tax, the card fee on card payments, and one free workspace per person691 /// Enters a paid prepayment page: what its lines came to before tax,
692 /// less the card fee, as credit; its tax and fee kept apart. Once the
693 /// page is claimed `open → paid`. The credit in cents.
694 pub(crate) async fn credit_prepayment(&self, workspace: &str, session: &stripe::Session, fee_cents: u32, by: &str) -> Result<i64> {
695 let fee = i64::from(fee_cents);
696 let cents = tax::prepay_credit_cents(session.before_tax_cents(), fee);
697 let tax_cents = session.tax_cents();
698 let description = if tax_cents > 0 || fee > 0 {
699 format!(
700 "Paid in advance (tax {} and card fee {} paid with it)",
701 features::cents(tax_cents * 10_000),
702 features::cents(fee * 10_000)
703 )
704 } else {
705 "Paid in advance".to_owned()
706 };
707 self.enter(
708 workspace,
709 EntryKind::TopUp,
710 cents * MICROS_PER_DOLLAR / 100,
711 &description,
712 &session.id,
713 None,
714 None,
715 Some(by),
716 session.customer.as_deref(),
717 )
718 .await?;
719 self.record_extras(workspace, &session.id, session.payment_intent.as_deref(), tax::Extras { tax_cents, fee_cents: fee }, None)
720 .await?;
721 Ok(cents)
722 }
723
Project dependencies: addresses, preview stacks, Affects, and agents who know724 /// Drops a saved customer the card processor no longer knows.
725 pub(crate) async fn forget_customer(&self, workspace: &str) -> Result<()> {
726 self.db
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept727 .prepare(
728 "UPDATE accounts SET customer_id = NULL, card_brand = NULL, card_last4 = NULL, card_exp_month = NULL,
729 card_exp_year = NULL, card_synced_at = NULL WHERE workspace = ?",
730 )
Project dependencies: addresses, preview stacks, Affects, and agents who know731 .bind(&[workspace.into()])?
732 .run()
733 .await?;
734 Ok(())
735 }
736
Account settings in the same shape as a workspace's737 /// A refusal if the workspace has no credit to start an agent with.
738 async fn out_of_credit<T>(&self, workspace: &str) -> Result<Option<Outcome<T>>> {
Billing accounts, terms and enterprises; g1t is no longer free739 // Billing is postpaid: usage limits decide whether work starts
740 // (see `limits`), and credit is a prepayment that lowers what is
741 // owed. A balance no longer has to be positive to start.
742 if self.free || !self.prepaid_only {
Free while g1t is being built out; agents can check out their own forks743 return Ok(None);
744 }
Account settings in the same shape as a workspace's745 let balance = self
746 .row(workspace)
747 .await?
748 .map_or(0, |row| row.balance_micros);
749 Ok((balance <= 0).then(|| {
750 Outcome::fail(
751 FailureCode::PaymentRequired,
752 format!(
753 "The {workspace} workspace has no agent credit. An owner can add some under Billing on the workspace's page."
754 ),
755 )
756 }))
Billing accounts, terms and enterprises; g1t is no longer free757 }
758
Account settings in the same shape as a workspace's759 async fn can_start(&self, a: CanStartArgs) -> Result<Outcome<bool>> {
760 if self.stripe.is_none() {
761 return Ok(Outcome::Ok(true));
762 }
Usage limits: unpaid usage can only go so far763 if let Some(stopped) = self.stopped(&a.workspace).await? {
764 return Ok(stopped);
765 }
Account settings in the same shape as a workspace's766 Ok(self
767 .out_of_credit(&a.workspace.to_lowercase())
768 .await?
769 .unwrap_or(Outcome::Ok(true)))
770 }
771
772 async fn start_run(&self, a: StartRunArgs) -> Result<Outcome<Option<RunTicket>>> {
773 if self.stripe.is_none() {
774 return Ok(Outcome::Ok(None));
775 }
776 let workspace = a.workspace.to_lowercase();
Usage limits: unpaid usage can only go so far777 if let Some(stopped) = self.stopped(&workspace).await? {
778 return Ok(stopped);
779 }
Account settings in the same shape as a workspace's780 if let Some(refused) = self.out_of_credit(&workspace).await? {
781 return Ok(refused);
782 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit783 // On g1t's models, a workspace on the plan needs AI credit (or
784 // included usage) first: g1t never fronts a model's cost (ai.rs).
785 if a.billed_to != "workspace"
786 && let Some(why) = self.ai_refusal(&workspace).await?
787 {
788 return Ok(Outcome::fail(FailureCode::PaymentRequired, why));
789 }
Account settings in the same shape as a workspace's790 let now = now_ms();
791 let run_id = new_id("run", now);
792 let mut bytes = [0u8; 32];
793 getrandom::getrandom(&mut bytes).expect("no source of randomness");
794 let token = hex::encode(bytes);
795 self.db
796 .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 tier797 "INSERT INTO runs (id, workspace, repo, number, task, model, token_hash, created_at, billed_to, session_id, tier)
798 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
Account settings in the same shape as a workspace's799 )
800 .bind(&[
801 run_id.as_str().into(),
802 workspace.into(),
803 format!("{}/{}", a.repo.namespace, a.repo.name).into(),
804 a.number.into(),
805 a.task.into(),
806 a.model.into(),
807 hash(&token).into(),
808 rfc3339(now).into(),
809 if a.billed_to == "workspace" { "workspace" } else { "g1t" }.into(),
Merge branch 'model-routing'810 // On the workspace's own provider too: the proxy counts the
811 // run's tokens under it, and the agent rate is charged on them.
812 optional(a.session.as_deref()),
813 optional(a.tier.as_deref().filter(|tier| tokens::is_tier(tier))),
Account settings in the same shape as a workspace's814 ])?
815 .run()
816 .await?;
817 Ok(Outcome::Ok(Some(RunTicket { run_id, token })))
818 }
819
820 async fn finish_run(&self, a: FinishRunArgs) -> Result<Outcome<bool>> {
821 let run = self
822 .db
823 .prepare(
824 "SELECT workspace, repo, number, task, model, token_hash, billed_to FROM runs
825 WHERE id = ? AND finished_at IS NULL",
826 )
827 .bind(&[a.run_id.as_str().into()])?
828 .first::<RunRow>(None)
829 .await?;
830 let Some(run) = run.filter(|run| run.token_hash == hash(&a.token)) else {
831 return Ok(Outcome::fail(FailureCode::NotFound, "Run not found."));
832 };
833 if !a.cost_usd.is_finite() || a.cost_usd < 0.0 {
834 return Ok(Outcome::fail(FailureCode::Invalid, "That is not a cost."));
835 }
836 // Only whoever closes the run charges for it.
837 let claimed = self
838 .db
839 .prepare(
840 "UPDATE runs SET finished_at = ? WHERE id = ? AND finished_at IS NULL RETURNING id",
841 )
842 .bind(&[rfc3339(now_ms()).into(), a.run_id.as_str().into()])?
843 .first::<Touched>(None)
844 .await?;
845 if claimed.is_none() {
846 return Ok(Outcome::Ok(false));
847 }
Merge branch 'model-routing'848 // On the workspace's own provider, the model was paid for there and
849 // the run's sandbox time is recorded on its own: only the agent rate
850 // is charged, on its own meter.
Prices are what g1t pays plus 20%, from the first second851 if run.own_provider() {
Merge branch 'model-routing'852 self.charge_agent_rate(&a.run_id, &run, a.tokens).await?;
Prices are what g1t pays plus 20%, from the first second853 return Ok(Outcome::Ok(true));
854 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look855 // Its cost plus the margin, on the account's terms; then the plan's
856 // included usage and the trial credit pay what they can, and g1t
857 // covers a free workspace's overrun (see `credits`). Agents are
858 // never the open-source pool's.
Usage, Billing settings and prepaid AI credit; fixes from the UX audit859 // The model at the provider's price and the price book's markup on it
860 // (`agent_models`: none from 2026-10-08); g1t's own part is the agent
861 // rate, charged on a line of its own below.
862 let base = charge_micros(a.cost_usd, self.model_markup().await?);
Merge branch 'worktree-agent-a633ac0f7f66d419d'863 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 put864 let month = credits::month_of(&rfc3339(now_ms()));
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look865 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 put866 let drawn = self.draw(&run.workspace, charge, &month, &eligible).await?;
Account settings in the same shape as a workspace's867 let mut description = match run.task.as_str() {
868 "plan" => format!("Planning for {}", run.repo),
869 "review" => format!("Review of {}#{}", run.repo, run.number),
870 "update" => format!("Catching up {}#{}", run.repo, run.number),
Chat and workspace agents: channels, DMs and named agents you talk to871 "reply" => reply_label(&run.repo),
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked872 "session" => session_label(&run.repo),
Account settings in the same shape as a workspace's873 _ => format!("Work on {}#{}", run.repo, run.number),
874 };
Billing accounts, terms and enterprises; g1t is no longer free875 description.push_str(&terms_note);
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put876 description.push_str(&drawn.note());
Account settings in the same shape as a workspace's877 self.enter(
878 &run.workspace,
879 EntryKind::Usage,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put880 -(charge - drawn.total()),
Account settings in the same shape as a workspace's881 &description,
882 &a.run_id,
883 Some(&run),
884 Some(charge_micros(a.cost_usd, 0)),
885 None,
886 None,
887 )
888 .await?;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put889 self.record_drawn(&a.run_id, &drawn).await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'890 self.record_discount(&a.run_id, discount).await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays891 self.count_spend(&run.workspace, charge_micros(a.cost_usd, 0), charge - drawn.total(), &drawn).await;
Merge branch 'model-routing'892 self.charge_agent_rate(&a.run_id, &run, a.tokens).await?;
Account settings in the same shape as a workspace's893 Ok(Outcome::Ok(true))
894 }
895}
896
Chat and workspace agents: channels, DMs and named agents you talk to897/// A workspace agent's chat reply, as its ledger line reads. The agents
898/// service bills a reply under `<workspace>/@<handle>` (no repository has an
899/// `@` in its name), so the line names the agent, not a project.
900fn reply_label(repo: &str) -> String {
901 match repo.split_once("/@") {
902 Some((workspace, handle)) => format!("Chat reply by @{handle} in {workspace}"),
903 None => format!("Chat reply in {repo}"),
904 }
905}
906
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked907/// A workspace agent's session (a piece of work it spun off, a routine's
908/// run, or a colleague's help with one), billed under the agent whose
909/// budget pays for it.
910fn session_label(repo: &str) -> String {
911 match repo.split_once("/@") {
912 Some((workspace, handle)) => format!("Agent session for @{handle} in {workspace}"),
913 None => format!("Agent session in {repo}"),
914 }
915}
916
Every sandbox is metered by the second917impl Billing {
Prices are what g1t pays plus 20%, from the first second918 /// 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 look919 /// second, from the first, at the price book's price; on its own CPU
920 /// when it reports it. Settles its reservation, if it names one.
Every sandbox is metered by the second921 async fn record_sandbox(&self, a: RecordSandboxArgs) -> Result<Outcome<bool>> {
Fast pages, required checks on the branch, self-hosted runners, honest incidents922 // Self-hosted time is recorded wherever g1t runs, for its minutes;
923 // anything else only where there is a bill to put it on.
924 if (self.stripe.is_none() && !a.self_hosted) || a.seconds == 0 {
Every sandbox is metered by the second925 return Ok(Outcome::Ok(false));
926 }
927 let workspace = a.workspace.to_lowercase();
928 let seen = self
929 .db
930 .prepare("SELECT id FROM ledger WHERE reference = ?")
931 .bind(&[a.reference.as_str().into()])?
932 .first::<Touched>(None)
933 .await?;
934 if seen.is_some() {
935 return Ok(Outcome::Ok(false));
936 }
937 let now = now_ms();
938 let timestamp = rfc3339(now);
939 let seconds = i64::from(a.seconds);
Fast pages, required checks on the branch, self-hosted runners, honest incidents940 // On the workspace's own machine: its minutes go on usage, at $0,
941 // and whatever was reserved for it is given back.
942 if a.self_hosted {
943 let description = format!("{}: {} of self-hosted runner time, $0", a.description, duration(seconds));
944 self.db
945 .prepare(
946 "INSERT INTO ledger
947 (id, workspace, kind, amount_micros, description, repo, task,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit948 cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros, quantity)
949 VALUES (?, ?, 'usage', 0, ?, ?, 'self_hosted', 0, ?, ?, 'workspace', 0, 0, 0, 0, ?)",
Fast pages, required checks on the branch, self-hosted runners, honest incidents950 )
951 .bind(&[
952 new_id("led", now).into(),
953 workspace.as_str().into(),
954 description.as_str().into(),
955 optional(a.repo.as_deref()),
956 a.reference.as_str().into(),
957 timestamp.as_str().into(),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit958 (seconds as f64).into(),
Fast pages, required checks on the branch, self-hosted runners, honest incidents959 ])?
960 .run()
961 .await?;
962 if let Some(reservation) = &a.reservation_id {
963 self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: 0 }).await?;
964 }
965 return Ok(Outcome::Ok(true));
966 }
Prices are what g1t pays plus 20%, from the first second967 // From the price book, which follows what Cloudflare bills g1t. A
968 // sandbox is the same container as a build, so without a row it is
969 // a build second's cost plus the margin.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look970 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 quotas971 let cost = deployment_costs::MICROS_PER_BUILD_SECOND as f64;
Prices are what g1t pays plus 20%, from the first second972 (cost, Price::price_for(cost, self.margin_percent))
973 });
Fast pages, required checks on the branch, self-hosted runners, honest incidents974 // A larger machine (`runs-on: g1t-4core`): its memory and disk
975 // cost more each second, and without its own CPU it is priced at
976 // its vCPUs as busy as the standard machine's.
977 let instance = a.instance.as_deref().and_then(g1t_contracts::actions::instance_named);
978 let base_scale = instance.map_or(1.0, |i| keeper::base_scale(i.memory_gib, i.disk_gb));
979 let price_scale = instance.map_or(1.0, |i| i.price_scale);
980 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 look981 // Its own CPU when the sandbox reports it; otherwise the average.
982 let parts = match a.cpu_seconds.filter(|cpu| cpu.is_finite() && *cpu >= 0.0) {
983 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 incidents984 (Some((base, _)), Some((vcpu, _))) => {
985 Some((keeper::run_cost(seconds, cpu.min(seconds as f64 * vcpus), base * base_scale, vcpu), cpu))
986 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look987 _ => None,
988 },
989 None => None,
990 };
Fast pages, required checks on the branch, self-hosted runners, honest incidents991 let cost = parts.map_or(seconds as f64 * cost_per_second * price_scale, |(cost, _)| cost).ceil() as i64;
Merge branch 'worktree-agent-a633ac0f7f66d419d'992 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 look993 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 put994 let drawn = self.draw(&workspace, charge, &credits::month_of(&timestamp), &eligible).await?;
995 let charge = charge - drawn.total();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look996 let cpu_note = parts.map_or(String::new(), |(_, cpu)| format!(", {cpu:.0} vCPU-seconds"));
997 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 daily998 // The price versions it was charged at (pricing.rs).
999 let meters: &[&str] = if parts.is_some() { &["sandbox_base_second", "sandbox_cpu_second"] } else { &["sandbox_second"] };
1000 let mut versions = Vec::new();
1001 for meter in meters {
1002 versions.extend(self.version_now(meter).await?);
1003 }
1004 let price_version = versions.join(",");
Every sandbox is metered by the second1005 self.db
1006 .batch(vec![
1007 self.db
1008 .prepare(
1009 "INSERT INTO ledger
1010 (id, workspace, kind, amount_micros, description, repo, task,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1011 cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros, price_version, quantity, compute)
1012 VALUES (?, ?, 'usage', ?, ?, ?, 'sandbox', ?, ?, ?, 'g1t', ?, ?, ?, ?, ?, ?, ?)",
Every sandbox is metered by the second1013 )
1014 .bind(&[
1015 new_id("led", now).into(),
1016 workspace.as_str().into(),
1017 (-(charge as f64)).into(),
1018 description.as_str().into(),
1019 optional(a.repo.as_deref()),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1020 (cost as f64).into(),
Every sandbox is metered by the second1021 a.reference.as_str().into(),
1022 timestamp.as_str().into(),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1023 (drawn.credit as f64).into(),
1024 (drawn.trial as f64).into(),
1025 (drawn.oss as f64).into(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1026 (drawn.given as f64).into(),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1027 optional(Some(price_version.as_str()).filter(|v| !v.is_empty())),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1028 (seconds as f64).into(),
1029 optional(a.kind.map(ComputeKind::as_str)),
Every sandbox is metered by the second1030 ])?,
1031 self.db
1032 .prepare(
1033 "INSERT INTO accounts (workspace, balance_micros, created_at)
1034 VALUES (?1, ?2, ?3)
1035 ON CONFLICT (workspace) DO UPDATE SET balance_micros = balance_micros + ?2",
1036 )
1037 .bind(&[
1038 workspace.as_str().into(),
1039 (-(charge as f64)).into(),
1040 timestamp.as_str().into(),
1041 ])?,
1042 ])
1043 .await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'1044 self.record_discount(&a.reference, discount).await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays1045 self.count_spend(&workspace, cost, charge, &drawn).await;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1046 if let Some(reservation) = &a.reservation_id {
1047 self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: cost }).await?;
1048 }
Every sandbox is metered by the second1049 Ok(Outcome::Ok(true))
1050 }
1051}
1052
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1053/// Whether an amount may be prepaid: $25 at the least by card, and from
1054/// $1,000 by bank transfer.
1055pub(crate) fn prepay_amount(cents: u32, bank_transfer: bool) -> std::result::Result<(), String> {
1056 let (min, max) = if bank_transfer { (MIN_BANK_TRANSFER_CENTS, MAX_BANK_TRANSFER_CENTS) } else { (MIN_TOP_UP_CENTS, MAX_TOP_UP_CENTS) };
1057 if (min..=max).contains(&cents) {
1058 return Ok(());
1059 }
1060 Err(if bank_transfer {
1061 format!("Prepay between ${} and ${} by bank transfer.", min / 100, group(max / 100))
1062 } else {
1063 format!("Prepay between ${} and ${} by card; from $1,000, a bank transfer works too.", min / 100, group(max / 100))
1064 })
1065}
1066
1067/// `10,000` for 10000.
1068fn group(n: u32) -> String {
1069 let digits = n.to_string();
1070 let mut out = String::new();
1071 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 kept1072 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 look1073 out.push(',');
1074 }
1075 out.push(c);
1076 }
1077 out
1078}
1079
1080#[cfg(test)]
Prices are what g1t pays plus 20%, from the first second1081/// What `seconds` of sandbox time are charged at `price_per_second`, in
1082/// millionths of a dollar: every second, rounded up to the next millionth.
1083fn sandbox_charge(seconds: i64, price_per_second: f64) -> i64 {
1084 (seconds as f64 * price_per_second).ceil() as i64
Every sandbox is metered by the second1085}
1086
1087/// `1h 2m`, `3m 12s` or `40s`.
1088fn duration(seconds: i64) -> String {
1089 let (h, m, s) = (seconds / 3600, seconds % 3600 / 60, seconds % 60);
1090 if h > 0 {
1091 format!("{h}h {m}m")
1092 } else if m > 0 {
1093 format!("{m}m {s}s")
1094 } else {
1095 format!("{s}s")
1096 }
1097}
1098
Billing accounts, terms and enterprises; g1t is no longer free1099impl Billing {
1100 /// What a workspace is charged for something that would be `base`:
1101 /// nothing while g1t is free, or as its account's terms say. With a
1102 /// note for the statement when it differs.
Merge branch 'worktree-agent-a633ac0f7f66d419d'1103 /// A charge at cost plus the margin (`base`) on the account's terms:
1104 /// what is charged, the note for the statement, and what a discount
1105 /// gave away below `base`. That last is written on the entry
1106 /// (`record_discount`) so the reconciliation counts it as given, never
1107 /// as margin lost: a sold charge is worth at least its cost plus the
1108 /// margin.
1109 pub(crate) async fn charged(&self, workspace: &str, base: i64) -> Result<(i64, String, i64)> {
Billing accounts, terms and enterprises; g1t is no longer free1110 if self.free {
Merge branch 'worktree-agent-a633ac0f7f66d419d'1111 return Ok((0, " (free while g1t is being built out)".to_owned(), 0));
Billing accounts, terms and enterprises; g1t is no longer free1112 }
1113 let terms = self.terms_of(workspace).await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'1114 let (charge, discount) = terms.discounted(base);
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging1115 let note = match terms.discount_label() {
1116 Some(label) if base > 0 => format!(" ({label})"),
Billing accounts, terms and enterprises; g1t is no longer free1117 _ => String::new(),
1118 };
Merge branch 'worktree-agent-a633ac0f7f66d419d'1119 Ok((charge, note, discount))
1120 }
1121
1122 /// What a discount gave away on an entry, below cost plus the margin
1123 /// (less than nothing on a correction down).
1124 pub(crate) async fn record_discount(&self, reference: &str, micros: i64) -> Result<()> {
1125 if micros == 0 {
1126 return Ok(());
1127 }
1128 self.db
1129 .prepare("UPDATE ledger SET discount_micros = ? WHERE reference = ?")
1130 .bind(&[(micros as f64).into(), reference.into()])?
1131 .run()
1132 .await?;
1133 Ok(())
Billing accounts, terms and enterprises; g1t is no longer free1134 }
1135}
1136
Account settings in the same shape as a workspace's1137fn members_only<T>() -> Outcome<T> {
1138 Outcome::fail(
1139 FailureCode::Forbidden,
1140 "Only members can see a workspace's billing.",
1141 )
1142}
1143
Prices keep themselves current with what g1t pays1144impl Billing {
1145 fn from_env(env: &Env) -> Result<Self> {
1146 Ok(Billing {
1147 db: env.d1("DB")?,
1148 stripe: env
1149 .secret("STRIPE_SECRET_KEY")
1150 .ok()
1151 .map(|key| key.to_string())
1152 .filter(|key| !key.is_empty())
1153 .map(Stripe::new),
Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard1154 webhook_secret: env
1155 .secret("STRIPE_WEBHOOK_SECRET")
1156 .ok()
1157 .map(|secret| secret.to_string().trim().to_owned())
1158 .filter(|secret| !secret.is_empty()),
Prices keep themselves current with what g1t pays1159 margin_percent: env
1160 .var("MARGIN_PERCENT")
1161 .ok()
1162 .and_then(|percent| percent.to_string().parse().ok())
1163 .unwrap_or(20),
1164 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 kept1165 ceilings: limits::Ceilings::from_env(env),
Billing accounts, terms and enterprises; g1t is no longer free1166 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 put1167 trials_on: {
1168 let plans = credits::Config::from_env(env);
1169 plans.trial_workspace_micros > 0 && plans.trial_monthly_pool_micros > 0
Prices keep themselves current with what g1t pays1170 },
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1171 plans: credits::Config::from_env(env),
1172 repos: env.service("REPOS").ok(),
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member1173 packages: env.service("PACKAGES").ok(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1174 identity: env.service("IDENTITY").ok(),
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays1175 caps: budget::Caps::from_env(env),
1176 env: env.clone(),
Prices keep themselves current with what g1t pays1177 })
1178 }
1179}
1180
Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails1181/// The fifteen-minute steps, each on its own: one failing never skips the
1182/// rest.
1183async fn tick(billing: &Billing, env: &Env, keeper: &keeper::Keeper) {
1184 if let Err(error) = billing.settle_runs(keeper).await {
Prices keep themselves current with what g1t pays1185 worker::console_error!("settling runs failed: {error}");
1186 }
Merge branch 'model-routing'1187 if let Err(error) = billing.settle_own_runs().await {
1188 worker::console_error!("closing runs on own providers failed: {error}");
1189 }
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1190 // Stripe events billing never received, handled now.
1191 match billing.replay_events().await {
1192 Ok(done) => worker::console_log!("stripe replay: {done}"),
1193 Err(error) => worker::console_error!("replaying Stripe events failed: {error}"),
Billing accounts, terms and enterprises; g1t is no longer free1194 }
Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails1195 // This month's users, read once for autopay and the warnings.
1196 let users = if billing.stripe.is_some() {
1197 match billing.month_users().await {
1198 Ok(users) => Some(users),
1199 Err(error) => {
1200 worker::console_error!("reading this month's users failed: {error}");
1201 None
1202 }
1203 }
1204 } else {
1205 None
1206 };
1207 if let Some(users) = &users
1208 && let Err(error) = billing.autopay(users).await {
1209 worker::console_error!("paying at the limit failed: {error}");
1210 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1211 // AI credit below a workspace's auto-reload threshold, reloaded (ai.rs).
1212 match billing.reload_ai_credit().await {
1213 Ok(0) => {}
1214 Ok(done) => worker::console_log!("auto-reloaded AI credit for {done} workspaces"),
1215 Err(error) => worker::console_error!("auto-reloading AI credit failed: {error}"),
1216 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1217 // Last month's metered usage (scans, embeddings, storage) goes on the
1218 // ledger before the month is closed and invoiced.
1219 if let Err(error) = billing.charge_pending().await {
1220 worker::console_error!("charging last month's metered usage failed: {error}");
1221 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1222 if let Err(error) = billing.close_months().await {
1223 worker::console_error!("closing the month failed: {error}");
1224 }
Stripe webhooks, enterprise invoices, and sudo for both1225 if let Err(error) = billing.invoice_enterprises().await {
1226 worker::console_error!("invoicing enterprises failed: {error}");
1227 }
Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails1228 if let Some(users) = &users
1229 && let Ok(identity) = env.service("IDENTITY")
1230 && let Err(error) = billing.warn_limits(&identity, users).await {
1231 worker::console_error!("warning owners failed: {error}");
1232 }
1233}
1234
1235/// Every fifteen minutes: runs settled, Stripe replayed, cards charged at
1236/// the limit, months closed, owners warned. Once a day, at
1237/// [`keeper::DAILY`], in an invocation of its own: the slower checks
1238/// against Stripe and Cloudflare, and measuring.
1239///
1240/// Each step logs its own failure and the next still runs. The spend
1241/// breaker and budget alerts go first: a step that runs out of CPU ends
1242/// the invocation, and must never take the alerts with it.
1243#[event(scheduled)]
1244async fn scheduled(event: ScheduledEvent, env: Env, _ctx: ScheduleContext) {
1245 let Ok(billing) = Billing::from_env(&env) else {
1246 return;
1247 };
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays1248 // Comped budgets' alerts, and a tripped breaker staff were not told of.
1249 if let Err(error) = billing.watch_spend().await {
1250 worker::console_error!("watching g1t's own spend failed: {error}");
1251 }
Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails1252 let keeper = keeper::Keeper::from_env(&env);
Merge platform pause and the hourly usage watcher: staff can pause compute, schedules, indexing or renders for everyone, the watcher emails on a breach and is never blind quietly, and the models proxy holds each run to its cap (billing 0051, integrations 0006)1253 // Once an hour, at the quarter past: what Cloudflare counted for the
1254 // whole platform in the hour before, against its thresholds
1255 // (platform.rs).
1256 if event.cron() == keeper::QUARTER_HOURLY && platform::hourly_due(now_ms()) {
1257 match billing.watch_platform(&keeper).await {
1258 Ok((read, breached)) => worker::console_log!("platform watch: {read} metrics, {breached} breaches"),
1259 Err(error) => worker::console_error!("watching platform usage failed: {error}"),
1260 }
1261 }
Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails1262 let daily = event.cron() == keeper::DAILY;
1263 if !daily {
1264 tick(&billing, &env, &keeper).await;
1265 }
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1266 // Once a day: Stripe's endpoint kept listening to billing's events and
1267 // enabled, and saved cards and plans not read in a while read again.
Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails1268 if daily {
Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard1269 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 kept1270 Ok(done) => worker::console_log!("stripe endpoint: {done}"),
1271 Err(error) => worker::console_error!("keeping Stripe's endpoint failed: {error}"),
1272 }
1273 match billing.refresh_from_stripe().await {
1274 Ok(done) => worker::console_log!("stripe refresh: {done}"),
1275 Err(error) => worker::console_error!("refreshing from Stripe failed: {error}"),
1276 }
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1277 }
The keeper reads Cloudflare as it really answers1278 // Once a day, and at once if the costs were never checked: check every
1279 // cost against what Cloudflare billed.
Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails1280 if (daily || billing.never_checked().await.unwrap_or(false))
Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept1281 && let Err(error) = billing.reconcile(&keeper).await {
Prices keep themselves current with what g1t pays1282 worker::console_error!("checking costs against Cloudflare failed: {error}");
1283 }
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging1284 // Once a day: credit from g1t past its expiry stops counting
1285 // (grants.rs), before the day is reconciled.
Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails1286 if daily {
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging1287 match billing.expire_credits().await {
1288 Ok(closed) => worker::console_log!("credits expired: {closed}"),
1289 Err(error) => worker::console_error!("expiring credits failed: {error}"),
1290 }
1291 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1292 // Once a day: what Cloudflare charged, reconciled against what g1t
1293 // counted and charged; prices whose day has come; margin alerts
1294 // (margin.rs). After the keeper, so its proposals are in.
Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails1295 if daily {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1296 match billing.costs_daily(&env, &keeper).await {
1297 Ok(run) => worker::console_log!("costs: {} lines, {} days, {} proposals, {} alerts", run.lines, run.days, run.proposals, run.alerts),
1298 Err(error) => worker::console_error!("reconciling costs failed: {error}"),
1299 }
1300 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1301 // Once a day: what each workspace's private repositories hold, its git
1302 // operations, Deployments plans from before the g1t plan set to end,
1303 // and old reservations cleared.
Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails1304 if daily {
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member1305 if let Err(error) = billing.measure_packages().await {
1306 worker::console_error!("measuring package storage failed: {error}");
1307 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1308 if let Err(error) = billing.measure_storage().await {
1309 worker::console_error!("measuring storage failed: {error}");
1310 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1311 if let Err(error) = billing.measure_git().await {
1312 worker::console_error!("measuring git operations failed: {error}");
1313 }
1314 if let Err(error) = billing.retire_deployments_plans().await {
1315 worker::console_error!("ending Deployments plans failed: {error}");
1316 }
1317 if let Err(error) = billing.sweep_reservations().await {
1318 worker::console_error!("clearing reservations failed: {error}");
1319 }
Merge the AI Gateway: Anthropic's Messages API on a workspace's tokens1320 // The AI Gateway's log keeps 30 days (gateway.rs).
1321 if let Err(error) = billing.forget_gateway_requests().await {
1322 worker::console_error!("clearing old AI Gateway requests failed: {error}");
1323 }
Merge branch 'main' into actions-toolkit-oidc-artifacts1324 // Checks of the providers' model lists keep 90 days (catalogue.rs).
1325 if let Err(error) = billing.forget_model_checks().await {
1326 worker::console_error!("clearing old model checks failed: {error}");
1327 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put1328 }
Prices keep themselves current with what g1t pays1329}
1330
Agents and memory, checks and conflicts, profiles, slug renames, custom domains1331/// Events from the bus, on billing's own queue: only a workspace's rename
1332/// matters here (see `rename`).
1333#[event(queue)]
1334async fn queue(batch: MessageBatch<g1t_contracts::events::Event>, env: Env, _ctx: Context) -> Result<()> {
1335 let billing = Billing::from_env(&env)?;
1336 let identity = env.service("IDENTITY").ok();
1337 for message in batch.messages()? {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1338 // A repository transferred: its share of the open-source pool this
1339 // month follows it. What it was charged stays with the workspace
1340 // it was charged to; usage from now on is charged to the new one.
1341 if g1t_kit::transfer::on_event(&env, &billing.db, message.body(), closing::TRANSFERRED).await? {
1342 message.ack();
1343 continue;
1344 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains1345 billing.on_event(identity.as_ref(), message.body()).await?;
1346 message.ack();
1347 }
1348 Ok(())
1349}
1350
Account settings in the same shape as a workspace's1351#[event(fetch)]
1352async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> {
1353 let Some(method) = rpc_method(&request) else {
1354 return Response::error("Not found", 404);
1355 };
Fast pages, required checks on the branch, self-hosted runners, honest incidents1356 // A replica near the caller when it asks for one (crates/kit/src/d1.rs);
1357 // what other services call (can_start, start_run) asks for none.
1358 let (db, served) = g1t_kit::d1::open(&env, "DB", &request)?;
Account settings in the same shape as a workspace's1359 let body: serde_json::Value = request.json().await?;
Fast pages, required checks on the branch, self-hosted runners, honest incidents1360 let mut billing = Billing::from_env(&env)?;
1361 billing.db = db;
1362 let answered = match method.as_str() {
Account settings in the same shape as a workspace's1363 "status" => reply(&billing.status()),
1364 "account" => reply(&billing.account(args(body)?).await?),
1365 "ledger" => reply(&billing.ledger(args(body)?).await?),
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging1366 "credits" => reply(&billing.credits(args(body)?).await?),
Account settings in the same shape as a workspace's1367 "usage" => reply(&billing.usage(args(body)?).await?),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1368 "usage_report" => reply(&billing.usage_report(args(body)?).await?),
1369 "ai_credit" => reply(&billing.ai_credit(args(body)?).await?),
1370 "buy_ai_credit" => reply(&billing.buy_ai_credit(args(body)?).await?),
1371 "confirm_ai_credit" => reply(&billing.confirm_ai_credit(args(body)?).await?),
1372 "set_ai_reload" => reply(&billing.set_ai_reload(args(body)?).await?),
1373 "set_budget" => reply(&billing.set_budget(args(body)?).await?),
1374 "billing_details" => reply(&billing.billing_details(args(body)?).await?),
1375 "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 mix1376 "record_tokens" => reply(&billing.record_tokens(args(body)?).await?),
1377 "token_usage" => reply(&billing.token_usage(args(body)?).await?),
Merge the AI Gateway: Anthropic's Messages API on a workspace's tokens1378 "gateway_models" => reply(&billing.gateway_models().await?),
Merge branch 'main' into actions-toolkit-oidc-artifacts1379 "model_defaults" => reply(&billing.model_defaults().await?),
1380 "record_discovery" => reply(&billing.record_discovery(args(body)?).await?),
1381 "admin_models" => reply(&billing.admin_models().await?),
1382 "admin_decide_model" => reply(&billing.admin_decide_model(args(body)?).await?),
1383 "admin_set_model_default" => reply(&billing.admin_set_model_default(args(body)?).await?),
Merge the AI Gateway: Anthropic's Messages API on a workspace's tokens1384 "gateway_admit" => reply(&billing.gateway_admit(args(body)?).await?),
1385 "record_gateway" => reply(&billing.record_gateway(args(body)?).await?),
1386 "gateway_requests" => reply(&billing.gateway_requests(args(body)?).await?),
Account settings in the same shape as a workspace's1387 "checkout" => reply(&billing.checkout(args(body)?).await?),
1388 "confirm" => reply(&billing.confirm(args(body)?).await?),
1389 "can_start" => reply(&billing.can_start(args(body)?).await?),
A free allowance on g1t's models, so anyone can try its agents1390 "trial" => reply(&billing.trial(args(body)?).await?),
Account settings in the same shape as a workspace's1391 "start_run" => reply(&billing.start_run(args(body)?).await?),
1392 "finish_run" => reply(&billing.finish_run(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan1393 "features" => reply(&billing.features(args(body)?).await?),
1394 "subscribe" => reply(&billing.subscribe(args(body)?).await?),
1395 "confirm_subscription" => reply(&billing.confirm_subscription(args(body)?).await?),
1396 "cancel_subscription" => reply(&billing.cancel_subscription(args(body)?).await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1397 "close_workspace" => reply(&billing.close_workspace(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan1398 "has_feature" => reply(&billing.has_feature(args(body)?).await?),
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1399 "free_workspaces" => reply(&billing.free_workspaces(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan1400 "charge_feature" => reply(&billing.charge_feature(args(body)?).await?),
Every sandbox is metered by the second1401 "record_sandbox" => reply(&billing.record_sandbox(args(body)?).await?),
Usage limits: unpaid usage can only go so far1402 "limit" => reply(&billing.limit(args(body)?).await?),
1403 "check_limit" => reply(&billing.check_limit(args(body)?).await?),
1404 "set_spend_limit" => reply(&billing.set_spend_limit(args(body)?).await?),
Prices keep themselves current with what g1t pays1405 "prices" => reply(&billing.prices().await?),
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1406 "billing_portal" => reply(&billing.billing_portal(args(body)?).await?),
1407 "admin_billing_link" => reply(&billing.admin_billing_link(args(body)?).await?),
Stripe webhooks, enterprise invoices, and sudo for both1408 "admin_stripe" => reply(&billing.admin_stripe(args(body)?).await?),
1409 "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 person1410 "admin_enterprise_address" => reply(&billing.admin_enterprise_address(args(body)?).await?),
Stripe webhooks, enterprise invoices, and sudo for both1411 "admin_invoice_enterprise" => reply(&billing.admin_invoice_enterprise(args(body)?).await?),
1412 "stripe_webhook" => reply(&billing.stripe_webhook(args(body)?).await?),
Two limits, real invoices, trust that grows by itself, sales signals1413 "invoices" => reply(&billing.invoices(args(body)?).await?),
The statement is a month at a time, a line per kind of charge1414 "statement" => reply(&billing.statement(args(body)?).await?),
1415 "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 quotas1416 "usage_meters" => reply(&billing.usage_meters(args(body)?).await?),
Two limits, real invoices, trust that grows by itself, sales signals1417 "admin_workspace_invoices" => {
1418 let a: AdminWorkspaceInvoicesArgs = args(body)?;
1419 reply(&billing.workspace_invoices(&a.workspace.to_lowercase()).await?)
1420 }
1421 "admin_signals" => reply(&billing.admin_signals(args(body)?).await?),
1422 "admin_overview" => reply(&billing.admin_overview(args(body)?).await?),
1423 "admin_sales" => reply(&billing.admin_sales(args(body)?).await?),
1424 "admin_set_sales" => reply(&billing.admin_set_sales(args(body)?).await?),
1425 "admin_add_note" => reply(&billing.admin_add_note(args(body)?).await?),
Billing lists every invoice and every staff change; signals carry follow-ups1426 "admin_invoices" => reply(&billing.admin_invoices(args(body)?).await?),
1427 "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 member1428 // A staff change made in another service, for sudo's audit log:
1429 // identity's restores and purges of deleted workspaces.
1430 "admin_log" => {
1431 let a: AdminLogArgs = args(body)?;
1432 billing
1433 .audit(&accounts::own_account(&a.workspace), &a.action, &a.detail, &a.by)
1434 .await?;
1435 reply(&true)
1436 }
Prices keep themselves current with what g1t pays1437 "note_pending" => reply(&billing.note_pending(args(body)?).await?),
Billing accounts, terms and enterprises; g1t is no longer free1438 "admin_accounts" => reply(&billing.admin_accounts(args(body)?).await?),
1439 "admin_account" => reply(&billing.admin_account(args(body)?).await?),
1440 "admin_set_terms" => reply(&billing.admin_set_terms(args(body)?).await?),
1441 "admin_create_enterprise" => reply(&billing.admin_create_enterprise(args(body)?).await?),
1442 "admin_attach" => reply(&billing.admin_attach(args(body)?).await?),
1443 "admin_credit" => reply(&billing.admin_credit(args(body)?).await?),
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging1444 "admin_credits" => reply(&billing.admin_credits(args(body)?).await?),
1445 "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 sold1446 "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 put1447 "admin_set_allowances" => reply(&billing.admin_set_allowances(args(body)?).await?),
1448 "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 sudo1449 "audit_retention" => reply(&billing.audit_retention(args(body)?).await?),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1450 "reserve" => reply(&billing.reserve(args(body)?).await?),
1451 "settle" => reply(&billing.settle_reservation(args(body)?).await?),
1452 "card_check" => reply(&billing.card_check(args(body)?).await?),
1453 "confirm_card_check" => reply(&billing.confirm_card_check(args(body)?).await?),
1454 "request_limit" => reply(&billing.request_limit(args(body)?).await?),
1455 "limit_requests" => reply(&billing.limit_requests(args(body)?).await?),
1456 "confirm_spike" => reply(&billing.confirm_spike(args(body)?).await?),
1457 "set_caps" => reply(&billing.set_caps(args(body)?).await?),
1458 "admin_limit_requests" => reply(&billing.admin_limit_requests(args(body)?).await?),
1459 "admin_decide_limit_request" => reply(&billing.admin_decide_limit_request(args(body)?).await?),
1460 "admin_overages" => reply(&billing.admin_overages(args(body)?).await?),
1461 "admin_goodwill" => reply(&billing.admin_goodwill(args(body)?).await?),
1462 "admin_velocity" => reply(&billing.admin_velocity(args(body)?).await?),
1463 "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 daily1464 "admin_costs" => reply(&billing.admin_costs(args(body)?, keeper::Keeper::from_env(&env).can_read_bill()).await?),
1465 "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 pays1466 "admin_spend_caps" => reply(&billing.spend_caps().await?),
1467 "admin_lift_breaker" => reply(&billing.admin_lift_breaker(args(body)?).await?),
Merge platform pause and the hourly usage watcher: staff can pause compute, schedules, indexing or renders for everyone, the watcher emails on a breach and is never blind quietly, and the models proxy holds each run to its cap (billing 0051, integrations 0006)1468 // Platform pauses (src/platform.rs): read by every service that
1469 // honours one, kept 30 seconds in each isolate.
1470 "platform_pause" => reply(&billing.pause_now().await),
1471 "admin_platform_guard" => reply(&billing.platform_guard(&keeper::Keeper::from_env(&env)).await?),
1472 "admin_set_pause" => reply(&billing.admin_set_pause(args(body)?, &keeper::Keeper::from_env(&env)).await?),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1473 "admin_decide_proposal" => reply(&billing.admin_decide_proposal(args(body)?).await?),
1474 "admin_set_cost_settings" => reply(&billing.admin_set_cost_settings(args(body)?).await?),
1475 "admin_set_cost_mapping" => reply(&billing.admin_set_cost_mapping(args(body)?).await?),
1476 "admin_run_costs" => reply(&billing.admin_run_costs(&env, args(body)?).await?),
Account settings in the same shape as a workspace's1477 _ => Response::error("Unknown method", 404),
Fast pages, required checks on the branch, self-hosted runners, honest incidents1478 };
1479 served.finish(answered)
Account settings in the same shape as a workspace's1480}
1481
1482#[cfg(test)]
1483mod tests {
1484 use super::*;
1485
1486 #[test]
1487 fn a_run_is_charged_its_cost_plus_the_margin() {
1488 // $0.05 at 20% is six cents.
1489 assert_eq!(charge_micros(0.05, 20), 60_000);
1490 assert_eq!(charge_micros(1.0, 20), 1_200_000);
1491 assert_eq!(charge_micros(0.05, 0), 50_000);
1492 }
1493
1494 #[test]
1495 fn fractions_of_a_millionth_round_up_and_nothing_costs_less_than_nothing() {
1496 assert_eq!(charge_micros(0.000_000_4, 20), 2);
1497 assert_eq!(charge_micros(0.0, 20), 0);
1498 assert_eq!(charge_micros(-3.0, 20), 0);
1499 }
1500
1501 #[test]
Prices are what g1t pays plus 20%, from the first second1502 fn sandbox_time_is_charged_from_the_first_second() {
1503 // 21 millionths a second at cost, plus 20%.
1504 let price = Price::price_for(21.0, 20);
1505 assert_eq!(sandbox_charge(1, price), 26);
1506 assert_eq!(sandbox_charge(60, price), 1_512);
1507 assert_eq!(sandbox_charge(0, price), 0);
Every sandbox is metered by the second1508 }
1509
1510 #[test]
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1511 fn prepaying_starts_at_twenty_five_dollars_and_bank_transfers_at_a_thousand() {
1512 assert!(prepay_amount(2_500, false).is_ok());
1513 assert!(prepay_amount(2_499, false).is_err());
1514 assert!(prepay_amount(10_000, false).is_ok());
1515 assert!(prepay_amount(1_000_000, false).is_ok());
1516 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.");
1517 assert!(prepay_amount(99_999, true).is_err());
1518 assert!(prepay_amount(100_000, true).is_ok());
1519 }
1520
1521 #[test]
Every sandbox is metered by the second1522 fn durations_read_plainly() {
1523 assert_eq!(duration(40), "40s");
1524 assert_eq!(duration(192), "3m 12s");
1525 assert_eq!(duration(3720), "1h 2m");
1526 }
1527
1528 #[test]
Account settings in the same shape as a workspace's1529 fn an_absurd_cost_is_capped() {
1530 assert_eq!(charge_micros(1e9, 20), 120 * MICROS_PER_DOLLAR);
1531 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1532
1533 /// Every migration, in order, as D1 applies them.
1534 const MIGRATIONS: &[&str] = &[
1535 include_str!("../migrations/0001_init.sql"),
1536 include_str!("../migrations/0002_own_provider.sql"),
1537 include_str!("../migrations/0003_subscriptions.sql"),
1538 include_str!("../migrations/0004_sandbox_time.sql"),
1539 include_str!("../migrations/0005_limits.sql"),
1540 include_str!("../migrations/0006_prices.sql"),
1541 include_str!("../migrations/0007_pending_usage.sql"),
1542 include_str!("../migrations/0008_accounts.sql"),
1543 include_str!("../migrations/0009_autopay.sql"),
1544 include_str!("../migrations/0010_month_close.sql"),
1545 include_str!("../migrations/0011_limit_warnings.sql"),
1546 include_str!("../migrations/0012_stripe_webhooks.sql"),
1547 include_str!("../migrations/0013_invoices_trust_sales.sql"),
1548 include_str!("../migrations/0014_custom_domain_price.sql"),
1549 include_str!("../migrations/0015_sandbox_at_cost.sql"),
1550 include_str!("../migrations/0016_plans_and_pools.sql"),
1551 include_str!("../migrations/0017_flagon_comped.sql"),
1552 include_str!("../migrations/0018_one_plan.sql"),
1553 include_str!("../migrations/0019_closed_workspaces.sql"),
1554 include_str!("../migrations/0020_syntaqx_standard.sql"),
1555 include_str!("../migrations/0021_no_quotas.sql"),
1556 include_str!("../migrations/0022_costs_and_margin.sql"),
1557 include_str!("../migrations/0023_one_operation_mapping.sql"),
1558 include_str!("../migrations/0024_spend_caps.sql"),
1559 include_str!("../migrations/0025_run_tier.sql"),
1560 include_str!("../migrations/0026_ledger_by_workspace_time.sql"),
1561 include_str!("../migrations/0027_stripe_cache.sql"),
1562 include_str!("../migrations/0028_drop_stripe_webhooks.sql"),
1563 include_str!("../migrations/0029_audit_retention.sql"),
1564 include_str!("../migrations/0030_token_usage.sql"),
1565 include_str!("../migrations/0031_package_storage.sql"),
1566 include_str!("../migrations/0032_workspace_value.sql"),
1567 include_str!("../migrations/0033_given_away.sql"),
1568 include_str!("../migrations/0034_given_by_why.sql"),
1569 include_str!("../migrations/0035_cf_subscriptions.sql"),
1570 include_str!("../migrations/0036_model_costs_in_full.sql"),
1571 include_str!("../migrations/0037_security_activation.sql"),
1572 include_str!("../migrations/0038_staff_credits.sql"),
1573 include_str!("../migrations/0039_discounts_not_comped.sql"),
1574 include_str!("../migrations/0040_ai_credit.sql"),
Merge branch 'model-routing'1575 include_str!("../migrations/0041_agent_rate_own_key.sql"),
1576 include_str!("../migrations/0042_agent_rate_weights.sql"),
Merge the AI Gateway: Anthropic's Messages API on a workspace's tokens1577 include_str!("../migrations/0043_tax_and_card_fees.sql"),
1578 include_str!("../migrations/0044_cache_reads_count_a_tenth.sql"),
1579 include_str!("../migrations/0045_gateway.sql"),
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb971580 include_str!("../migrations/0046_reset_costs.sql"),
1581 include_str!("../migrations/0047_gateway_formats.sql"),
Merge branch 'main' into actions-toolkit-oidc-artifacts1582 include_str!("../migrations/0048_model_catalogue.sql"),
Merge platform pause and the hourly usage watcher: staff can pause compute, schedules, indexing or renders for everyone, the watcher emails on a breach and is never blind quietly, and the models proxy holds each run to its cap (billing 0051, integrations 0006)1583 include_str!("../migrations/0049_superseded_proposals.sql"),
1584 include_str!("../migrations/0050_ledger_usage_by_time.sql"),
1585 include_str!("../migrations/0051_platform_guardrails.sql"),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1586 ];
1587
1588 /// The columns of `table` after the migrations: each with whether an
1589 /// insert must give it (NOT NULL, no default).
1590 fn columns(table: &str) -> Vec<(String, bool)> {
1591 let mut out = vec![];
1592 for sql in MIGRATIONS {
1593 let sql: String = sql.lines().map(|l| l.split("--").next().unwrap_or("")).collect::<Vec<_>>().join("\n");
1594 if let Some(start) = sql.find(&format!("CREATE TABLE {table} (")) {
1595 let body = &sql[start + format!("CREATE TABLE {table} (").len()..];
1596 let body = &body[..body.find(");").unwrap()];
1597 for column in body.split(",\n") {
1598 let column = column.trim();
1599 let name = column.split_whitespace().next().unwrap_or("").to_owned();
1600 if name.is_empty() || name == "PRIMARY" {
1601 continue;
1602 }
1603 let required = column.contains("NOT NULL") && !column.contains("DEFAULT") && !column.contains("PRIMARY KEY");
1604 out.push((name, required || column.contains("PRIMARY KEY")));
1605 }
1606 }
1607 for statement in sql.split(';') {
1608 let s = statement.trim();
1609 if let Some(rest) = s.strip_prefix(&format!("ALTER TABLE {table} ADD COLUMN ")) {
1610 let name = rest.split_whitespace().next().unwrap().to_owned();
1611 out.push((name, rest.contains("NOT NULL") && !rest.contains("DEFAULT")));
1612 }
1613 }
1614 }
1615 out
1616 }
1617
1618 /// The columns an `INSERT INTO table (…)` names.
1619 fn inserted(sql: &str, table: &str) -> Vec<String> {
1620 let start = sql.find(&format!("INSERT INTO {table} (")).unwrap() + format!("INSERT INTO {table} (").len();
1621 sql[start..start + sql[start..].find(')').unwrap()].split(',').map(|c| c.trim().to_owned()).collect()
1622 }
1623
1624
1625 #[test]
1626 fn ai_prices_are_price_book_data_with_dated_versions() {
1627 let sql = include_str!("../migrations/0040_ai_credit.sql");
1628 let row = |needle: &str| sql.lines().find(|l| l.contains(needle)).unwrap_or_else(|| panic!("no {needle}")).to_owned();
1629 // AI Gateway: the provider's price, no markup while in beta.
1630 assert!(row("('gateway_models', 'AI Gateway models'").contains("1000000, 0, 'list'"));
1631 // Models lose their markup from 2026-10-08, a fall that applies at once…
1632 assert!(row("('pv_agent_models_2'").contains("1000000, 0, '2026-10-08"));
1633 // …and the agent rate is $0.25 a million tokens after 14 days' notice.
1634 assert!(row("('pv_agent_tokens_2'").contains("250000, 0, '2026-10-22"));
1635 // The card fee is 2.9% + 30¢, switchable.
1636 assert!(row("('card_fee_percent'").contains("29000"));
1637 assert!(row("('card_fee_fixed'").contains("300000"));
1638 assert!(row("('card_fee', 'on'").contains("'on'"));
1639 }
Merge branch 'model-routing'1640
1641 #[test]
Chat and workspace agents: channels, DMs and named agents you talk to1642 fn a_chat_reply_is_labelled_by_its_agent() {
1643 assert_eq!(reply_label("acme/@ship"), "Chat reply by @ship in acme");
1644 assert_eq!(reply_label("acme/web"), "Chat reply in acme/web");
1645 }
1646
1647 #[test]
Merge branch 'model-routing'1648 fn the_agent_rate_on_an_own_model_key_is_its_own_dated_meter() {
1649 let sql = include_str!("../migrations/0041_agent_rate_own_key.sql");
1650 let row = |needle: &str| sql.lines().find(|l| l.contains(needle)).unwrap_or_else(|| panic!("no {needle}")).to_owned();
1651 // Nothing until the notice has run…
1652 assert!(row("('pv_agent_tokens_own_1'").contains("0, 0, '2026-10-08"));
1653 // …then $0.25 a million tokens, as on g1t's models, 14 days after.
1654 assert!(row("('pv_agent_tokens_own_2'").contains("250000, 0, '2026-10-22"));
1655 assert!(row("('agent_tokens_own',").contains("'million tokens', 0, 0, 'list'"));
1656 assert_eq!(ai::agent_rate_meter(true), "agent_tokens_own");
1657 }
1658
1659 #[test]
1660 fn the_agent_rate_counts_every_token_once_until_a_weight_is_decided() {
1661 let sql = include_str!("../migrations/0042_agent_rate_weights.sql");
1662 for kind in ["input", "output", "cache_read", "cache_write"] {
1663 let meter = format!("('agent_token_weight_{kind}', 'Agent rate weight");
1664 let row = sql.lines().find(|l| l.contains(&meter)).unwrap_or_else(|| panic!("no {kind} weight"));
1665 assert!(row.contains("'weight', 1000000, 0, 'list'"), "{kind}: {row}");
1666 let version = format!("('pv_agent_token_weight_{kind}_1', 'agent_token_weight_{kind}', 1, 1000000,");
1667 assert!(sql.contains(&version), "{kind} has no applied version");
1668 }
1669 assert_eq!(ai::weight_of(1_000_000.0), 1.0);
1670 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1671 #[test]
1672 fn every_checkout_insert_fills_the_table() {
1673 // The plan's, the activation's, a card check's, a prepayment's and
1674 // AI credit's pages all go through one insert, and it names every
1675 // column the table needs and none it lacks: a missing NOT NULL
1676 // column, or one from a migration not yet applied, was a 500.
1677 let table = columns("checkouts");
1678 let names: Vec<&str> = table.iter().map(|(n, _)| n.as_str()).collect();
1679 assert_eq!(names, ["id", "workspace", "amount_cents", "created_by", "status", "created_at", "feature", "fee_cents"]);
1680 let given = inserted(CHECKOUT_INSERT, "checkouts");
1681 for column in &given {
1682 assert!(names.contains(&column.as_str()), "the insert names {column}, which checkouts does not have");
1683 }
1684 for (column, required) in &table {
1685 assert!(!required || given.contains(column), "checkouts needs {column}, which the insert leaves out");
1686 }
1687 // As many values as columns.
1688 let values = CHECKOUT_INSERT.split("VALUES").nth(1).unwrap();
1689 assert_eq!(values.matches('?').count() + values.matches("'open'").count(), given.len());
1690 // And no page writes a row of its own any more.
1691 for (file, source) in [
1692 ("lib.rs", include_str!("lib.rs")),
1693 ("features.rs", include_str!("features.rs")),
1694 ("cards.rs", include_str!("cards.rs")),
1695 ("ai.rs", include_str!("ai.rs")),
1696 ] {
1697 let inserts = source.matches(concat!("INSERT INTO ", "checkouts")).count();
1698 assert!(inserts <= usize::from(file == "lib.rs"), "{file} inserts into checkouts on its own");
1699 }
1700 }
1701
1702 #[test]
1703 fn a_new_ledger_column_has_a_default() {
1704 // The ledger is written from a dozen places; a column without a
1705 // default would break every one that does not name it.
1706 for (column, required) in columns("ledger") {
1707 assert!(!required || ["id", "workspace", "kind", "amount_micros", "description", "reference", "created_at"].contains(&column.as_str()), "{column}");
1708 }
1709 }
Account settings in the same shape as a workspace's1710}

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