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 look | 1 | //! The billing service: what g1t's compute costs, charged to the workspace |
| 2 | //! it ran for at what g1t pays plus 20%. | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 3 | //! |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 4 | //! 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 plan | 13 | //! |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 14 | //! 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 free | 20 | mod accounts; |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 21 | mod ai; |
| Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays | 22 | mod budget; |
| Merge branch 'main' into actions-toolkit-oidc-artifacts | 23 | mod catalogue; |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 24 | mod cards; |
| 25 | mod closing; | |
| 26 | mod compute; | |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 27 | mod 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) | 28 | mod cycle; |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 29 | mod 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) | 30 | mod platform; |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 31 | mod pricing; |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 32 | mod report; |
| 33 | mod details; | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 34 | mod credits; |
| Billing: credits with a kind and expiry, discounts instead of comped, and safer charging | 35 | mod grants; |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 36 | mod overages; |
| 37 | mod requests; | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 38 | mod storage; |
| Two limits, real invoices, trust that grows by itself, sales signals | 39 | mod invoices; |
| 40 | mod sales; | |
| The statement is a month at a time, a line per kind of charge | 41 | mod statement; |
| Stripe webhooks, enterprise invoices, and sudo for both | 42 | mod webhooks; |
| Paid features: a workspace turns on Deployments with a monthly plan | 43 | mod features; |
| Merge the AI Gateway: Anthropic's Messages API on a workspace's tokens | 44 | mod gateway; |
| Prices keep themselves current with what g1t pays | 45 | mod keeper; |
| Usage limits: unpaid usage can only go so far | 46 | mod limits; |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 47 | mod 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's | 48 | mod reset; |
| Audit logs are kept by plan: a week on free, 90 days on the plan, and what staff set for an account in sudo | 49 | mod retention; |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 50 | mod stripe; |
| Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept | 51 | mod 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 & pricing | 52 | mod subscriptions; |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 53 | mod tax; |
| Mission control shows model usage, yours and the workspace's: tokens, cost, active days, cache share, each day, and the mix | 54 | mod tokens; |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 55 | |
| 56 | use g1t_contracts::billing::*; | |
| 57 | use g1t_contracts::time::rfc3339; | |
| Merge main (membership, two-factor, GitHub repo roles) into tokens | 58 | use g1t_contracts::{FailureCode, Outcome, new_id}; |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 59 | use g1t_kit::{args, now_ms, reply, rpc_method}; |
| 60 | use serde::Deserialize; | |
| 61 | use sha2::{Digest, Sha256}; | |
| 62 | use worker::wasm_bindgen::JsValue; | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 63 | use 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 index | 64 | use futures_util::future::{try_join, try_join5}; |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 65 | |
| 66 | use stripe::Stripe; | |
| 67 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 68 | /// 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. | |
| 70 | const MIN_TOP_UP_CENTS: u32 = 2_500; | |
| 71 | const MAX_TOP_UP_CENTS: u32 = 1_000_000; | |
| 72 | const MIN_BANK_TRANSFER_CENTS: u32 = 100_000; | |
| 73 | const MAX_BANK_TRANSFER_CENTS: u32 = 10_000_000; | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 74 | const 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. | |
| 77 | const 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. | |
| 81 | pub 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. | |
| 91 | pub 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 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 97 | fn hash(token: &str) -> String { |
| 98 | hex::encode(Sha256::digest(token.as_bytes())) | |
| 99 | } | |
| 100 | ||
| 101 | fn optional(value: Option<&str>) -> JsValue { | |
| 102 | value.map_or(JsValue::NULL, JsValue::from) | |
| 103 | } | |
| 104 | ||
| 105 | #[derive(Deserialize)] | |
| 106 | struct AccountRow { | |
| 107 | balance_micros: i64, | |
| 108 | customer_id: Option<String>, | |
| 109 | } | |
| 110 | ||
| 111 | #[derive(Deserialize)] | |
| 112 | struct 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, | |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 123 | billed_to: Option<String>, |
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 124 | #[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 put | 126 | #[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 look | 132 | #[serde(default)] |
| 133 | given_micros: Option<i64>, | |
| Billing: credits with a kind and expiry, discounts instead of comped, and safer charging | 134 | #[serde(default)] |
| 135 | credit_kind: Option<String>, | |
| 136 | #[serde(default)] | |
| 137 | discount_micros: Option<i64>, | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 138 | } |
| 139 | ||
| 140 | impl 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, | |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 151 | billed_to: row.billed_to.unwrap_or_else(|| "g1t".to_owned()), |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 152 | created_by: row.created_by, |
| 153 | created_at: row.created_at, | |
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 154 | workspace: row.workspace, |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 155 | 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 look | 158 | given_micros: row.given_micros.unwrap_or(0), |
| Billing: credits with a kind and expiry, discounts instead of comped, and safer charging | 159 | credit_kind: row.credit_kind.as_deref().and_then(CreditKind::parse), |
| 160 | discount_micros: row.discount_micros.unwrap_or(0), | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 161 | } |
| 162 | } | |
| 163 | } | |
| 164 | ||
| Merge branch 'model-routing' | 165 | #[derive(Clone, Deserialize)] |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 166 | struct RunRow { |
| 167 | workspace: String, | |
| 168 | repo: String, | |
| 169 | number: u32, | |
| 170 | task: String, | |
| 171 | model: String, | |
| 172 | token_hash: String, | |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 173 | billed_to: Option<String>, |
| 174 | } | |
| 175 | ||
| 176 | impl RunRow { | |
| 177 | fn own_provider(&self) -> bool { | |
| 178 | self.billed_to.as_deref() == Some("workspace") | |
| 179 | } | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 180 | } |
| 181 | ||
| 182 | #[derive(Deserialize)] | |
| 183 | struct CheckoutRow { | |
| 184 | workspace: String, | |
| 185 | created_by: String, | |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 186 | #[serde(default)] |
| 187 | fee_cents: Option<u32>, | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 188 | } |
| 189 | ||
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 190 | /// A payment page started, as `checkouts` keeps it. |
| 191 | pub(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. | |
| 208 | pub(crate) const CHECKOUT_INSERT: &str = "INSERT INTO checkouts (id, workspace, amount_cents, fee_cents, created_by, created_at, feature, status) | |
| 209 | VALUES (?, ?, ?, ?, ?, ?, ?, 'open')"; | |
| 210 | ||
| 211 | impl 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 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 230 | /// A row an `UPDATE … RETURNING` touched. |
| 231 | #[derive(Deserialize)] | |
| 232 | struct Touched { | |
| 233 | #[allow(dead_code)] | |
| 234 | id: String, | |
| 235 | } | |
| 236 | ||
| 237 | struct 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 dashboard | 241 | /// The destination's signing secret from Stripe (`STRIPE_WEBHOOK_SECRET`); |
| 242 | /// without it no event is believed. | |
| 243 | webhook_secret: Option<String>, | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 244 | margin_percent: u32, |
| Free while g1t is being built out; agents can check out their own forks | 245 | /// 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 put | 247 | /// 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 look | 252 | /// 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 put | 254 | repos: Option<worker::Fetcher>, |
| Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member | 255 | /// 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 look | 257 | /// 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 far | 260 | /// How far unpaid usage may go; see `limits`. |
| 261 | ceilings: limits::Ceilings, | |
| Billing accounts, terms and enterprises; g1t is no longer free | 262 | /// `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 pays | 264 | /// 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 agents | 268 | } |
| 269 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 270 | impl 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 forks | 275 | free: self.free, |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 276 | } |
| 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 kept | 288 | // 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?; | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 290 | Ok(Account { |
| 291 | workspace: workspace.to_owned(), | |
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 292 | balance_micros: row.map_or(0, |row| row.balance_micros), |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 293 | status: self.status(), |
| 294 | margin_percent: self.margin_percent, | |
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 295 | card, |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 296 | }) |
| 297 | } | |
| 298 | ||
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 299 | /// 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 tokens | 322 | 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 workspace | 324 | } |
| 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 audit | 330 | Err(error) => return Ok(Outcome::fail(FailureCode::Conflict, crate::stripe::friendly(&error))), |
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 331 | }; |
| 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 audit | 339 | Err(error) => Ok(Outcome::fail(FailureCode::Conflict, crate::stripe::friendly(&error))), |
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 340 | } |
| 341 | } | |
| 342 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 343 | /// 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, | |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 370 | model, cost_micros, reference, created_by, created_at, billed_to) |
| 371 | VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 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(), | |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 389 | run.map_or("g1t", |run| if run.own_provider() { "workspace" } else { "g1t" }).into(), |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 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 charging | 407 | // 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 free | 411 | 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 | } | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 417 | 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 | ||
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 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 charging | 456 | // 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 audit | 459 | // 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 charging | 461 | let discount_percent = self.terms_of(&workspace).await?.percent_off(); |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 462 | let measure = if self.free { "COALESCE(cost_micros, 0)" } else { crate::statement::PRICE_SQL }; |
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 463 | let slices = |key: &str, limit: u32| { |
| 464 | format!( | |
| Usage while free is shown at cost; agents get rustfmt and clippy | 465 | "SELECT {key} AS key, SUM({measure}) AS micros, COUNT(*) AS runs FROM ledger |
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 466 | 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>, | |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 496 | provider: Option<i64>, |
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 497 | runs: Option<u32>, |
| 498 | added: Option<i64>, | |
| Billing: credits with a kind and expiry, discounts instead of comped, and safer charging | 499 | discount: Option<i64>, |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 500 | covered: Option<i64>, |
| 501 | price: Option<i64>, | |
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 502 | } |
| 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 index | 503 | let totals = async { |
| 504 | self.db | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 505 | .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 index | 506 | "SELECT |
| 507 | -SUM(CASE WHEN kind = 'usage' THEN amount_micros END) AS spent, | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 508 | 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 index | 513 | 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 audit | 515 | 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 charging | 516 | 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 index | 518 | 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?; | |
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 537 | let totals = totals.unwrap_or(Totals { |
| 538 | spent: None, | |
| 539 | cost: None, | |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 540 | provider: None, |
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 541 | runs: None, |
| 542 | added: None, | |
| Billing: credits with a kind and expiry, discounts instead of comped, and safer charging | 543 | discount: None, |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 544 | covered: None, |
| 545 | price: None, | |
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 546 | }); |
| 547 | Ok(Outcome::Ok(Usage { | |
| 548 | spent_micros: totals.spent.unwrap_or_default(), | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 549 | // 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() }, | |
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 553 | cost_micros: totals.cost.unwrap_or_default(), |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 554 | provider_micros: totals.provider.unwrap_or_default(), |
| Usage while free is shown at cost; agents get rustfmt and clippy | 555 | 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 charging | 557 | discount_micros: totals.discount.unwrap_or_default(), |
| 558 | discount_percent: (discount_percent > 0).then_some(discount_percent), | |
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 559 | 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 index | 561 | by_day, |
| 562 | by_task, | |
| 563 | by_repo, | |
| 564 | by_pull, | |
| 565 | by_model, | |
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 566 | since: a.since, |
| 567 | })) | |
| 568 | } | |
| 569 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 570 | /// `checkout`: prepays usage, by card or (from $1,000) bank transfer. |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 571 | 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 tokens | 573 | if !a.actor.manages_billing(&workspace) { |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 574 | return Ok(Outcome::fail( |
| 575 | FailureCode::Forbidden, | |
| Merge main (membership, two-factor, GitHub repo roles) into tokens | 576 | "Only an owner or a billing manager can prepay for a workspace.", |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 577 | )); |
| 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 look | 585 | 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)); | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 588 | } |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 589 | // 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 audit | 593 | 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 look | 594 | } |
| 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 person | 598 | // 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 know | 601 | // 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 audit | 604 | 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 person | 605 | 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 know | 606 | } |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 607 | other => other, |
| Project dependencies: addresses, preview stacks, Affects, and agents who know | 608 | }; |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 609 | 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 audit | 610 | } |
| 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 | } | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 630 | }; |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 631 | 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 | } | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 641 | 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 charging | 656 | // 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 person | 659 | "SELECT workspace, created_by, fee_cents FROM checkouts |
| Billing: credits with a kind and expiry, discounts instead of comped, and safer charging | 660 | WHERE id = ? AND workspace = ? AND status = 'open' AND feature IS NULL", |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 661 | ) |
| 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 audit | 669 | 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 person | 673 | if session.payment_status == "paid" && session.amount_total.is_some() { |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 674 | // 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 person | 685 | self.credit_prepayment(&checkout.workspace, &session, checkout.fee_cents.unwrap_or(0), &checkout.created_by).await?; |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 686 | } |
| 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 person | 691 | /// 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 know | 724 | /// 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 kept | 727 | .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 know | 731 | .bind(&[workspace.into()])? |
| 732 | .run() | |
| 733 | .await?; | |
| 734 | Ok(()) | |
| 735 | } | |
| 736 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 737 | /// 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 free | 739 | // 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 forks | 743 | return Ok(None); |
| 744 | } | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 745 | 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 free | 757 | } |
| 758 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 759 | 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 far | 763 | if let Some(stopped) = self.stopped(&a.workspace).await? { |
| 764 | return Ok(stopped); | |
| 765 | } | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 766 | 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 far | 777 | if let Some(stopped) = self.stopped(&workspace).await? { |
| 778 | return Ok(stopped); | |
| 779 | } | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 780 | 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 audit | 783 | // 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 | } | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 790 | 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 tier | 797 | "INSERT INTO runs (id, workspace, repo, number, task, model, token_hash, created_at, billed_to, session_id, tier) |
| 798 | VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 799 | ) |
| 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(), | |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 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))), | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 814 | ])? |
| 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( | |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 824 | "SELECT workspace, repo, number, task, model, token_hash, billed_to FROM runs |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 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 second | 851 | 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 second | 853 | return Ok(Outcome::Ok(true)); |
| 854 | } | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 855 | // 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 audit | 859 | // 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 put | 864 | let month = credits::month_of(&rfc3339(now_ms())); |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 865 | 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 put | 866 | let drawn = self.draw(&run.workspace, charge, &month, &eligible).await?; |
| Integrations: your own model provider, alerts that open issues, tickets agents read | 867 | let mut description = match run.task.as_str() { |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 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 to | 871 | "reply" => reply_label(&run.repo), |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 872 | _ => format!("Work on {}#{}", run.repo, run.number), |
| 873 | }; | |
| Billing accounts, terms and enterprises; g1t is no longer free | 874 | description.push_str(&terms_note); |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 875 | description.push_str(&drawn.note()); |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 876 | self.enter( |
| 877 | &run.workspace, | |
| 878 | EntryKind::Usage, | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 879 | -(charge - drawn.total()), |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 880 | &description, |
| 881 | &a.run_id, | |
| 882 | Some(&run), | |
| 883 | Some(charge_micros(a.cost_usd, 0)), | |
| 884 | None, | |
| 885 | None, | |
| 886 | ) | |
| 887 | .await?; | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 888 | self.record_drawn(&a.run_id, &drawn).await?; |
| Merge branch 'worktree-agent-a633ac0f7f66d419d' | 889 | self.record_discount(&a.run_id, discount).await?; |
| Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays | 890 | self.count_spend(&run.workspace, charge_micros(a.cost_usd, 0), charge - drawn.total(), &drawn).await; |
| Merge branch 'model-routing' | 891 | self.charge_agent_rate(&a.run_id, &run, a.tokens).await?; |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 892 | Ok(Outcome::Ok(true)) |
| 893 | } | |
| 894 | } | |
| 895 | ||
| Chat and workspace agents: channels, DMs and named agents you talk to | 896 | /// A workspace agent's chat reply, as its ledger line reads. The agents |
| 897 | /// service bills a reply under `<workspace>/@<handle>` (no repository has an | |
| 898 | /// `@` in its name), so the line names the agent, not a project. | |
| 899 | fn reply_label(repo: &str) -> String { | |
| 900 | match repo.split_once("/@") { | |
| 901 | Some((workspace, handle)) => format!("Chat reply by @{handle} in {workspace}"), | |
| 902 | None => format!("Chat reply in {repo}"), | |
| 903 | } | |
| 904 | } | |
| 905 | ||
| Every sandbox is metered by the second | 906 | impl Billing { |
| Prices are what g1t pays plus 20%, from the first second | 907 | /// 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 look | 908 | /// second, from the first, at the price book's price; on its own CPU |
| 909 | /// when it reports it. Settles its reservation, if it names one. | |
| Every sandbox is metered by the second | 910 | async fn record_sandbox(&self, a: RecordSandboxArgs) -> Result<Outcome<bool>> { |
| Fast pages, required checks on the branch, self-hosted runners, honest incidents | 911 | // Self-hosted time is recorded wherever g1t runs, for its minutes; |
| 912 | // anything else only where there is a bill to put it on. | |
| 913 | if (self.stripe.is_none() && !a.self_hosted) || a.seconds == 0 { | |
| Every sandbox is metered by the second | 914 | return Ok(Outcome::Ok(false)); |
| 915 | } | |
| 916 | let workspace = a.workspace.to_lowercase(); | |
| 917 | let seen = self | |
| 918 | .db | |
| 919 | .prepare("SELECT id FROM ledger WHERE reference = ?") | |
| 920 | .bind(&[a.reference.as_str().into()])? | |
| 921 | .first::<Touched>(None) | |
| 922 | .await?; | |
| 923 | if seen.is_some() { | |
| 924 | return Ok(Outcome::Ok(false)); | |
| 925 | } | |
| 926 | let now = now_ms(); | |
| 927 | let timestamp = rfc3339(now); | |
| 928 | let seconds = i64::from(a.seconds); | |
| Fast pages, required checks on the branch, self-hosted runners, honest incidents | 929 | // On the workspace's own machine: its minutes go on usage, at $0, |
| 930 | // and whatever was reserved for it is given back. | |
| 931 | if a.self_hosted { | |
| 932 | let description = format!("{}: {} of self-hosted runner time, $0", a.description, duration(seconds)); | |
| 933 | self.db | |
| 934 | .prepare( | |
| 935 | "INSERT INTO ledger | |
| 936 | (id, workspace, kind, amount_micros, description, repo, task, | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 937 | cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros, quantity) |
| 938 | VALUES (?, ?, 'usage', 0, ?, ?, 'self_hosted', 0, ?, ?, 'workspace', 0, 0, 0, 0, ?)", | |
| Fast pages, required checks on the branch, self-hosted runners, honest incidents | 939 | ) |
| 940 | .bind(&[ | |
| 941 | new_id("led", now).into(), | |
| 942 | workspace.as_str().into(), | |
| 943 | description.as_str().into(), | |
| 944 | optional(a.repo.as_deref()), | |
| 945 | a.reference.as_str().into(), | |
| 946 | timestamp.as_str().into(), | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 947 | (seconds as f64).into(), |
| Fast pages, required checks on the branch, self-hosted runners, honest incidents | 948 | ])? |
| 949 | .run() | |
| 950 | .await?; | |
| 951 | if let Some(reservation) = &a.reservation_id { | |
| 952 | self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: 0 }).await?; | |
| 953 | } | |
| 954 | return Ok(Outcome::Ok(true)); | |
| 955 | } | |
| Prices are what g1t pays plus 20%, from the first second | 956 | // From the price book, which follows what Cloudflare bills g1t. A |
| 957 | // sandbox is the same container as a build, so without a row it is | |
| 958 | // a build second's cost plus the margin. | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 959 | 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 quotas | 960 | let cost = deployment_costs::MICROS_PER_BUILD_SECOND as f64; |
| Prices are what g1t pays plus 20%, from the first second | 961 | (cost, Price::price_for(cost, self.margin_percent)) |
| 962 | }); | |
| Fast pages, required checks on the branch, self-hosted runners, honest incidents | 963 | // A larger machine (`runs-on: g1t-4core`): its memory and disk |
| 964 | // cost more each second, and without its own CPU it is priced at | |
| 965 | // its vCPUs as busy as the standard machine's. | |
| 966 | let instance = a.instance.as_deref().and_then(g1t_contracts::actions::instance_named); | |
| 967 | let base_scale = instance.map_or(1.0, |i| keeper::base_scale(i.memory_gib, i.disk_gb)); | |
| 968 | let price_scale = instance.map_or(1.0, |i| i.price_scale); | |
| 969 | 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 look | 970 | // Its own CPU when the sandbox reports it; otherwise the average. |
| 971 | let parts = match a.cpu_seconds.filter(|cpu| cpu.is_finite() && *cpu >= 0.0) { | |
| 972 | 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 incidents | 973 | (Some((base, _)), Some((vcpu, _))) => { |
| 974 | Some((keeper::run_cost(seconds, cpu.min(seconds as f64 * vcpus), base * base_scale, vcpu), cpu)) | |
| 975 | } | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 976 | _ => None, |
| 977 | }, | |
| 978 | None => None, | |
| 979 | }; | |
| Fast pages, required checks on the branch, self-hosted runners, honest incidents | 980 | let cost = parts.map_or(seconds as f64 * cost_per_second * price_scale, |(cost, _)| cost).ceil() as i64; |
| Merge branch 'worktree-agent-a633ac0f7f66d419d' | 981 | 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 look | 982 | 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 put | 983 | let drawn = self.draw(&workspace, charge, &credits::month_of(×tamp), &eligible).await?; |
| 984 | let charge = charge - drawn.total(); | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 985 | let cpu_note = parts.map_or(String::new(), |(_, cpu)| format!(", {cpu:.0} vCPU-seconds")); |
| 986 | 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 daily | 987 | // The price versions it was charged at (pricing.rs). |
| 988 | let meters: &[&str] = if parts.is_some() { &["sandbox_base_second", "sandbox_cpu_second"] } else { &["sandbox_second"] }; | |
| 989 | let mut versions = Vec::new(); | |
| 990 | for meter in meters { | |
| 991 | versions.extend(self.version_now(meter).await?); | |
| 992 | } | |
| 993 | let price_version = versions.join(","); | |
| Every sandbox is metered by the second | 994 | self.db |
| 995 | .batch(vec![ | |
| 996 | self.db | |
| 997 | .prepare( | |
| 998 | "INSERT INTO ledger | |
| 999 | (id, workspace, kind, amount_micros, description, repo, task, | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 1000 | cost_micros, reference, created_at, billed_to, credit_micros, trial_micros, oss_micros, given_micros, price_version, quantity, compute) |
| 1001 | VALUES (?, ?, 'usage', ?, ?, ?, 'sandbox', ?, ?, ?, 'g1t', ?, ?, ?, ?, ?, ?, ?)", | |
| Every sandbox is metered by the second | 1002 | ) |
| 1003 | .bind(&[ | |
| 1004 | new_id("led", now).into(), | |
| 1005 | workspace.as_str().into(), | |
| 1006 | (-(charge as f64)).into(), | |
| 1007 | description.as_str().into(), | |
| 1008 | optional(a.repo.as_deref()), | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1009 | (cost as f64).into(), |
| Every sandbox is metered by the second | 1010 | a.reference.as_str().into(), |
| 1011 | timestamp.as_str().into(), | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 1012 | (drawn.credit as f64).into(), |
| 1013 | (drawn.trial as f64).into(), | |
| 1014 | (drawn.oss as f64).into(), | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1015 | (drawn.given as f64).into(), |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 1016 | optional(Some(price_version.as_str()).filter(|v| !v.is_empty())), |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 1017 | (seconds as f64).into(), |
| 1018 | optional(a.kind.map(ComputeKind::as_str)), | |
| Every sandbox is metered by the second | 1019 | ])?, |
| 1020 | self.db | |
| 1021 | .prepare( | |
| 1022 | "INSERT INTO accounts (workspace, balance_micros, created_at) | |
| 1023 | VALUES (?1, ?2, ?3) | |
| 1024 | ON CONFLICT (workspace) DO UPDATE SET balance_micros = balance_micros + ?2", | |
| 1025 | ) | |
| 1026 | .bind(&[ | |
| 1027 | workspace.as_str().into(), | |
| 1028 | (-(charge as f64)).into(), | |
| 1029 | timestamp.as_str().into(), | |
| 1030 | ])?, | |
| 1031 | ]) | |
| 1032 | .await?; | |
| Merge branch 'worktree-agent-a633ac0f7f66d419d' | 1033 | self.record_discount(&a.reference, discount).await?; |
| Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays | 1034 | self.count_spend(&workspace, cost, charge, &drawn).await; |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1035 | if let Some(reservation) = &a.reservation_id { |
| 1036 | self.settle_reservation(SettleArgs { reservation_id: reservation.clone(), actual_micros: cost }).await?; | |
| 1037 | } | |
| Every sandbox is metered by the second | 1038 | Ok(Outcome::Ok(true)) |
| 1039 | } | |
| 1040 | } | |
| 1041 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1042 | /// Whether an amount may be prepaid: $25 at the least by card, and from |
| 1043 | /// $1,000 by bank transfer. | |
| 1044 | pub(crate) fn prepay_amount(cents: u32, bank_transfer: bool) -> std::result::Result<(), String> { | |
| 1045 | let (min, max) = if bank_transfer { (MIN_BANK_TRANSFER_CENTS, MAX_BANK_TRANSFER_CENTS) } else { (MIN_TOP_UP_CENTS, MAX_TOP_UP_CENTS) }; | |
| 1046 | if (min..=max).contains(¢s) { | |
| 1047 | return Ok(()); | |
| 1048 | } | |
| 1049 | Err(if bank_transfer { | |
| 1050 | format!("Prepay between ${} and ${} by bank transfer.", min / 100, group(max / 100)) | |
| 1051 | } else { | |
| 1052 | format!("Prepay between ${} and ${} by card; from $1,000, a bank transfer works too.", min / 100, group(max / 100)) | |
| 1053 | }) | |
| 1054 | } | |
| 1055 | ||
| 1056 | /// `10,000` for 10000. | |
| 1057 | fn group(n: u32) -> String { | |
| 1058 | let digits = n.to_string(); | |
| 1059 | let mut out = String::new(); | |
| 1060 | 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 kept | 1061 | 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 look | 1062 | out.push(','); |
| 1063 | } | |
| 1064 | out.push(c); | |
| 1065 | } | |
| 1066 | out | |
| 1067 | } | |
| 1068 | ||
| 1069 | #[cfg(test)] | |
| Prices are what g1t pays plus 20%, from the first second | 1070 | /// What `seconds` of sandbox time are charged at `price_per_second`, in |
| 1071 | /// millionths of a dollar: every second, rounded up to the next millionth. | |
| 1072 | fn sandbox_charge(seconds: i64, price_per_second: f64) -> i64 { | |
| 1073 | (seconds as f64 * price_per_second).ceil() as i64 | |
| Every sandbox is metered by the second | 1074 | } |
| 1075 | ||
| 1076 | /// `1h 2m`, `3m 12s` or `40s`. | |
| 1077 | fn duration(seconds: i64) -> String { | |
| 1078 | let (h, m, s) = (seconds / 3600, seconds % 3600 / 60, seconds % 60); | |
| 1079 | if h > 0 { | |
| 1080 | format!("{h}h {m}m") | |
| 1081 | } else if m > 0 { | |
| 1082 | format!("{m}m {s}s") | |
| 1083 | } else { | |
| 1084 | format!("{s}s") | |
| 1085 | } | |
| 1086 | } | |
| 1087 | ||
| Billing accounts, terms and enterprises; g1t is no longer free | 1088 | impl Billing { |
| 1089 | /// What a workspace is charged for something that would be `base`: | |
| 1090 | /// nothing while g1t is free, or as its account's terms say. With a | |
| 1091 | /// note for the statement when it differs. | |
| Merge branch 'worktree-agent-a633ac0f7f66d419d' | 1092 | /// A charge at cost plus the margin (`base`) on the account's terms: |
| 1093 | /// what is charged, the note for the statement, and what a discount | |
| 1094 | /// gave away below `base`. That last is written on the entry | |
| 1095 | /// (`record_discount`) so the reconciliation counts it as given, never | |
| 1096 | /// as margin lost: a sold charge is worth at least its cost plus the | |
| 1097 | /// margin. | |
| 1098 | pub(crate) async fn charged(&self, workspace: &str, base: i64) -> Result<(i64, String, i64)> { | |
| Billing accounts, terms and enterprises; g1t is no longer free | 1099 | if self.free { |
| Merge branch 'worktree-agent-a633ac0f7f66d419d' | 1100 | return Ok((0, " (free while g1t is being built out)".to_owned(), 0)); |
| Billing accounts, terms and enterprises; g1t is no longer free | 1101 | } |
| 1102 | let terms = self.terms_of(workspace).await?; | |
| Merge branch 'worktree-agent-a633ac0f7f66d419d' | 1103 | let (charge, discount) = terms.discounted(base); |
| Billing: credits with a kind and expiry, discounts instead of comped, and safer charging | 1104 | let note = match terms.discount_label() { |
| 1105 | Some(label) if base > 0 => format!(" ({label})"), | |
| Billing accounts, terms and enterprises; g1t is no longer free | 1106 | _ => String::new(), |
| 1107 | }; | |
| Merge branch 'worktree-agent-a633ac0f7f66d419d' | 1108 | Ok((charge, note, discount)) |
| 1109 | } | |
| 1110 | ||
| 1111 | /// What a discount gave away on an entry, below cost plus the margin | |
| 1112 | /// (less than nothing on a correction down). | |
| 1113 | pub(crate) async fn record_discount(&self, reference: &str, micros: i64) -> Result<()> { | |
| 1114 | if micros == 0 { | |
| 1115 | return Ok(()); | |
| 1116 | } | |
| 1117 | self.db | |
| 1118 | .prepare("UPDATE ledger SET discount_micros = ? WHERE reference = ?") | |
| 1119 | .bind(&[(micros as f64).into(), reference.into()])? | |
| 1120 | .run() | |
| 1121 | .await?; | |
| 1122 | Ok(()) | |
| Billing accounts, terms and enterprises; g1t is no longer free | 1123 | } |
| 1124 | } | |
| 1125 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1126 | fn members_only<T>() -> Outcome<T> { |
| 1127 | Outcome::fail( | |
| 1128 | FailureCode::Forbidden, | |
| 1129 | "Only members can see a workspace's billing.", | |
| 1130 | ) | |
| 1131 | } | |
| 1132 | ||
| Prices keep themselves current with what g1t pays | 1133 | impl Billing { |
| 1134 | fn from_env(env: &Env) -> Result<Self> { | |
| 1135 | Ok(Billing { | |
| 1136 | db: env.d1("DB")?, | |
| 1137 | stripe: env | |
| 1138 | .secret("STRIPE_SECRET_KEY") | |
| 1139 | .ok() | |
| 1140 | .map(|key| key.to_string()) | |
| 1141 | .filter(|key| !key.is_empty()) | |
| 1142 | .map(Stripe::new), | |
| Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard | 1143 | webhook_secret: env |
| 1144 | .secret("STRIPE_WEBHOOK_SECRET") | |
| 1145 | .ok() | |
| 1146 | .map(|secret| secret.to_string().trim().to_owned()) | |
| 1147 | .filter(|secret| !secret.is_empty()), | |
| Prices keep themselves current with what g1t pays | 1148 | margin_percent: env |
| 1149 | .var("MARGIN_PERCENT") | |
| 1150 | .ok() | |
| 1151 | .and_then(|percent| percent.to_string().parse().ok()) | |
| 1152 | .unwrap_or(20), | |
| 1153 | 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 kept | 1154 | ceilings: limits::Ceilings::from_env(env), |
| Billing accounts, terms and enterprises; g1t is no longer free | 1155 | 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 put | 1156 | trials_on: { |
| 1157 | let plans = credits::Config::from_env(env); | |
| 1158 | plans.trial_workspace_micros > 0 && plans.trial_monthly_pool_micros > 0 | |
| Prices keep themselves current with what g1t pays | 1159 | }, |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 1160 | plans: credits::Config::from_env(env), |
| 1161 | repos: env.service("REPOS").ok(), | |
| Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member | 1162 | packages: env.service("PACKAGES").ok(), |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1163 | identity: env.service("IDENTITY").ok(), |
| Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays | 1164 | caps: budget::Caps::from_env(env), |
| 1165 | env: env.clone(), | |
| Prices keep themselves current with what g1t pays | 1166 | }) |
| 1167 | } | |
| 1168 | } | |
| 1169 | ||
| Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails | 1170 | /// The fifteen-minute steps, each on its own: one failing never skips the |
| 1171 | /// rest. | |
| 1172 | async fn tick(billing: &Billing, env: &Env, keeper: &keeper::Keeper) { | |
| 1173 | if let Err(error) = billing.settle_runs(keeper).await { | |
| Prices keep themselves current with what g1t pays | 1174 | worker::console_error!("settling runs failed: {error}"); |
| 1175 | } | |
| Merge branch 'model-routing' | 1176 | if let Err(error) = billing.settle_own_runs().await { |
| 1177 | worker::console_error!("closing runs on own providers failed: {error}"); | |
| 1178 | } | |
| Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept | 1179 | // Stripe events billing never received, handled now. |
| 1180 | match billing.replay_events().await { | |
| 1181 | Ok(done) => worker::console_log!("stripe replay: {done}"), | |
| 1182 | Err(error) => worker::console_error!("replaying Stripe events failed: {error}"), | |
| Billing accounts, terms and enterprises; g1t is no longer free | 1183 | } |
| Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails | 1184 | // This month's users, read once for autopay and the warnings. |
| 1185 | let users = if billing.stripe.is_some() { | |
| 1186 | match billing.month_users().await { | |
| 1187 | Ok(users) => Some(users), | |
| 1188 | Err(error) => { | |
| 1189 | worker::console_error!("reading this month's users failed: {error}"); | |
| 1190 | None | |
| 1191 | } | |
| 1192 | } | |
| 1193 | } else { | |
| 1194 | None | |
| 1195 | }; | |
| 1196 | if let Some(users) = &users | |
| 1197 | && let Err(error) = billing.autopay(users).await { | |
| 1198 | worker::console_error!("paying at the limit failed: {error}"); | |
| 1199 | } | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 1200 | // AI credit below a workspace's auto-reload threshold, reloaded (ai.rs). |
| 1201 | match billing.reload_ai_credit().await { | |
| 1202 | Ok(0) => {} | |
| 1203 | Ok(done) => worker::console_log!("auto-reloaded AI credit for {done} workspaces"), | |
| 1204 | Err(error) => worker::console_error!("auto-reloading AI credit failed: {error}"), | |
| 1205 | } | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 1206 | // Last month's metered usage (scans, embeddings, storage) goes on the |
| 1207 | // ledger before the month is closed and invoiced. | |
| 1208 | if let Err(error) = billing.charge_pending().await { | |
| 1209 | worker::console_error!("charging last month's metered usage failed: {error}"); | |
| 1210 | } | |
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 1211 | if let Err(error) = billing.close_months().await { |
| 1212 | worker::console_error!("closing the month failed: {error}"); | |
| 1213 | } | |
| Stripe webhooks, enterprise invoices, and sudo for both | 1214 | if let Err(error) = billing.invoice_enterprises().await { |
| 1215 | worker::console_error!("invoicing enterprises failed: {error}"); | |
| 1216 | } | |
| Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails | 1217 | if let Some(users) = &users |
| 1218 | && let Ok(identity) = env.service("IDENTITY") | |
| 1219 | && let Err(error) = billing.warn_limits(&identity, users).await { | |
| 1220 | worker::console_error!("warning owners failed: {error}"); | |
| 1221 | } | |
| 1222 | } | |
| 1223 | ||
| 1224 | /// Every fifteen minutes: runs settled, Stripe replayed, cards charged at | |
| 1225 | /// the limit, months closed, owners warned. Once a day, at | |
| 1226 | /// [`keeper::DAILY`], in an invocation of its own: the slower checks | |
| 1227 | /// against Stripe and Cloudflare, and measuring. | |
| 1228 | /// | |
| 1229 | /// Each step logs its own failure and the next still runs. The spend | |
| 1230 | /// breaker and budget alerts go first: a step that runs out of CPU ends | |
| 1231 | /// the invocation, and must never take the alerts with it. | |
| 1232 | #[event(scheduled)] | |
| 1233 | async fn scheduled(event: ScheduledEvent, env: Env, _ctx: ScheduleContext) { | |
| 1234 | let Ok(billing) = Billing::from_env(&env) else { | |
| 1235 | return; | |
| 1236 | }; | |
| Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays | 1237 | // Comped budgets' alerts, and a tripped breaker staff were not told of. |
| 1238 | if let Err(error) = billing.watch_spend().await { | |
| 1239 | worker::console_error!("watching g1t's own spend failed: {error}"); | |
| 1240 | } | |
| Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails | 1241 | 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) | 1242 | // Once an hour, at the quarter past: what Cloudflare counted for the |
| 1243 | // whole platform in the hour before, against its thresholds | |
| 1244 | // (platform.rs). | |
| 1245 | if event.cron() == keeper::QUARTER_HOURLY && platform::hourly_due(now_ms()) { | |
| 1246 | match billing.watch_platform(&keeper).await { | |
| 1247 | Ok((read, breached)) => worker::console_log!("platform watch: {read} metrics, {breached} breaches"), | |
| 1248 | Err(error) => worker::console_error!("watching platform usage failed: {error}"), | |
| 1249 | } | |
| 1250 | } | |
| Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails | 1251 | let daily = event.cron() == keeper::DAILY; |
| 1252 | if !daily { | |
| 1253 | tick(&billing, &env, &keeper).await; | |
| 1254 | } | |
| Billing keeps Stripe's view itself: the saved card on the account, missed events replayed every 15 minutes, and the endpoint kept | 1255 | // Once a day: Stripe's endpoint kept listening to billing's events and |
| 1256 | // enabled, and saved cards and plans not read in a while read again. | |
| Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails | 1257 | if daily { |
| Stripe's webhook secret is a Worker secret, STRIPE_WEBHOOK_SECRET, from a destination made in Stripe's dashboard | 1258 | 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 kept | 1259 | Ok(done) => worker::console_log!("stripe endpoint: {done}"), |
| 1260 | Err(error) => worker::console_error!("keeping Stripe's endpoint failed: {error}"), | |
| 1261 | } | |
| 1262 | match billing.refresh_from_stripe().await { | |
| 1263 | Ok(done) => worker::console_log!("stripe refresh: {done}"), | |
| 1264 | Err(error) => worker::console_error!("refreshing from Stripe failed: {error}"), | |
| 1265 | } | |
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 1266 | } |
| The keeper reads Cloudflare as it really answers | 1267 | // Once a day, and at once if the costs were never checked: check every |
| 1268 | // cost against what Cloudflare billed. | |
| Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails | 1269 | 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 kept | 1270 | && let Err(error) = billing.reconcile(&keeper).await { |
| Prices keep themselves current with what g1t pays | 1271 | worker::console_error!("checking costs against Cloudflare failed: {error}"); |
| 1272 | } | |
| Billing: credits with a kind and expiry, discounts instead of comped, and safer charging | 1273 | // Once a day: credit from g1t past its expiry stops counting |
| 1274 | // (grants.rs), before the day is reconciled. | |
| Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails | 1275 | if daily { |
| Billing: credits with a kind and expiry, discounts instead of comped, and safer charging | 1276 | match billing.expire_credits().await { |
| 1277 | Ok(closed) => worker::console_log!("credits expired: {closed}"), | |
| 1278 | Err(error) => worker::console_error!("expiring credits failed: {error}"), | |
| 1279 | } | |
| 1280 | } | |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 1281 | // Once a day: what Cloudflare charged, reconciled against what g1t |
| 1282 | // counted and charged; prices whose day has come; margin alerts | |
| 1283 | // (margin.rs). After the keeper, so its proposals are in. | |
| Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails | 1284 | if daily { |
| Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily | 1285 | match billing.costs_daily(&env, &keeper).await { |
| 1286 | Ok(run) => worker::console_log!("costs: {} lines, {} days, {} proposals, {} alerts", run.lines, run.days, run.proposals, run.alerts), | |
| 1287 | Err(error) => worker::console_error!("reconciling costs failed: {error}"), | |
| 1288 | } | |
| 1289 | } | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1290 | // Once a day: what each workspace's private repositories hold, its git |
| 1291 | // operations, Deployments plans from before the g1t plan set to end, | |
| 1292 | // and old reservations cleared. | |
| Merge branch 'worktree-agent-ab9543c492a7ed481' into spend-guardrails | 1293 | if daily { |
| Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member | 1294 | if let Err(error) = billing.measure_packages().await { |
| 1295 | worker::console_error!("measuring package storage failed: {error}"); | |
| 1296 | } | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 1297 | if let Err(error) = billing.measure_storage().await { |
| 1298 | worker::console_error!("measuring storage failed: {error}"); | |
| 1299 | } | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1300 | if let Err(error) = billing.measure_git().await { |
| 1301 | worker::console_error!("measuring git operations failed: {error}"); | |
| 1302 | } | |
| 1303 | if let Err(error) = billing.retire_deployments_plans().await { | |
| 1304 | worker::console_error!("ending Deployments plans failed: {error}"); | |
| 1305 | } | |
| 1306 | if let Err(error) = billing.sweep_reservations().await { | |
| 1307 | worker::console_error!("clearing reservations failed: {error}"); | |
| 1308 | } | |
| Merge the AI Gateway: Anthropic's Messages API on a workspace's tokens | 1309 | // The AI Gateway's log keeps 30 days (gateway.rs). |
| 1310 | if let Err(error) = billing.forget_gateway_requests().await { | |
| 1311 | worker::console_error!("clearing old AI Gateway requests failed: {error}"); | |
| 1312 | } | |
| Merge branch 'main' into actions-toolkit-oidc-artifacts | 1313 | // Checks of the providers' model lists keep 90 days (catalogue.rs). |
| 1314 | if let Err(error) = billing.forget_model_checks().await { | |
| 1315 | worker::console_error!("clearing old model checks failed: {error}"); | |
| 1316 | } | |
| Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put | 1317 | } |
| Prices keep themselves current with what g1t pays | 1318 | } |
| 1319 | ||
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 1320 | /// Events from the bus, on billing's own queue: only a workspace's rename |
| 1321 | /// matters here (see `rename`). | |
| 1322 | #[event(queue)] | |
| 1323 | async fn queue(batch: MessageBatch<g1t_contracts::events::Event>, env: Env, _ctx: Context) -> Result<()> { | |
| 1324 | let billing = Billing::from_env(&env)?; | |
| 1325 | let identity = env.service("IDENTITY").ok(); | |
| 1326 | for message in batch.messages()? { | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1327 | // A repository transferred: its share of the open-source pool this |
| 1328 | // month follows it. What it was charged stays with the workspace | |
| 1329 | // it was charged to; usage from now on is charged to the new one. | |
| 1330 | if g1t_kit::transfer::on_event(&env, &billing.db, message.body(), closing::TRANSFERRED).await? { | |
| 1331 | message.ack(); | |
| 1332 | continue; | |
| 1333 | } | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 1334 | billing.on_event(identity.as_ref(), message.body()).await?; |
| 1335 | message.ack(); | |
| 1336 | } | |
| 1337 | Ok(()) | |
| 1338 | } | |
| 1339 | ||
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1340 | #[event(fetch)] |
| 1341 | async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> { | |
| 1342 | let Some(method) = rpc_method(&request) else { | |
| 1343 | return Response::error("Not found", 404); | |
| 1344 | }; | |
| Fast pages, required checks on the branch, self-hosted runners, honest incidents | 1345 | // A replica near the caller when it asks for one (crates/kit/src/d1.rs); |
| 1346 | // what other services call (can_start, start_run) asks for none. | |
| 1347 | let (db, served) = g1t_kit::d1::open(&env, "DB", &request)?; | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1348 | let body: serde_json::Value = request.json().await?; |
| Fast pages, required checks on the branch, self-hosted runners, honest incidents | 1349 | let mut billing = Billing::from_env(&env)?; |
| 1350 | billing.db = db; | |
| 1351 | let answered = match method.as_str() { | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1352 | "status" => reply(&billing.status()), |
| 1353 | "account" => reply(&billing.account(args(body)?).await?), | |
| 1354 | "ledger" => reply(&billing.ledger(args(body)?).await?), | |
| Billing: credits with a kind and expiry, discounts instead of comped, and safer charging | 1355 | "credits" => reply(&billing.credits(args(body)?).await?), |
| Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request | 1356 | "usage" => reply(&billing.usage(args(body)?).await?), |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 1357 | "usage_report" => reply(&billing.usage_report(args(body)?).await?), |
| 1358 | "ai_credit" => reply(&billing.ai_credit(args(body)?).await?), | |
| 1359 | "buy_ai_credit" => reply(&billing.buy_ai_credit(args(body)?).await?), | |
| 1360 | "confirm_ai_credit" => reply(&billing.confirm_ai_credit(args(body)?).await?), | |
| 1361 | "set_ai_reload" => reply(&billing.set_ai_reload(args(body)?).await?), | |
| 1362 | "set_budget" => reply(&billing.set_budget(args(body)?).await?), | |
| 1363 | "billing_details" => reply(&billing.billing_details(args(body)?).await?), | |
| 1364 | "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 mix | 1365 | "record_tokens" => reply(&billing.record_tokens(args(body)?).await?), |
| 1366 | "token_usage" => reply(&billing.token_usage(args(body)?).await?), | |
| Merge the AI Gateway: Anthropic's Messages API on a workspace's tokens | 1367 | "gateway_models" => reply(&billing.gateway_models().await?), |
| Merge branch 'main' into actions-toolkit-oidc-artifacts | 1368 | "model_defaults" => reply(&billing.model_defaults().await?), |
| 1369 | "record_discovery" => reply(&billing.record_discovery(args(body)?).await?), | |
| 1370 | "admin_models" => reply(&billing.admin_models().await?), | |
| 1371 | "admin_decide_model" => reply(&billing.admin_decide_model(args(body)?).await?), | |
| 1372 | "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 tokens | 1373 | "gateway_admit" => reply(&billing.gateway_admit(args(body)?).await?), |
| 1374 | "record_gateway" => reply(&billing.record_gateway(args(body)?).await?), | |
| 1375 | "gateway_requests" => reply(&billing.gateway_requests(args(body)?).await?), | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1376 | "checkout" => reply(&billing.checkout(args(body)?).await?), |
| 1377 | "confirm" => reply(&billing.confirm(args(body)?).await?), | |
| 1378 | "can_start" => reply(&billing.can_start(args(body)?).await?), | |
| A free allowance on g1t's models, so anyone can try its agents | 1379 | "trial" => reply(&billing.trial(args(body)?).await?), |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1380 | "start_run" => reply(&billing.start_run(args(body)?).await?), |
| 1381 | "finish_run" => reply(&billing.finish_run(args(body)?).await?), | |
| Paid features: a workspace turns on Deployments with a monthly plan | 1382 | "features" => reply(&billing.features(args(body)?).await?), |
| 1383 | "subscribe" => reply(&billing.subscribe(args(body)?).await?), | |
| 1384 | "confirm_subscription" => reply(&billing.confirm_subscription(args(body)?).await?), | |
| 1385 | "cancel_subscription" => reply(&billing.cancel_subscription(args(body)?).await?), | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1386 | "close_workspace" => reply(&billing.close_workspace(args(body)?).await?), |
| Paid features: a workspace turns on Deployments with a monthly plan | 1387 | "has_feature" => reply(&billing.has_feature(args(body)?).await?), |
| Merge Stripe Tax, the card fee on card payments, and one free workspace per person | 1388 | "free_workspaces" => reply(&billing.free_workspaces(args(body)?).await?), |
| Paid features: a workspace turns on Deployments with a monthly plan | 1389 | "charge_feature" => reply(&billing.charge_feature(args(body)?).await?), |
| Every sandbox is metered by the second | 1390 | "record_sandbox" => reply(&billing.record_sandbox(args(body)?).await?), |
| Usage limits: unpaid usage can only go so far | 1391 | "limit" => reply(&billing.limit(args(body)?).await?), |
| 1392 | "check_limit" => reply(&billing.check_limit(args(body)?).await?), | |
| 1393 | "set_spend_limit" => reply(&billing.set_spend_limit(args(body)?).await?), | |
| Prices keep themselves current with what g1t pays | 1394 | "prices" => reply(&billing.prices().await?), |
| Billing on Stripe's pages, month-end charges, warnings; sudo by workspace | 1395 | "billing_portal" => reply(&billing.billing_portal(args(body)?).await?), |
| 1396 | "admin_billing_link" => reply(&billing.admin_billing_link(args(body)?).await?), | |
| Stripe webhooks, enterprise invoices, and sudo for both | 1397 | "admin_stripe" => reply(&billing.admin_stripe(args(body)?).await?), |
| 1398 | "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 person | 1399 | "admin_enterprise_address" => reply(&billing.admin_enterprise_address(args(body)?).await?), |
| Stripe webhooks, enterprise invoices, and sudo for both | 1400 | "admin_invoice_enterprise" => reply(&billing.admin_invoice_enterprise(args(body)?).await?), |
| 1401 | "stripe_webhook" => reply(&billing.stripe_webhook(args(body)?).await?), | |
| Two limits, real invoices, trust that grows by itself, sales signals | 1402 | "invoices" => reply(&billing.invoices(args(body)?).await?), |
| The statement is a month at a time, a line per kind of charge | 1403 | "statement" => reply(&billing.statement(args(body)?).await?), |
| 1404 | "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 quotas | 1405 | "usage_meters" => reply(&billing.usage_meters(args(body)?).await?), |
| Two limits, real invoices, trust that grows by itself, sales signals | 1406 | "admin_workspace_invoices" => { |
| 1407 | let a: AdminWorkspaceInvoicesArgs = args(body)?; | |
| 1408 | reply(&billing.workspace_invoices(&a.workspace.to_lowercase()).await?) | |
| 1409 | } | |
| 1410 | "admin_signals" => reply(&billing.admin_signals(args(body)?).await?), | |
| 1411 | "admin_overview" => reply(&billing.admin_overview(args(body)?).await?), | |
| 1412 | "admin_sales" => reply(&billing.admin_sales(args(body)?).await?), | |
| 1413 | "admin_set_sales" => reply(&billing.admin_set_sales(args(body)?).await?), | |
| 1414 | "admin_add_note" => reply(&billing.admin_add_note(args(body)?).await?), | |
| Billing lists every invoice and every staff change; signals carry follow-ups | 1415 | "admin_invoices" => reply(&billing.admin_invoices(args(body)?).await?), |
| 1416 | "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 member | 1417 | // A staff change made in another service, for sudo's audit log: |
| 1418 | // identity's restores and purges of deleted workspaces. | |
| 1419 | "admin_log" => { | |
| 1420 | let a: AdminLogArgs = args(body)?; | |
| 1421 | billing | |
| 1422 | .audit(&accounts::own_account(&a.workspace), &a.action, &a.detail, &a.by) | |
| 1423 | .await?; | |
| 1424 | reply(&true) | |
| 1425 | } | |
| Prices keep themselves current with what g1t pays | 1426 | "note_pending" => reply(&billing.note_pending(args(body)?).await?), |
| Billing accounts, terms and enterprises; g1t is no longer free | 1427 | "admin_accounts" => reply(&billing.admin_accounts(args(body)?).await?), |
| 1428 | "admin_account" => reply(&billing.admin_account(args(body)?).await?), | |
| 1429 | "admin_set_terms" => reply(&billing.admin_set_terms(args(body)?).await?), | |
| 1430 | "admin_create_enterprise" => reply(&billing.admin_create_enterprise(args(body)?).await?), | |
| 1431 | "admin_attach" => reply(&billing.admin_attach(args(body)?).await?), | |
| 1432 | "admin_credit" => reply(&billing.admin_credit(args(body)?).await?), | |
| Billing: credits with a kind and expiry, discounts instead of comped, and safer charging | 1433 | "admin_credits" => reply(&billing.admin_credits(args(body)?).await?), |
| 1434 | "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 sold | 1435 | "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 put | 1436 | "admin_set_allowances" => reply(&billing.admin_set_allowances(args(body)?).await?), |
| 1437 | "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 sudo | 1438 | "audit_retention" => reply(&billing.audit_retention(args(body)?).await?), |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1439 | "reserve" => reply(&billing.reserve(args(body)?).await?), |
| 1440 | "settle" => reply(&billing.settle_reservation(args(body)?).await?), | |
| 1441 | "card_check" => reply(&billing.card_check(args(body)?).await?), | |
| 1442 | "confirm_card_check" => reply(&billing.confirm_card_check(args(body)?).await?), | |
| 1443 | "request_limit" => reply(&billing.request_limit(args(body)?).await?), | |
| 1444 | "limit_requests" => reply(&billing.limit_requests(args(body)?).await?), | |
| 1445 | "confirm_spike" => reply(&billing.confirm_spike(args(body)?).await?), | |
| 1446 | "set_caps" => reply(&billing.set_caps(args(body)?).await?), | |
| 1447 | "admin_limit_requests" => reply(&billing.admin_limit_requests(args(body)?).await?), | |
| 1448 | "admin_decide_limit_request" => reply(&billing.admin_decide_limit_request(args(body)?).await?), | |
| 1449 | "admin_overages" => reply(&billing.admin_overages(args(body)?).await?), | |
| 1450 | "admin_goodwill" => reply(&billing.admin_goodwill(args(body)?).await?), | |
| 1451 | "admin_velocity" => reply(&billing.admin_velocity(args(body)?).await?), | |
| 1452 | "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 daily | 1453 | "admin_costs" => reply(&billing.admin_costs(args(body)?, keeper::Keeper::from_env(&env).can_read_bill()).await?), |
| 1454 | "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 pays | 1455 | "admin_spend_caps" => reply(&billing.spend_caps().await?), |
| 1456 | "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) | 1457 | // Platform pauses (src/platform.rs): read by every service that |
| 1458 | // honours one, kept 30 seconds in each isolate. | |
| 1459 | "platform_pause" => reply(&billing.pause_now().await), | |
| 1460 | "admin_platform_guard" => reply(&billing.platform_guard(&keeper::Keeper::from_env(&env)).await?), | |
| 1461 | "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 daily | 1462 | "admin_decide_proposal" => reply(&billing.admin_decide_proposal(args(body)?).await?), |
| 1463 | "admin_set_cost_settings" => reply(&billing.admin_set_cost_settings(args(body)?).await?), | |
| 1464 | "admin_set_cost_mapping" => reply(&billing.admin_set_cost_mapping(args(body)?).await?), | |
| 1465 | "admin_run_costs" => reply(&billing.admin_run_costs(&env, args(body)?).await?), | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1466 | _ => Response::error("Unknown method", 404), |
| Fast pages, required checks on the branch, self-hosted runners, honest incidents | 1467 | }; |
| 1468 | served.finish(answered) | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1469 | } |
| 1470 | ||
| 1471 | #[cfg(test)] | |
| 1472 | mod tests { | |
| 1473 | use super::*; | |
| 1474 | ||
| 1475 | #[test] | |
| 1476 | fn a_run_is_charged_its_cost_plus_the_margin() { | |
| 1477 | // $0.05 at 20% is six cents. | |
| 1478 | assert_eq!(charge_micros(0.05, 20), 60_000); | |
| 1479 | assert_eq!(charge_micros(1.0, 20), 1_200_000); | |
| 1480 | assert_eq!(charge_micros(0.05, 0), 50_000); | |
| 1481 | } | |
| 1482 | ||
| 1483 | #[test] | |
| 1484 | fn fractions_of_a_millionth_round_up_and_nothing_costs_less_than_nothing() { | |
| 1485 | assert_eq!(charge_micros(0.000_000_4, 20), 2); | |
| 1486 | assert_eq!(charge_micros(0.0, 20), 0); | |
| 1487 | assert_eq!(charge_micros(-3.0, 20), 0); | |
| 1488 | } | |
| 1489 | ||
| 1490 | #[test] | |
| Prices are what g1t pays plus 20%, from the first second | 1491 | fn sandbox_time_is_charged_from_the_first_second() { |
| 1492 | // 21 millionths a second at cost, plus 20%. | |
| 1493 | let price = Price::price_for(21.0, 20); | |
| 1494 | assert_eq!(sandbox_charge(1, price), 26); | |
| 1495 | assert_eq!(sandbox_charge(60, price), 1_512); | |
| 1496 | assert_eq!(sandbox_charge(0, price), 0); | |
| Every sandbox is metered by the second | 1497 | } |
| 1498 | ||
| 1499 | #[test] | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1500 | fn prepaying_starts_at_twenty_five_dollars_and_bank_transfers_at_a_thousand() { |
| 1501 | assert!(prepay_amount(2_500, false).is_ok()); | |
| 1502 | assert!(prepay_amount(2_499, false).is_err()); | |
| 1503 | assert!(prepay_amount(10_000, false).is_ok()); | |
| 1504 | assert!(prepay_amount(1_000_000, false).is_ok()); | |
| 1505 | 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."); | |
| 1506 | assert!(prepay_amount(99_999, true).is_err()); | |
| 1507 | assert!(prepay_amount(100_000, true).is_ok()); | |
| 1508 | } | |
| 1509 | ||
| 1510 | #[test] | |
| Every sandbox is metered by the second | 1511 | fn durations_read_plainly() { |
| 1512 | assert_eq!(duration(40), "40s"); | |
| 1513 | assert_eq!(duration(192), "3m 12s"); | |
| 1514 | assert_eq!(duration(3720), "1h 2m"); | |
| 1515 | } | |
| 1516 | ||
| 1517 | #[test] | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1518 | fn an_absurd_cost_is_capped() { |
| 1519 | assert_eq!(charge_micros(1e9, 20), 120 * MICROS_PER_DOLLAR); | |
| 1520 | } | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 1521 | |
| 1522 | /// Every migration, in order, as D1 applies them. | |
| 1523 | const MIGRATIONS: &[&str] = &[ | |
| 1524 | include_str!("../migrations/0001_init.sql"), | |
| 1525 | include_str!("../migrations/0002_own_provider.sql"), | |
| 1526 | include_str!("../migrations/0003_subscriptions.sql"), | |
| 1527 | include_str!("../migrations/0004_sandbox_time.sql"), | |
| 1528 | include_str!("../migrations/0005_limits.sql"), | |
| 1529 | include_str!("../migrations/0006_prices.sql"), | |
| 1530 | include_str!("../migrations/0007_pending_usage.sql"), | |
| 1531 | include_str!("../migrations/0008_accounts.sql"), | |
| 1532 | include_str!("../migrations/0009_autopay.sql"), | |
| 1533 | include_str!("../migrations/0010_month_close.sql"), | |
| 1534 | include_str!("../migrations/0011_limit_warnings.sql"), | |
| 1535 | include_str!("../migrations/0012_stripe_webhooks.sql"), | |
| 1536 | include_str!("../migrations/0013_invoices_trust_sales.sql"), | |
| 1537 | include_str!("../migrations/0014_custom_domain_price.sql"), | |
| 1538 | include_str!("../migrations/0015_sandbox_at_cost.sql"), | |
| 1539 | include_str!("../migrations/0016_plans_and_pools.sql"), | |
| 1540 | include_str!("../migrations/0017_flagon_comped.sql"), | |
| 1541 | include_str!("../migrations/0018_one_plan.sql"), | |
| 1542 | include_str!("../migrations/0019_closed_workspaces.sql"), | |
| 1543 | include_str!("../migrations/0020_syntaqx_standard.sql"), | |
| 1544 | include_str!("../migrations/0021_no_quotas.sql"), | |
| 1545 | include_str!("../migrations/0022_costs_and_margin.sql"), | |
| 1546 | include_str!("../migrations/0023_one_operation_mapping.sql"), | |
| 1547 | include_str!("../migrations/0024_spend_caps.sql"), | |
| 1548 | include_str!("../migrations/0025_run_tier.sql"), | |
| 1549 | include_str!("../migrations/0026_ledger_by_workspace_time.sql"), | |
| 1550 | include_str!("../migrations/0027_stripe_cache.sql"), | |
| 1551 | include_str!("../migrations/0028_drop_stripe_webhooks.sql"), | |
| 1552 | include_str!("../migrations/0029_audit_retention.sql"), | |
| 1553 | include_str!("../migrations/0030_token_usage.sql"), | |
| 1554 | include_str!("../migrations/0031_package_storage.sql"), | |
| 1555 | include_str!("../migrations/0032_workspace_value.sql"), | |
| 1556 | include_str!("../migrations/0033_given_away.sql"), | |
| 1557 | include_str!("../migrations/0034_given_by_why.sql"), | |
| 1558 | include_str!("../migrations/0035_cf_subscriptions.sql"), | |
| 1559 | include_str!("../migrations/0036_model_costs_in_full.sql"), | |
| 1560 | include_str!("../migrations/0037_security_activation.sql"), | |
| 1561 | include_str!("../migrations/0038_staff_credits.sql"), | |
| 1562 | include_str!("../migrations/0039_discounts_not_comped.sql"), | |
| 1563 | include_str!("../migrations/0040_ai_credit.sql"), | |
| Merge branch 'model-routing' | 1564 | include_str!("../migrations/0041_agent_rate_own_key.sql"), |
| 1565 | include_str!("../migrations/0042_agent_rate_weights.sql"), | |
| Merge the AI Gateway: Anthropic's Messages API on a workspace's tokens | 1566 | include_str!("../migrations/0043_tax_and_card_fees.sql"), |
| 1567 | include_str!("../migrations/0044_cache_reads_count_a_tenth.sql"), | |
| 1568 | include_str!("../migrations/0045_gateway.sql"), | |
| Merge branch 'main' into worktree-agent-a69aeabc4b0deeb97 | 1569 | include_str!("../migrations/0046_reset_costs.sql"), |
| 1570 | include_str!("../migrations/0047_gateway_formats.sql"), | |
| Merge branch 'main' into actions-toolkit-oidc-artifacts | 1571 | 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) | 1572 | include_str!("../migrations/0049_superseded_proposals.sql"), |
| 1573 | include_str!("../migrations/0050_ledger_usage_by_time.sql"), | |
| 1574 | include_str!("../migrations/0051_platform_guardrails.sql"), | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 1575 | ]; |
| 1576 | ||
| 1577 | /// The columns of `table` after the migrations: each with whether an | |
| 1578 | /// insert must give it (NOT NULL, no default). | |
| 1579 | fn columns(table: &str) -> Vec<(String, bool)> { | |
| 1580 | let mut out = vec![]; | |
| 1581 | for sql in MIGRATIONS { | |
| 1582 | let sql: String = sql.lines().map(|l| l.split("--").next().unwrap_or("")).collect::<Vec<_>>().join("\n"); | |
| 1583 | if let Some(start) = sql.find(&format!("CREATE TABLE {table} (")) { | |
| 1584 | let body = &sql[start + format!("CREATE TABLE {table} (").len()..]; | |
| 1585 | let body = &body[..body.find(");").unwrap()]; | |
| 1586 | for column in body.split(",\n") { | |
| 1587 | let column = column.trim(); | |
| 1588 | let name = column.split_whitespace().next().unwrap_or("").to_owned(); | |
| 1589 | if name.is_empty() || name == "PRIMARY" { | |
| 1590 | continue; | |
| 1591 | } | |
| 1592 | let required = column.contains("NOT NULL") && !column.contains("DEFAULT") && !column.contains("PRIMARY KEY"); | |
| 1593 | out.push((name, required || column.contains("PRIMARY KEY"))); | |
| 1594 | } | |
| 1595 | } | |
| 1596 | for statement in sql.split(';') { | |
| 1597 | let s = statement.trim(); | |
| 1598 | if let Some(rest) = s.strip_prefix(&format!("ALTER TABLE {table} ADD COLUMN ")) { | |
| 1599 | let name = rest.split_whitespace().next().unwrap().to_owned(); | |
| 1600 | out.push((name, rest.contains("NOT NULL") && !rest.contains("DEFAULT"))); | |
| 1601 | } | |
| 1602 | } | |
| 1603 | } | |
| 1604 | out | |
| 1605 | } | |
| 1606 | ||
| 1607 | /// The columns an `INSERT INTO table (…)` names. | |
| 1608 | fn inserted(sql: &str, table: &str) -> Vec<String> { | |
| 1609 | let start = sql.find(&format!("INSERT INTO {table} (")).unwrap() + format!("INSERT INTO {table} (").len(); | |
| 1610 | sql[start..start + sql[start..].find(')').unwrap()].split(',').map(|c| c.trim().to_owned()).collect() | |
| 1611 | } | |
| 1612 | ||
| 1613 | ||
| 1614 | #[test] | |
| 1615 | fn ai_prices_are_price_book_data_with_dated_versions() { | |
| 1616 | let sql = include_str!("../migrations/0040_ai_credit.sql"); | |
| 1617 | let row = |needle: &str| sql.lines().find(|l| l.contains(needle)).unwrap_or_else(|| panic!("no {needle}")).to_owned(); | |
| 1618 | // AI Gateway: the provider's price, no markup while in beta. | |
| 1619 | assert!(row("('gateway_models', 'AI Gateway models'").contains("1000000, 0, 'list'")); | |
| 1620 | // Models lose their markup from 2026-10-08, a fall that applies at once… | |
| 1621 | assert!(row("('pv_agent_models_2'").contains("1000000, 0, '2026-10-08")); | |
| 1622 | // …and the agent rate is $0.25 a million tokens after 14 days' notice. | |
| 1623 | assert!(row("('pv_agent_tokens_2'").contains("250000, 0, '2026-10-22")); | |
| 1624 | // The card fee is 2.9% + 30¢, switchable. | |
| 1625 | assert!(row("('card_fee_percent'").contains("29000")); | |
| 1626 | assert!(row("('card_fee_fixed'").contains("300000")); | |
| 1627 | assert!(row("('card_fee', 'on'").contains("'on'")); | |
| 1628 | } | |
| Merge branch 'model-routing' | 1629 | |
| 1630 | #[test] | |
| Chat and workspace agents: channels, DMs and named agents you talk to | 1631 | fn a_chat_reply_is_labelled_by_its_agent() { |
| 1632 | assert_eq!(reply_label("acme/@ship"), "Chat reply by @ship in acme"); | |
| 1633 | assert_eq!(reply_label("acme/web"), "Chat reply in acme/web"); | |
| 1634 | } | |
| 1635 | ||
| 1636 | #[test] | |
| Merge branch 'model-routing' | 1637 | fn the_agent_rate_on_an_own_model_key_is_its_own_dated_meter() { |
| 1638 | let sql = include_str!("../migrations/0041_agent_rate_own_key.sql"); | |
| 1639 | let row = |needle: &str| sql.lines().find(|l| l.contains(needle)).unwrap_or_else(|| panic!("no {needle}")).to_owned(); | |
| 1640 | // Nothing until the notice has run… | |
| 1641 | assert!(row("('pv_agent_tokens_own_1'").contains("0, 0, '2026-10-08")); | |
| 1642 | // …then $0.25 a million tokens, as on g1t's models, 14 days after. | |
| 1643 | assert!(row("('pv_agent_tokens_own_2'").contains("250000, 0, '2026-10-22")); | |
| 1644 | assert!(row("('agent_tokens_own',").contains("'million tokens', 0, 0, 'list'")); | |
| 1645 | assert_eq!(ai::agent_rate_meter(true), "agent_tokens_own"); | |
| 1646 | } | |
| 1647 | ||
| 1648 | #[test] | |
| 1649 | fn the_agent_rate_counts_every_token_once_until_a_weight_is_decided() { | |
| 1650 | let sql = include_str!("../migrations/0042_agent_rate_weights.sql"); | |
| 1651 | for kind in ["input", "output", "cache_read", "cache_write"] { | |
| 1652 | let meter = format!("('agent_token_weight_{kind}', 'Agent rate weight"); | |
| 1653 | let row = sql.lines().find(|l| l.contains(&meter)).unwrap_or_else(|| panic!("no {kind} weight")); | |
| 1654 | assert!(row.contains("'weight', 1000000, 0, 'list'"), "{kind}: {row}"); | |
| 1655 | let version = format!("('pv_agent_token_weight_{kind}_1', 'agent_token_weight_{kind}', 1, 1000000,"); | |
| 1656 | assert!(sql.contains(&version), "{kind} has no applied version"); | |
| 1657 | } | |
| 1658 | assert_eq!(ai::weight_of(1_000_000.0), 1.0); | |
| 1659 | } | |
| Usage, Billing settings and prepaid AI credit; fixes from the UX audit | 1660 | #[test] |
| 1661 | fn every_checkout_insert_fills_the_table() { | |
| 1662 | // The plan's, the activation's, a card check's, a prepayment's and | |
| 1663 | // AI credit's pages all go through one insert, and it names every | |
| 1664 | // column the table needs and none it lacks: a missing NOT NULL | |
| 1665 | // column, or one from a migration not yet applied, was a 500. | |
| 1666 | let table = columns("checkouts"); | |
| 1667 | let names: Vec<&str> = table.iter().map(|(n, _)| n.as_str()).collect(); | |
| 1668 | assert_eq!(names, ["id", "workspace", "amount_cents", "created_by", "status", "created_at", "feature", "fee_cents"]); | |
| 1669 | let given = inserted(CHECKOUT_INSERT, "checkouts"); | |
| 1670 | for column in &given { | |
| 1671 | assert!(names.contains(&column.as_str()), "the insert names {column}, which checkouts does not have"); | |
| 1672 | } | |
| 1673 | for (column, required) in &table { | |
| 1674 | assert!(!required || given.contains(column), "checkouts needs {column}, which the insert leaves out"); | |
| 1675 | } | |
| 1676 | // As many values as columns. | |
| 1677 | let values = CHECKOUT_INSERT.split("VALUES").nth(1).unwrap(); | |
| 1678 | assert_eq!(values.matches('?').count() + values.matches("'open'").count(), given.len()); | |
| 1679 | // And no page writes a row of its own any more. | |
| 1680 | for (file, source) in [ | |
| 1681 | ("lib.rs", include_str!("lib.rs")), | |
| 1682 | ("features.rs", include_str!("features.rs")), | |
| 1683 | ("cards.rs", include_str!("cards.rs")), | |
| 1684 | ("ai.rs", include_str!("ai.rs")), | |
| 1685 | ] { | |
| 1686 | let inserts = source.matches(concat!("INSERT INTO ", "checkouts")).count(); | |
| 1687 | assert!(inserts <= usize::from(file == "lib.rs"), "{file} inserts into checkouts on its own"); | |
| 1688 | } | |
| 1689 | } | |
| 1690 | ||
| 1691 | #[test] | |
| 1692 | fn a_new_ledger_column_has_a_default() { | |
| 1693 | // The ledger is written from a dozen places; a column without a | |
| 1694 | // default would break every one that does not name it. | |
| 1695 | for (column, required) in columns("ledger") { | |
| 1696 | assert!(!required || ["id", "workspace", "kind", "amount_micros", "description", "reference", "created_at"].contains(&column.as_str()), "{column}"); | |
| 1697 | } | |
| 1698 | } | |
| Agents as a team: lifecycle, merge queue, billing and a new shell | 1699 | } |
This file's history is long; its oldest lines are credited to the oldest commit read.