flagon-io/g1t

public

Git for AI scale: a forge for thousands of agents working on the same code at once.

g1t/services/billing/src/lib.rs

995 lines38,481 bytesCodeBlame

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

Agents as a team: lifecycle, merge queue, billing and a new shell1//! The billing service: what agents cost, charged to the workspace they
2//! worked for.
3//!
4//! A workspace buys credit with a card. Before the runner starts an agent
5//! it asks here, and is refused if the workspace has none. When the
6//! agent's sandbox finishes it reports what the model cost, and that plus
7//! g1t's margin comes off the balance. Every change is a ledger entry, and
8//! a balance is always the sum of its ledger.
9//!
Paid features: a workspace turns on Deployments with a monthly plan10//! Paid features (deployments) are bought separately, as monthly plans;
11//! see `features`. They are never free.
12//!
Agents as a team: lifecycle, merge queue, billing and a new shell13//! Without a card processor configured the service says so and charges
14//! nothing, so that g1t still runs where billing has not been set up.
15//!
16//! Reached only through service bindings; see `g1t_contracts::billing` for
17//! the methods and their arguments.
18
Billing accounts, terms and enterprises; g1t is no longer free19mod accounts;
Paid features: a workspace turns on Deployments with a monthly plan20mod features;
Prices keep themselves current with what g1t pays21mod keeper;
Usage limits: unpaid usage can only go so far22mod limits;
Agents as a team: lifecycle, merge queue, billing and a new shell23mod stripe;
24
25use g1t_contracts::billing::*;
26use g1t_contracts::time::rfc3339;
27use g1t_contracts::{FailureCode, Outcome, Role, new_id};
Billing accounts, terms and enterprises; g1t is no longer free28use g1t_contracts::billing::TermsKind;
Agents as a team: lifecycle, merge queue, billing and a new shell29use g1t_kit::{args, now_ms, reply, rpc_method};
30use serde::Deserialize;
31use sha2::{Digest, Sha256};
32use worker::wasm_bindgen::JsValue;
Prices keep themselves current with what g1t pays33use worker::{Context, D1Database, Env, Request, Response, Result, ScheduleContext, ScheduledEvent, event};
Agents as a team: lifecycle, merge queue, billing and a new shell34
35use stripe::Stripe;
36
37const MIN_TOP_UP_CENTS: u32 = 500;
38const MAX_TOP_UP_CENTS: u32 = 50_000;
39const LEDGER_PAGE: u32 = 100;
40/// A run's reported cost is believed up to this much. A sandbox cannot
41/// spend more in the time it has, so anything above is a fault.
42const MAX_RUN_COST_USD: f64 = 100.0;
43
44/// What a run is charged: its cost plus the margin, rounded up to a whole
45/// millionth of a dollar.
46pub fn charge_micros(cost_usd: f64, margin_percent: u32) -> i64 {
47 let cost_micros = (cost_usd.clamp(0.0, MAX_RUN_COST_USD) * MICROS_PER_DOLLAR as f64).ceil();
48 (cost_micros * f64::from(100 + margin_percent) / 100.0).ceil() as i64
49}
50
51fn hash(token: &str) -> String {
52 hex::encode(Sha256::digest(token.as_bytes()))
53}
54
55fn optional(value: Option<&str>) -> JsValue {
56 value.map_or(JsValue::NULL, JsValue::from)
57}
58
59#[derive(Deserialize)]
60struct AccountRow {
61 balance_micros: i64,
62 customer_id: Option<String>,
63}
64
65#[derive(Deserialize)]
66struct LedgerRow {
67 id: String,
68 kind: EntryKind,
69 amount_micros: i64,
70 description: String,
71 repo: Option<String>,
72 number: Option<u32>,
73 task: Option<String>,
74 model: Option<String>,
75 created_by: Option<String>,
76 created_at: String,
Integrations: your own model provider, alerts that open issues, tickets agents read77 billed_to: Option<String>,
Agents as a team: lifecycle, merge queue, billing and a new shell78}
79
80impl From<LedgerRow> for LedgerEntry {
81 fn from(row: LedgerRow) -> Self {
82 LedgerEntry {
83 id: row.id,
84 kind: row.kind,
85 amount_micros: row.amount_micros,
86 description: row.description,
87 repo: row.repo,
88 number: row.number,
89 task: row.task,
90 model: row.model,
Integrations: your own model provider, alerts that open issues, tickets agents read91 billed_to: row.billed_to.unwrap_or_else(|| "g1t".to_owned()),
Agents as a team: lifecycle, merge queue, billing and a new shell92 created_by: row.created_by,
93 created_at: row.created_at,
94 }
95 }
96}
97
98#[derive(Deserialize)]
99struct RunRow {
100 workspace: String,
101 repo: String,
102 number: u32,
103 task: String,
104 model: String,
105 token_hash: String,
Integrations: your own model provider, alerts that open issues, tickets agents read106 billed_to: Option<String>,
107}
108
109impl RunRow {
110 fn own_provider(&self) -> bool {
111 self.billed_to.as_deref() == Some("workspace")
112 }
Agents as a team: lifecycle, merge queue, billing and a new shell113}
114
115#[derive(Deserialize)]
116struct CheckoutRow {
117 workspace: String,
118 created_by: String,
119}
120
121/// A row an `UPDATE … RETURNING` touched.
122#[derive(Deserialize)]
123struct Touched {
124 #[allow(dead_code)]
125 id: String,
126}
127
128struct Billing {
129 db: D1Database,
130 /// Absent when no card processor is configured.
131 stripe: Option<Stripe>,
132 margin_percent: u32,
Integrations: your own model provider, alerts that open issues, tickets agents read133 /// Charged for a run on the workspace's own model provider.
134 orchestration_fee_micros: i64,
Free while g1t is being built out; agents can check out their own forks135 /// While g1t is being built out, nothing is charged (`FREE_WHILE_BUILDING`).
136 free: bool,
A free allowance on g1t's models, so anyone can try its agents137 /// The free allowance on g1t's hosted models, when there is one.
138 trial: Option<TrialConfig>,
Paid features: a workspace turns on Deployments with a monthly plan139 /// The Deployments plan's monthly price (`DEPLOYMENTS_MONTHLY_CENTS`).
140 deployments_monthly_cents: u32,
Usage limits: unpaid usage can only go so far141 /// How far unpaid usage may go; see `limits`.
142 ceilings: limits::Ceilings,
Billing accounts, terms and enterprises; g1t is no longer free143 /// `PREPAID_ONLY`: the old rule, that agents need credit first.
144 prepaid_only: bool,
A free allowance on g1t's models, so anyone can try its agents145}
146
147/// `TRIAL_WORKSPACE_MICROS`, `TRIAL_TOTAL_MICROS` and `TRIAL_UNTIL`.
148struct TrialConfig {
149 per_workspace_micros: i64,
150 total_micros: i64,
151 /// RFC 3339, in UTC.
152 until: String,
153}
154
155#[derive(serde::Deserialize)]
156struct Sum {
157 micros: Option<i64>,
Agents as a team: lifecycle, merge queue, billing and a new shell158}
159
160impl Billing {
161 fn status(&self) -> Status {
162 Status {
163 enabled: self.stripe.is_some(),
164 live: self.stripe.as_ref().is_some_and(Stripe::live),
Free while g1t is being built out; agents can check out their own forks165 free: self.free,
Agents as a team: lifecycle, merge queue, billing and a new shell166 }
167 }
168
169 async fn row(&self, workspace: &str) -> Result<Option<AccountRow>> {
170 self.db
171 .prepare("SELECT balance_micros, customer_id FROM accounts WHERE workspace = ?")
172 .bind(&[workspace.into()])?
173 .first::<AccountRow>(None)
174 .await
175 }
176
177 async fn standing(&self, workspace: &str) -> Result<Account> {
178 Ok(Account {
179 workspace: workspace.to_owned(),
180 balance_micros: self
181 .row(workspace)
182 .await?
183 .map_or(0, |row| row.balance_micros),
184 status: self.status(),
185 margin_percent: self.margin_percent,
Integrations: your own model provider, alerts that open issues, tickets agents read186 orchestration_fee_micros: self.orchestration_fee_micros,
Agents as a team: lifecycle, merge queue, billing and a new shell187 })
188 }
189
190 /// Adds a ledger entry and moves the balance by the same amount, as
191 /// one write.
192 #[allow(clippy::too_many_arguments)]
193 async fn enter(
194 &self,
195 workspace: &str,
196 kind: EntryKind,
197 amount_micros: i64,
198 description: &str,
199 reference: &str,
200 run: Option<&RunRow>,
201 cost_micros: Option<i64>,
202 created_by: Option<&str>,
203 customer: Option<&str>,
204 ) -> Result<()> {
205 let now = now_ms();
206 let timestamp = rfc3339(now);
207 let kind = match kind {
208 EntryKind::TopUp => "top_up",
209 EntryKind::Usage => "usage",
210 };
211 self.db
212 .batch(vec![
213 self.db
214 .prepare(
215 "INSERT INTO ledger
216 (id, workspace, kind, amount_micros, description, repo, number, task,
Integrations: your own model provider, alerts that open issues, tickets agents read217 model, cost_micros, reference, created_by, created_at, billed_to)
218 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
Agents as a team: lifecycle, merge queue, billing and a new shell219 )
220 .bind(&[
221 new_id("led", now).into(),
222 workspace.into(),
223 kind.into(),
224 // D1 takes numbers as doubles, which hold every
225 // amount this service will see exactly.
226 (amount_micros as f64).into(),
227 description.into(),
228 optional(run.map(|run| run.repo.as_str())),
229 run.map_or(JsValue::NULL, |run| run.number.into()),
230 optional(run.map(|run| run.task.as_str())),
231 optional(run.map(|run| run.model.as_str())),
232 cost_micros.map_or(JsValue::NULL, |cost| (cost as f64).into()),
233 reference.into(),
234 optional(created_by),
235 timestamp.as_str().into(),
Integrations: your own model provider, alerts that open issues, tickets agents read236 run.map_or("g1t", |run| if run.own_provider() { "workspace" } else { "g1t" }).into(),
Agents as a team: lifecycle, merge queue, billing and a new shell237 ])?,
238 self.db
239 .prepare(
240 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at)
241 VALUES (?1, ?2, ?3, ?4)
242 ON CONFLICT (workspace) DO UPDATE SET
243 balance_micros = balance_micros + ?2,
244 customer_id = COALESCE(?3, customer_id)",
245 )
246 .bind(&[
247 workspace.into(),
248 (amount_micros as f64).into(),
249 optional(customer),
250 timestamp.as_str().into(),
251 ])?,
252 ])
253 .await?;
Billing accounts, terms and enterprises; g1t is no longer free254 // Money in clears a card declined at the limit.
255 if kind == "top_up" {
256 self.db
257 .prepare("UPDATE limits SET autopay_failed_at = NULL, autopay_error = NULL WHERE workspace = ?")
258 .bind(&[workspace.into()])?
259 .run()
260 .await?;
261 }
Agents as a team: lifecycle, merge queue, billing and a new shell262 Ok(())
263 }
264
265 async fn account(&self, a: AccountArgs) -> Result<Outcome<Account>> {
266 let workspace = a.workspace.to_lowercase();
267 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
268 return Ok(members_only());
269 }
270 Ok(Outcome::Ok(self.standing(&workspace).await?))
271 }
272
273 async fn ledger(&self, a: AccountArgs) -> Result<Outcome<Vec<LedgerEntry>>> {
274 let workspace = a.workspace.to_lowercase();
275 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
276 return Ok(members_only());
277 }
278 let rows = self
279 .db
280 .prepare("SELECT * FROM ledger WHERE workspace = ? ORDER BY id DESC LIMIT ?")
281 .bind(&[workspace.into(), LEDGER_PAGE.into()])?
282 .all()
283 .await?
284 .results::<LedgerRow>()?;
285 Ok(Outcome::Ok(
286 rows.into_iter().map(LedgerEntry::from).collect(),
287 ))
288 }
289
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request290 async fn usage(&self, a: UsageArgs) -> Result<Outcome<Usage>> {
291 let workspace = a.workspace.to_lowercase();
292 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
293 return Ok(members_only());
294 }
295 #[derive(serde::Deserialize)]
296 struct SliceRow {
297 key: Option<String>,
298 micros: Option<i64>,
299 runs: Option<u32>,
300 }
Usage while free is shown at cost; agents get rustfmt and clippy301 // While nothing is charged, what was used is what there is to show.
302 let measure = if self.free { "COALESCE(cost_micros, 0)" } else { "-amount_micros" };
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request303 let slices = |key: &str, limit: u32| {
304 format!(
Usage while free is shown at cost; agents get rustfmt and clippy305 "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 request306 WHERE workspace = ?1 AND kind = 'usage' AND created_at >= ?2
307 GROUP BY 1 ORDER BY micros DESC LIMIT {limit}"
308 )
309 };
310 let query = |sql: String| {
311 let db = &self.db;
312 let workspace = workspace.clone();
313 let since = a.since.clone();
314 async move {
315 let rows = db
316 .prepare(sql)
317 .bind(&[workspace.into(), since.into()])?
318 .all()
319 .await?
320 .results::<SliceRow>()?;
321 Ok::<Vec<UsageSlice>, worker::Error>(
322 rows.into_iter()
323 .map(|row| UsageSlice {
324 key: row.key.unwrap_or_else(|| "other".to_owned()),
325 micros: row.micros.unwrap_or_default(),
326 runs: row.runs.unwrap_or_default(),
327 })
328 .collect(),
329 )
330 }
331 };
332 #[derive(serde::Deserialize)]
333 struct Totals {
334 spent: Option<i64>,
335 cost: Option<i64>,
Integrations: your own model provider, alerts that open issues, tickets agents read336 provider: Option<i64>,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request337 runs: Option<u32>,
338 added: Option<i64>,
339 }
340 let totals = self
341 .db
342 .prepare(
343 "SELECT
344 -SUM(CASE WHEN kind = 'usage' THEN amount_micros END) AS spent,
Integrations: your own model provider, alerts that open issues, tickets agents read345 SUM(CASE WHEN kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' THEN cost_micros END) AS cost,
346 SUM(CASE WHEN kind = 'usage' AND billed_to = 'workspace' THEN cost_micros END) AS provider,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request347 SUM(CASE WHEN kind = 'usage' THEN 1 ELSE 0 END) AS runs,
348 SUM(CASE WHEN kind = 'top_up' THEN amount_micros END) AS added
349 FROM ledger WHERE workspace = ?1 AND created_at >= ?2",
350 )
351 .bind(&[workspace.as_str().into(), a.since.as_str().into()])?
352 .first::<Totals>(None)
353 .await?;
354 let totals = totals.unwrap_or(Totals {
355 spent: None,
356 cost: None,
Integrations: your own model provider, alerts that open issues, tickets agents read357 provider: None,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request358 runs: None,
359 added: None,
360 });
361 Ok(Outcome::Ok(Usage {
362 spent_micros: totals.spent.unwrap_or_default(),
363 cost_micros: totals.cost.unwrap_or_default(),
Integrations: your own model provider, alerts that open issues, tickets agents read364 provider_micros: totals.provider.unwrap_or_default(),
Usage while free is shown at cost; agents get rustfmt and clippy365 used_micros: totals.cost.unwrap_or_default() + totals.provider.unwrap_or_default(),
366 free: self.free,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request367 runs: totals.runs.unwrap_or_default(),
368 added_micros: totals.added.unwrap_or_default(),
369 by_day: query(slices("substr(created_at, 1, 10) || '/' || COALESCE(task, 'other')", 400)).await?,
370 by_task: query(slices("task", 20)).await?,
371 by_repo: query(slices("repo", 20)).await?,
372 by_pull: query(slices("repo || '#' || number", 10)).await?,
373 by_model: query(slices("model", 10)).await?,
374 since: a.since,
375 }))
376 }
377
Agents as a team: lifecycle, merge queue, billing and a new shell378 async fn checkout(&self, a: CheckoutArgs) -> Result<Outcome<Checkout>> {
379 let workspace = a.workspace.to_lowercase();
380 if a.actor.role_in(&workspace) != Some(Role::Owner) {
381 return Ok(Outcome::fail(
382 FailureCode::Forbidden,
383 "Only an owner can add credit to a workspace.",
384 ));
385 }
386 let Some(stripe) = &self.stripe else {
387 return Ok(Outcome::fail(
388 FailureCode::Conflict,
389 "Payments are not set up on this g1t yet.",
390 ));
391 };
392 if !(MIN_TOP_UP_CENTS..=MAX_TOP_UP_CENTS).contains(&a.amount_cents) {
393 return Ok(Outcome::fail(
394 FailureCode::Invalid,
395 format!(
396 "Add between ${} and ${} at a time.",
397 MIN_TOP_UP_CENTS / 100,
398 MAX_TOP_UP_CENTS / 100
399 ),
400 ));
401 }
402 let customer = self.row(&workspace).await?.and_then(|row| row.customer_id);
Project dependencies: addresses, preview stacks, Affects, and agents who know403 let session = match stripe
404 .start_checkout(&workspace, a.amount_cents, customer.as_deref(), &a.return_url)
405 .await
406 {
407 Ok(session) => session,
408 // A customer saved under another Stripe account: start afresh.
409 Err(error) if customer.is_some() && stripe::is_missing(&error) => {
410 self.forget_customer(&workspace).await?;
411 stripe.start_checkout(&workspace, a.amount_cents, None, &a.return_url).await?
412 }
413 Err(error) => return Err(error),
414 };
Agents as a team: lifecycle, merge queue, billing and a new shell415 let Some(url) = session.url else {
416 return Err(worker::Error::RustError(
417 "the card processor returned no payment page".into(),
418 ));
419 };
420 self.db
421 .prepare(
422 "INSERT INTO checkouts (id, workspace, amount_cents, created_by, created_at)
423 VALUES (?, ?, ?, ?, ?)",
424 )
425 .bind(&[
426 session.id.into(),
427 workspace.into(),
428 a.amount_cents.into(),
429 a.actor.username.into(),
430 rfc3339(now_ms()).into(),
431 ])?
432 .run()
433 .await?;
434 Ok(Outcome::Ok(Checkout { url }))
435 }
436
437 /// Credits a payment if the processor says it was made and it has not
438 /// been credited before. The amount credited is what the processor
439 /// says was paid, not what anyone here remembers asking for.
440 async fn confirm(&self, a: ConfirmArgs) -> Result<Outcome<Account>> {
441 let workspace = a.workspace.to_lowercase();
442 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
443 return Ok(members_only());
444 }
445 let (Some(stripe), Some(checkout)) = (
446 &self.stripe,
447 self.db
448 .prepare(
449 "SELECT workspace, created_by FROM checkouts
450 WHERE id = ? AND workspace = ? AND status = 'open'",
451 )
452 .bind(&[a.session.as_str().into(), workspace.as_str().into()])?
453 .first::<CheckoutRow>(None)
454 .await?,
455 ) else {
456 // Unknown, someone else's, or already credited: nothing to do.
457 return Ok(Outcome::Ok(self.standing(&workspace).await?));
458 };
459 let session = stripe.session(&a.session).await?;
460 let paid = session
461 .amount_total
462 .filter(|_| session.payment_status == "paid");
463 if let Some(cents) = paid {
464 // Only whoever flips it from open to paid enters the credit.
465 let claimed = self
466 .db
467 .prepare(
468 "UPDATE checkouts SET status = 'paid' WHERE id = ? AND status = 'open'
469 RETURNING id",
470 )
471 .bind(&[a.session.as_str().into()])?
472 .first::<Touched>(None)
473 .await?;
474 if claimed.is_some() {
475 self.enter(
476 &checkout.workspace,
477 EntryKind::TopUp,
478 i64::from(cents) * MICROS_PER_DOLLAR / 100,
479 "Credit added by card",
480 &session.id,
481 None,
482 None,
483 Some(&checkout.created_by),
484 session.customer.as_deref(),
485 )
486 .await?;
487 }
488 }
489 Ok(Outcome::Ok(self.standing(&workspace).await?))
490 }
491
Project dependencies: addresses, preview stacks, Affects, and agents who know492 /// Drops a saved customer the card processor no longer knows.
493 pub(crate) async fn forget_customer(&self, workspace: &str) -> Result<()> {
494 self.db
495 .prepare("UPDATE accounts SET customer_id = NULL WHERE workspace = ?")
496 .bind(&[workspace.into()])?
497 .run()
498 .await?;
499 Ok(())
500 }
501
Agents as a team: lifecycle, merge queue, billing and a new shell502 /// A refusal if the workspace has no credit to start an agent with.
503 async fn out_of_credit<T>(&self, workspace: &str) -> Result<Option<Outcome<T>>> {
Billing accounts, terms and enterprises; g1t is no longer free504 // Billing is postpaid: usage limits decide whether work starts
505 // (see `limits`), and credit is a prepayment that lowers what is
506 // owed. A balance no longer has to be positive to start.
507 if self.free || !self.prepaid_only {
Free while g1t is being built out; agents can check out their own forks508 return Ok(None);
509 }
Agents as a team: lifecycle, merge queue, billing and a new shell510 let balance = self
511 .row(workspace)
512 .await?
513 .map_or(0, |row| row.balance_micros);
514 Ok((balance <= 0).then(|| {
515 Outcome::fail(
516 FailureCode::PaymentRequired,
517 format!(
518 "The {workspace} workspace has no agent credit. An owner can add some under Billing on the workspace's page."
519 ),
520 )
521 }))
522 }
523
A free allowance on g1t's models, so anyone can try its agents524 /// A workspace's free allowance on g1t's hosted models: what its runs
525 /// there have cost against its share, and the pool everyone draws on.
Billing accounts, terms and enterprises; g1t is no longer free526 /// How much of a hosted model run's cost the workspace's free allowance
527 /// covers, if it is still open.
528 async fn trial_covers(&self, workspace: &str, cost_micros: i64) -> Result<i64> {
529 let trial = self.trial(TrialArgs { workspace: workspace.to_owned(), exempt: vec![] }).await?;
530 if !trial.open {
531 return Ok(0);
532 }
533 Ok(cost_micros.min((trial.limit_micros - trial.used_micros).max(0)))
534 }
535
A free allowance on g1t's models, so anyone can try its agents536 async fn trial(&self, a: TrialArgs) -> Result<Trial> {
537 let workspace = a.workspace.to_lowercase();
538 let Some(config) = &self.trial else {
539 return Ok(Trial {
540 open: false,
541 used_micros: 0,
542 limit_micros: 0,
543 ends_at: None,
544 reason: Some("off".to_owned()),
545 });
546 };
547 let used = self
548 .db
549 .prepare(
550 "SELECT SUM(cost_micros) AS micros FROM ledger
Billing accounts, terms and enterprises; g1t is no longer free551 WHERE kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' AND COALESCE(task, '') NOT IN ('sandbox', 'deployments') AND workspace = ?",
A free allowance on g1t's models, so anyone can try its agents552 )
553 .bind(&[workspace.as_str().into()])?
554 .first::<Sum>(None)
555 .await?
556 .and_then(|sum| sum.micros)
557 .unwrap_or_default();
558 // Everyone's, but for the workspaces open to hosted models anyway.
559 let exempt: Vec<String> = a.exempt.iter().map(|name| name.trim().to_lowercase()).collect();
560 let marks = vec!["?"; exempt.len().max(1)].join(", ");
561 let mut values: Vec<JsValue> = exempt.iter().map(|name| JsValue::from(name.as_str())).collect();
562 if values.is_empty() {
563 values.push(JsValue::from(""));
564 }
565 let pooled = self
566 .db
567 .prepare(format!(
568 "SELECT SUM(cost_micros) AS micros FROM ledger
Billing accounts, terms and enterprises; g1t is no longer free569 WHERE kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' AND COALESCE(task, '') NOT IN ('sandbox', 'deployments') AND workspace NOT IN ({marks})"
A free allowance on g1t's models, so anyone can try its agents570 ))
571 .bind(&values)?
572 .first::<Sum>(None)
573 .await?
574 .and_then(|sum| sum.micros)
575 .unwrap_or_default();
576 let reason = if rfc3339(now_ms()) >= config.until {
577 Some("ended")
578 } else if used >= config.per_workspace_micros {
579 Some("used")
580 } else if pooled >= config.total_micros {
581 Some("pool")
582 } else {
583 None
584 };
585 Ok(Trial {
586 open: reason.is_none(),
587 used_micros: used,
588 limit_micros: config.per_workspace_micros,
589 ends_at: Some(config.until.clone()),
590 reason: reason.map(str::to_owned),
591 })
592 }
593
Agents as a team: lifecycle, merge queue, billing and a new shell594 async fn can_start(&self, a: CanStartArgs) -> Result<Outcome<bool>> {
595 if self.stripe.is_none() {
596 return Ok(Outcome::Ok(true));
597 }
Usage limits: unpaid usage can only go so far598 if let Some(stopped) = self.stopped(&a.workspace).await? {
599 return Ok(stopped);
600 }
Agents as a team: lifecycle, merge queue, billing and a new shell601 Ok(self
602 .out_of_credit(&a.workspace.to_lowercase())
603 .await?
604 .unwrap_or(Outcome::Ok(true)))
605 }
606
607 async fn start_run(&self, a: StartRunArgs) -> Result<Outcome<Option<RunTicket>>> {
608 if self.stripe.is_none() {
609 return Ok(Outcome::Ok(None));
610 }
611 let workspace = a.workspace.to_lowercase();
Usage limits: unpaid usage can only go so far612 if let Some(stopped) = self.stopped(&workspace).await? {
613 return Ok(stopped);
614 }
Agents as a team: lifecycle, merge queue, billing and a new shell615 if let Some(refused) = self.out_of_credit(&workspace).await? {
616 return Ok(refused);
617 }
618 let now = now_ms();
619 let run_id = new_id("run", now);
620 let mut bytes = [0u8; 32];
621 getrandom::getrandom(&mut bytes).expect("no source of randomness");
622 let token = hex::encode(bytes);
623 self.db
624 .prepare(
Prices keep themselves current with what g1t pays625 "INSERT INTO runs (id, workspace, repo, number, task, model, token_hash, created_at, billed_to, session_id)
626 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
Agents as a team: lifecycle, merge queue, billing and a new shell627 )
628 .bind(&[
629 run_id.as_str().into(),
630 workspace.into(),
631 format!("{}/{}", a.repo.namespace, a.repo.name).into(),
632 a.number.into(),
633 a.task.into(),
634 a.model.into(),
635 hash(&token).into(),
636 rfc3339(now).into(),
Integrations: your own model provider, alerts that open issues, tickets agents read637 if a.billed_to == "workspace" { "workspace" } else { "g1t" }.into(),
Prices keep themselves current with what g1t pays638 optional(a.session.as_deref().filter(|_| a.billed_to != "workspace")),
Agents as a team: lifecycle, merge queue, billing and a new shell639 ])?
640 .run()
641 .await?;
642 Ok(Outcome::Ok(Some(RunTicket { run_id, token })))
643 }
644
645 async fn finish_run(&self, a: FinishRunArgs) -> Result<Outcome<bool>> {
646 let run = self
647 .db
648 .prepare(
Integrations: your own model provider, alerts that open issues, tickets agents read649 "SELECT workspace, repo, number, task, model, token_hash, billed_to FROM runs
Agents as a team: lifecycle, merge queue, billing and a new shell650 WHERE id = ? AND finished_at IS NULL",
651 )
652 .bind(&[a.run_id.as_str().into()])?
653 .first::<RunRow>(None)
654 .await?;
655 let Some(run) = run.filter(|run| run.token_hash == hash(&a.token)) else {
656 return Ok(Outcome::fail(FailureCode::NotFound, "Run not found."));
657 };
658 if !a.cost_usd.is_finite() || a.cost_usd < 0.0 {
659 return Ok(Outcome::fail(FailureCode::Invalid, "That is not a cost."));
660 }
661 // Only whoever closes the run charges for it.
662 let claimed = self
663 .db
664 .prepare(
665 "UPDATE runs SET finished_at = ? WHERE id = ? AND finished_at IS NULL RETURNING id",
666 )
667 .bind(&[rfc3339(now_ms()).into(), a.run_id.as_str().into()])?
668 .first::<Touched>(None)
669 .await?;
670 if claimed.is_none() {
671 return Ok(Outcome::Ok(false));
672 }
Integrations: your own model provider, alerts that open issues, tickets agents read673 // On the workspace's own provider, the model was paid for there:
674 // g1t charges its fee, and keeps the provider's cost to show.
Billing accounts, terms and enterprises; g1t is no longer free675 let base = if run.own_provider() {
Integrations: your own model provider, alerts that open issues, tickets agents read676 self.orchestration_fee_micros
677 } else {
Billing accounts, terms and enterprises; g1t is no longer free678 // The free allowance on g1t's models covers what it can.
679 let cost = charge_micros(a.cost_usd, 0);
680 let covered = self.trial_covers(&run.workspace, cost).await?;
681 charge_micros((cost - covered) as f64 / MICROS_PER_DOLLAR as f64, self.margin_percent)
Integrations: your own model provider, alerts that open issues, tickets agents read682 };
Billing accounts, terms and enterprises; g1t is no longer free683 let (charge, terms_note) = self.charged(&run.workspace, base).await?;
Integrations: your own model provider, alerts that open issues, tickets agents read684 let mut description = match run.task.as_str() {
Agents as a team: lifecycle, merge queue, billing and a new shell685 "plan" => format!("Planning for {}", run.repo),
686 "review" => format!("Review of {}#{}", run.repo, run.number),
687 "update" => format!("Catching up {}#{}", run.repo, run.number),
688 _ => format!("Work on {}#{}", run.repo, run.number),
689 };
Integrations: your own model provider, alerts that open issues, tickets agents read690 if run.own_provider() {
691 description.push_str(", on your own model provider");
692 }
Billing accounts, terms and enterprises; g1t is no longer free693 description.push_str(&terms_note);
Agents as a team: lifecycle, merge queue, billing and a new shell694 self.enter(
695 &run.workspace,
696 EntryKind::Usage,
697 -charge,
698 &description,
699 &a.run_id,
700 Some(&run),
701 Some(charge_micros(a.cost_usd, 0)),
702 None,
703 None,
704 )
705 .await?;
706 Ok(Outcome::Ok(true))
707 }
708}
709
Every sandbox is metered by the second710impl Billing {
711 /// Records how long a sandbox ran: its cost always, and a charge for
712 /// the seconds past the month's free minutes.
713 async fn record_sandbox(&self, a: RecordSandboxArgs) -> Result<Outcome<bool>> {
714 if self.stripe.is_none() || a.seconds == 0 {
715 return Ok(Outcome::Ok(false));
716 }
717 let workspace = a.workspace.to_lowercase();
718 let seen = self
719 .db
720 .prepare("SELECT id FROM ledger WHERE reference = ?")
721 .bind(&[a.reference.as_str().into()])?
722 .first::<Touched>(None)
723 .await?;
724 if seen.is_some() {
725 return Ok(Outcome::Ok(false));
726 }
727 let now = now_ms();
728 let timestamp = rfc3339(now);
729 let month = &timestamp[..7];
730 #[derive(Deserialize)]
731 struct Used {
732 seconds: i64,
733 }
734 let seconds = i64::from(a.seconds);
735 let after = self
736 .db
737 .prepare(
738 "INSERT INTO sandbox_months (workspace, month, seconds) VALUES (?1, ?2, ?3)
739 ON CONFLICT (workspace, month) DO UPDATE SET seconds = seconds + ?3
740 RETURNING seconds",
741 )
742 .bind(&[workspace.as_str().into(), month.into(), (seconds as f64).into()])?
743 .first::<Used>(None)
744 .await?
745 .map_or(seconds, |used| used.seconds);
746 let billable = sandbox_billable(after - seconds, seconds);
Prices keep themselves current with what g1t pays747 // From the price book, which follows what Cloudflare bills g1t.
748 let (cost_per_second, price_per_second) = self.price("sandbox_second").await?.unwrap_or((
749 sandbox_allowance::COST_MICROS_PER_SECOND as f64,
750 sandbox_allowance::MICROS_PER_SECOND as f64,
751 ));
Billing accounts, terms and enterprises; g1t is no longer free752 let (charge, terms_note) = self.charged(&workspace, (billable as f64 * price_per_second).ceil() as i64).await?;
Every sandbox is metered by the second753 let mut description = format!("{}: {} of sandbox time", a.description, duration(seconds));
754 if billable < seconds {
755 description.push_str(if billable == 0 {
756 ", within the month's free minutes"
757 } else {
758 ", partly within the month's free minutes"
759 });
760 }
Billing accounts, terms and enterprises; g1t is no longer free761 if billable > 0 {
762 description.push_str(&terms_note);
Every sandbox is metered by the second763 }
764 self.db
765 .batch(vec![
766 self.db
767 .prepare(
768 "INSERT INTO ledger
769 (id, workspace, kind, amount_micros, description, repo, task,
770 cost_micros, reference, created_at, billed_to)
771 VALUES (?, ?, 'usage', ?, ?, ?, 'sandbox', ?, ?, ?, 'g1t')",
772 )
773 .bind(&[
774 new_id("led", now).into(),
775 workspace.as_str().into(),
776 (-(charge as f64)).into(),
777 description.as_str().into(),
778 optional(a.repo.as_deref()),
Prices keep themselves current with what g1t pays779 (seconds as f64 * cost_per_second).ceil().into(),
Every sandbox is metered by the second780 a.reference.as_str().into(),
781 timestamp.as_str().into(),
782 ])?,
783 self.db
784 .prepare(
785 "INSERT INTO accounts (workspace, balance_micros, created_at)
786 VALUES (?1, ?2, ?3)
787 ON CONFLICT (workspace) DO UPDATE SET balance_micros = balance_micros + ?2",
788 )
789 .bind(&[
790 workspace.as_str().into(),
791 (-(charge as f64)).into(),
792 timestamp.as_str().into(),
793 ])?,
794 ])
795 .await?;
796 Ok(Outcome::Ok(true))
797 }
798}
799
800/// Of `seconds` used after `before` this month, how many are past the
801/// free minutes.
802fn sandbox_billable(before: i64, seconds: i64) -> i64 {
803 let free_left = (sandbox_allowance::FREE_SECONDS - before).max(0);
804 (seconds - free_left).max(0)
805}
806
807/// `1h 2m`, `3m 12s` or `40s`.
808fn duration(seconds: i64) -> String {
809 let (h, m, s) = (seconds / 3600, seconds % 3600 / 60, seconds % 60);
810 if h > 0 {
811 format!("{h}h {m}m")
812 } else if m > 0 {
813 format!("{m}m {s}s")
814 } else {
815 format!("{s}s")
816 }
817}
818
Billing accounts, terms and enterprises; g1t is no longer free819impl Billing {
820 /// What a workspace is charged for something that would be `base`:
821 /// nothing while g1t is free, or as its account's terms say. With a
822 /// note for the statement when it differs.
823 pub(crate) async fn charged(&self, workspace: &str, base: i64) -> Result<(i64, String)> {
824 if self.free {
825 return Ok((0, " (free while g1t is being built out)".to_owned()));
826 }
827 let terms = self.terms_of(workspace).await?;
828 let charge = terms.apply(base);
829 let note = match terms.kind {
830 TermsKind::Comped => " (comped)".to_owned(),
831 TermsKind::Custom if terms.discount_percent > 0 && base > 0 => format!(" ({}% off)", terms.discount_percent),
832 _ => String::new(),
833 };
834 Ok((charge, note))
835 }
836}
837
Agents as a team: lifecycle, merge queue, billing and a new shell838fn members_only<T>() -> Outcome<T> {
839 Outcome::fail(
840 FailureCode::Forbidden,
841 "Only members can see a workspace's billing.",
842 )
843}
844
Prices keep themselves current with what g1t pays845impl Billing {
846 fn from_env(env: &Env) -> Result<Self> {
847 Ok(Billing {
848 db: env.d1("DB")?,
849 stripe: env
850 .secret("STRIPE_SECRET_KEY")
851 .ok()
852 .map(|key| key.to_string())
853 .filter(|key| !key.is_empty())
854 .map(Stripe::new),
855 margin_percent: env
856 .var("MARGIN_PERCENT")
857 .ok()
858 .and_then(|percent| percent.to_string().parse().ok())
859 .unwrap_or(20),
860 orchestration_fee_micros: env
861 .var("ORCHESTRATION_FEE_MICROS")
862 .ok()
863 .and_then(|fee| fee.to_string().parse().ok())
864 .unwrap_or(100_000),
865 free: env.var("FREE_WHILE_BUILDING").is_ok_and(|v| v.to_string() == "true"),
866 ceilings: limits::Ceilings::from_env(&env),
Billing accounts, terms and enterprises; g1t is no longer free867 prepaid_only: env.var("PREPAID_ONLY").is_ok_and(|v| v.to_string() == "true"),
Prices keep themselves current with what g1t pays868 deployments_monthly_cents: env
869 .var("DEPLOYMENTS_MONTHLY_CENTS")
870 .ok()
871 .and_then(|cents| cents.to_string().parse().ok())
872 .unwrap_or(500),
873 trial: {
874 let number = |name: &str| env.var(name).ok().and_then(|v| v.to_string().parse::<i64>().ok());
875 match (
876 number("TRIAL_WORKSPACE_MICROS"),
877 number("TRIAL_TOTAL_MICROS"),
878 env.var("TRIAL_UNTIL").ok().map(|v| v.to_string()),
879 ) {
880 (Some(per_workspace_micros), Some(total_micros), Some(until))
881 if per_workspace_micros > 0 && !until.is_empty() =>
882 {
883 Some(TrialConfig {
884 per_workspace_micros,
885 total_micros,
886 until,
887 })
888 }
889 _ => None,
890 }
891 },
892 })
893 }
894}
895
896#[event(scheduled)]
897async fn scheduled(event: ScheduledEvent, env: Env, _ctx: ScheduleContext) {
898 let Ok(billing) = Billing::from_env(&env) else {
899 return;
900 };
901 let keeper = keeper::Keeper::from_env(&env);
902 if let Err(error) = billing.settle_runs(&keeper).await {
903 worker::console_error!("settling runs failed: {error}");
904 }
Billing accounts, terms and enterprises; g1t is no longer free905 if let Err(error) = billing.autopay().await {
906 worker::console_error!("paying at the limit failed: {error}");
907 }
The keeper reads Cloudflare as it really answers908 // Once a day, and at once if the costs were never checked: check every
909 // cost against what Cloudflare billed.
910 if event.cron() == keeper::DAILY || billing.never_checked().await.unwrap_or(false) {
Prices keep themselves current with what g1t pays911 if let Err(error) = billing.reconcile(&keeper).await {
912 worker::console_error!("checking costs against Cloudflare failed: {error}");
913 }
914 }
915}
916
Agents as a team: lifecycle, merge queue, billing and a new shell917#[event(fetch)]
918async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> {
919 let Some(method) = rpc_method(&request) else {
920 return Response::error("Not found", 404);
921 };
922 let body: serde_json::Value = request.json().await?;
Prices keep themselves current with what g1t pays923 let billing = Billing::from_env(&env)?;
Agents as a team: lifecycle, merge queue, billing and a new shell924 match method.as_str() {
925 "status" => reply(&billing.status()),
926 "account" => reply(&billing.account(args(body)?).await?),
927 "ledger" => reply(&billing.ledger(args(body)?).await?),
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request928 "usage" => reply(&billing.usage(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell929 "checkout" => reply(&billing.checkout(args(body)?).await?),
930 "confirm" => reply(&billing.confirm(args(body)?).await?),
931 "can_start" => reply(&billing.can_start(args(body)?).await?),
A free allowance on g1t's models, so anyone can try its agents932 "trial" => reply(&billing.trial(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell933 "start_run" => reply(&billing.start_run(args(body)?).await?),
934 "finish_run" => reply(&billing.finish_run(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan935 "features" => reply(&billing.features(args(body)?).await?),
936 "subscribe" => reply(&billing.subscribe(args(body)?).await?),
937 "confirm_subscription" => reply(&billing.confirm_subscription(args(body)?).await?),
938 "cancel_subscription" => reply(&billing.cancel_subscription(args(body)?).await?),
939 "has_feature" => reply(&billing.has_feature(args(body)?).await?),
940 "charge_feature" => reply(&billing.charge_feature(args(body)?).await?),
Every sandbox is metered by the second941 "record_sandbox" => reply(&billing.record_sandbox(args(body)?).await?),
Usage limits: unpaid usage can only go so far942 "limit" => reply(&billing.limit(args(body)?).await?),
943 "check_limit" => reply(&billing.check_limit(args(body)?).await?),
944 "set_spend_limit" => reply(&billing.set_spend_limit(args(body)?).await?),
Prices keep themselves current with what g1t pays945 "prices" => reply(&billing.prices().await?),
946 "note_pending" => reply(&billing.note_pending(args(body)?).await?),
Billing accounts, terms and enterprises; g1t is no longer free947 "admin_accounts" => reply(&billing.admin_accounts(args(body)?).await?),
948 "admin_account" => reply(&billing.admin_account(args(body)?).await?),
949 "admin_set_terms" => reply(&billing.admin_set_terms(args(body)?).await?),
950 "admin_create_enterprise" => reply(&billing.admin_create_enterprise(args(body)?).await?),
951 "admin_attach" => reply(&billing.admin_attach(args(body)?).await?),
952 "admin_credit" => reply(&billing.admin_credit(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell953 _ => Response::error("Unknown method", 404),
954 }
955}
956
957#[cfg(test)]
958mod tests {
959 use super::*;
960
961 #[test]
962 fn a_run_is_charged_its_cost_plus_the_margin() {
963 // $0.05 at 20% is six cents.
964 assert_eq!(charge_micros(0.05, 20), 60_000);
965 assert_eq!(charge_micros(1.0, 20), 1_200_000);
966 assert_eq!(charge_micros(0.05, 0), 50_000);
967 }
968
969 #[test]
970 fn fractions_of_a_millionth_round_up_and_nothing_costs_less_than_nothing() {
971 assert_eq!(charge_micros(0.000_000_4, 20), 2);
972 assert_eq!(charge_micros(0.0, 20), 0);
973 assert_eq!(charge_micros(-3.0, 20), 0);
974 }
975
976 #[test]
Every sandbox is metered by the second977 fn sandbox_seconds_are_charged_only_past_the_free_minutes() {
978 let free = sandbox_allowance::FREE_SECONDS;
979 assert_eq!(sandbox_billable(0, 600), 0);
980 assert_eq!(sandbox_billable(free - 100, 600), 500);
981 assert_eq!(sandbox_billable(free + 5, 600), 600);
982 }
983
984 #[test]
985 fn durations_read_plainly() {
986 assert_eq!(duration(40), "40s");
987 assert_eq!(duration(192), "3m 12s");
988 assert_eq!(duration(3720), "1h 2m");
989 }
990
991 #[test]
Agents as a team: lifecycle, merge queue, billing and a new shell992 fn an_absurd_cost_is_capped() {
993 assert_eq!(charge_micros(1e9, 20), 120 * MICROS_PER_DOLLAR);
994 }
995}