g1t/services/billing/src/lib.rs

763 lines28,148 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
Paid features: a workspace turns on Deployments with a monthly plan19mod features;
Agents as a team: lifecycle, merge queue, billing and a new shell20mod stripe;
21
22use g1t_contracts::billing::*;
23use g1t_contracts::time::rfc3339;
24use g1t_contracts::{FailureCode, Outcome, Role, new_id};
25use g1t_kit::{args, now_ms, reply, rpc_method};
26use serde::Deserialize;
27use sha2::{Digest, Sha256};
28use worker::wasm_bindgen::JsValue;
29use worker::{Context, D1Database, Env, Request, Response, Result, event};
30
31use stripe::Stripe;
32
33const MIN_TOP_UP_CENTS: u32 = 500;
34const MAX_TOP_UP_CENTS: u32 = 50_000;
35const LEDGER_PAGE: u32 = 100;
36/// A run's reported cost is believed up to this much. A sandbox cannot
37/// spend more in the time it has, so anything above is a fault.
38const MAX_RUN_COST_USD: f64 = 100.0;
39
40/// What a run is charged: its cost plus the margin, rounded up to a whole
41/// millionth of a dollar.
42pub fn charge_micros(cost_usd: f64, margin_percent: u32) -> i64 {
43 let cost_micros = (cost_usd.clamp(0.0, MAX_RUN_COST_USD) * MICROS_PER_DOLLAR as f64).ceil();
44 (cost_micros * f64::from(100 + margin_percent) / 100.0).ceil() as i64
45}
46
47fn hash(token: &str) -> String {
48 hex::encode(Sha256::digest(token.as_bytes()))
49}
50
51fn optional(value: Option<&str>) -> JsValue {
52 value.map_or(JsValue::NULL, JsValue::from)
53}
54
55#[derive(Deserialize)]
56struct AccountRow {
57 balance_micros: i64,
58 customer_id: Option<String>,
59}
60
61#[derive(Deserialize)]
62struct LedgerRow {
63 id: String,
64 kind: EntryKind,
65 amount_micros: i64,
66 description: String,
67 repo: Option<String>,
68 number: Option<u32>,
69 task: Option<String>,
70 model: Option<String>,
71 created_by: Option<String>,
72 created_at: String,
Integrations: your own model provider, alerts that open issues, tickets agents read73 billed_to: Option<String>,
Agents as a team: lifecycle, merge queue, billing and a new shell74}
75
76impl From<LedgerRow> for LedgerEntry {
77 fn from(row: LedgerRow) -> Self {
78 LedgerEntry {
79 id: row.id,
80 kind: row.kind,
81 amount_micros: row.amount_micros,
82 description: row.description,
83 repo: row.repo,
84 number: row.number,
85 task: row.task,
86 model: row.model,
Integrations: your own model provider, alerts that open issues, tickets agents read87 billed_to: row.billed_to.unwrap_or_else(|| "g1t".to_owned()),
Agents as a team: lifecycle, merge queue, billing and a new shell88 created_by: row.created_by,
89 created_at: row.created_at,
90 }
91 }
92}
93
94#[derive(Deserialize)]
95struct RunRow {
96 workspace: String,
97 repo: String,
98 number: u32,
99 task: String,
100 model: String,
101 token_hash: String,
Integrations: your own model provider, alerts that open issues, tickets agents read102 billed_to: Option<String>,
103}
104
105impl RunRow {
106 fn own_provider(&self) -> bool {
107 self.billed_to.as_deref() == Some("workspace")
108 }
Agents as a team: lifecycle, merge queue, billing and a new shell109}
110
111#[derive(Deserialize)]
112struct CheckoutRow {
113 workspace: String,
114 created_by: String,
115}
116
117/// A row an `UPDATE … RETURNING` touched.
118#[derive(Deserialize)]
119struct Touched {
120 #[allow(dead_code)]
121 id: String,
122}
123
124struct Billing {
125 db: D1Database,
126 /// Absent when no card processor is configured.
127 stripe: Option<Stripe>,
128 margin_percent: u32,
Integrations: your own model provider, alerts that open issues, tickets agents read129 /// Charged for a run on the workspace's own model provider.
130 orchestration_fee_micros: i64,
Free while g1t is being built out; agents can check out their own forks131 /// While g1t is being built out, nothing is charged (`FREE_WHILE_BUILDING`).
132 free: bool,
A free allowance on g1t's models, so anyone can try its agents133 /// The free allowance on g1t's hosted models, when there is one.
134 trial: Option<TrialConfig>,
Paid features: a workspace turns on Deployments with a monthly plan135 /// The Deployments plan's monthly price (`DEPLOYMENTS_MONTHLY_CENTS`).
136 deployments_monthly_cents: u32,
A free allowance on g1t's models, so anyone can try its agents137}
138
139/// `TRIAL_WORKSPACE_MICROS`, `TRIAL_TOTAL_MICROS` and `TRIAL_UNTIL`.
140struct TrialConfig {
141 per_workspace_micros: i64,
142 total_micros: i64,
143 /// RFC 3339, in UTC.
144 until: String,
145}
146
147#[derive(serde::Deserialize)]
148struct Sum {
149 micros: Option<i64>,
Agents as a team: lifecycle, merge queue, billing and a new shell150}
151
152impl Billing {
153 fn status(&self) -> Status {
154 Status {
155 enabled: self.stripe.is_some(),
156 live: self.stripe.as_ref().is_some_and(Stripe::live),
Free while g1t is being built out; agents can check out their own forks157 free: self.free,
Agents as a team: lifecycle, merge queue, billing and a new shell158 }
159 }
160
161 async fn row(&self, workspace: &str) -> Result<Option<AccountRow>> {
162 self.db
163 .prepare("SELECT balance_micros, customer_id FROM accounts WHERE workspace = ?")
164 .bind(&[workspace.into()])?
165 .first::<AccountRow>(None)
166 .await
167 }
168
169 async fn standing(&self, workspace: &str) -> Result<Account> {
170 Ok(Account {
171 workspace: workspace.to_owned(),
172 balance_micros: self
173 .row(workspace)
174 .await?
175 .map_or(0, |row| row.balance_micros),
176 status: self.status(),
177 margin_percent: self.margin_percent,
Integrations: your own model provider, alerts that open issues, tickets agents read178 orchestration_fee_micros: self.orchestration_fee_micros,
Agents as a team: lifecycle, merge queue, billing and a new shell179 })
180 }
181
182 /// Adds a ledger entry and moves the balance by the same amount, as
183 /// one write.
184 #[allow(clippy::too_many_arguments)]
185 async fn enter(
186 &self,
187 workspace: &str,
188 kind: EntryKind,
189 amount_micros: i64,
190 description: &str,
191 reference: &str,
192 run: Option<&RunRow>,
193 cost_micros: Option<i64>,
194 created_by: Option<&str>,
195 customer: Option<&str>,
196 ) -> Result<()> {
197 let now = now_ms();
198 let timestamp = rfc3339(now);
199 let kind = match kind {
200 EntryKind::TopUp => "top_up",
201 EntryKind::Usage => "usage",
202 };
203 self.db
204 .batch(vec![
205 self.db
206 .prepare(
207 "INSERT INTO ledger
208 (id, workspace, kind, amount_micros, description, repo, number, task,
Integrations: your own model provider, alerts that open issues, tickets agents read209 model, cost_micros, reference, created_by, created_at, billed_to)
210 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
Agents as a team: lifecycle, merge queue, billing and a new shell211 )
212 .bind(&[
213 new_id("led", now).into(),
214 workspace.into(),
215 kind.into(),
216 // D1 takes numbers as doubles, which hold every
217 // amount this service will see exactly.
218 (amount_micros as f64).into(),
219 description.into(),
220 optional(run.map(|run| run.repo.as_str())),
221 run.map_or(JsValue::NULL, |run| run.number.into()),
222 optional(run.map(|run| run.task.as_str())),
223 optional(run.map(|run| run.model.as_str())),
224 cost_micros.map_or(JsValue::NULL, |cost| (cost as f64).into()),
225 reference.into(),
226 optional(created_by),
227 timestamp.as_str().into(),
Integrations: your own model provider, alerts that open issues, tickets agents read228 run.map_or("g1t", |run| if run.own_provider() { "workspace" } else { "g1t" }).into(),
Agents as a team: lifecycle, merge queue, billing and a new shell229 ])?,
230 self.db
231 .prepare(
232 "INSERT INTO accounts (workspace, balance_micros, customer_id, created_at)
233 VALUES (?1, ?2, ?3, ?4)
234 ON CONFLICT (workspace) DO UPDATE SET
235 balance_micros = balance_micros + ?2,
236 customer_id = COALESCE(?3, customer_id)",
237 )
238 .bind(&[
239 workspace.into(),
240 (amount_micros as f64).into(),
241 optional(customer),
242 timestamp.as_str().into(),
243 ])?,
244 ])
245 .await?;
246 Ok(())
247 }
248
249 async fn account(&self, a: AccountArgs) -> Result<Outcome<Account>> {
250 let workspace = a.workspace.to_lowercase();
251 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
252 return Ok(members_only());
253 }
254 Ok(Outcome::Ok(self.standing(&workspace).await?))
255 }
256
257 async fn ledger(&self, a: AccountArgs) -> Result<Outcome<Vec<LedgerEntry>>> {
258 let workspace = a.workspace.to_lowercase();
259 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
260 return Ok(members_only());
261 }
262 let rows = self
263 .db
264 .prepare("SELECT * FROM ledger WHERE workspace = ? ORDER BY id DESC LIMIT ?")
265 .bind(&[workspace.into(), LEDGER_PAGE.into()])?
266 .all()
267 .await?
268 .results::<LedgerRow>()?;
269 Ok(Outcome::Ok(
270 rows.into_iter().map(LedgerEntry::from).collect(),
271 ))
272 }
273
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request274 async fn usage(&self, a: UsageArgs) -> Result<Outcome<Usage>> {
275 let workspace = a.workspace.to_lowercase();
276 if !a.viewer.is_some_and(|viewer| viewer.is_member(&workspace)) {
277 return Ok(members_only());
278 }
279 #[derive(serde::Deserialize)]
280 struct SliceRow {
281 key: Option<String>,
282 micros: Option<i64>,
283 runs: Option<u32>,
284 }
Usage while free is shown at cost; agents get rustfmt and clippy285 // While nothing is charged, what was used is what there is to show.
286 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 request287 let slices = |key: &str, limit: u32| {
288 format!(
Usage while free is shown at cost; agents get rustfmt and clippy289 "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 request290 WHERE workspace = ?1 AND kind = 'usage' AND created_at >= ?2
291 GROUP BY 1 ORDER BY micros DESC LIMIT {limit}"
292 )
293 };
294 let query = |sql: String| {
295 let db = &self.db;
296 let workspace = workspace.clone();
297 let since = a.since.clone();
298 async move {
299 let rows = db
300 .prepare(sql)
301 .bind(&[workspace.into(), since.into()])?
302 .all()
303 .await?
304 .results::<SliceRow>()?;
305 Ok::<Vec<UsageSlice>, worker::Error>(
306 rows.into_iter()
307 .map(|row| UsageSlice {
308 key: row.key.unwrap_or_else(|| "other".to_owned()),
309 micros: row.micros.unwrap_or_default(),
310 runs: row.runs.unwrap_or_default(),
311 })
312 .collect(),
313 )
314 }
315 };
316 #[derive(serde::Deserialize)]
317 struct Totals {
318 spent: Option<i64>,
319 cost: Option<i64>,
Integrations: your own model provider, alerts that open issues, tickets agents read320 provider: Option<i64>,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request321 runs: Option<u32>,
322 added: Option<i64>,
323 }
324 let totals = self
325 .db
326 .prepare(
327 "SELECT
328 -SUM(CASE WHEN kind = 'usage' THEN amount_micros END) AS spent,
Integrations: your own model provider, alerts that open issues, tickets agents read329 SUM(CASE WHEN kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' THEN cost_micros END) AS cost,
330 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 request331 SUM(CASE WHEN kind = 'usage' THEN 1 ELSE 0 END) AS runs,
332 SUM(CASE WHEN kind = 'top_up' THEN amount_micros END) AS added
333 FROM ledger WHERE workspace = ?1 AND created_at >= ?2",
334 )
335 .bind(&[workspace.as_str().into(), a.since.as_str().into()])?
336 .first::<Totals>(None)
337 .await?;
338 let totals = totals.unwrap_or(Totals {
339 spent: None,
340 cost: None,
Integrations: your own model provider, alerts that open issues, tickets agents read341 provider: None,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request342 runs: None,
343 added: None,
344 });
345 Ok(Outcome::Ok(Usage {
346 spent_micros: totals.spent.unwrap_or_default(),
347 cost_micros: totals.cost.unwrap_or_default(),
Integrations: your own model provider, alerts that open issues, tickets agents read348 provider_micros: totals.provider.unwrap_or_default(),
Usage while free is shown at cost; agents get rustfmt and clippy349 used_micros: totals.cost.unwrap_or_default() + totals.provider.unwrap_or_default(),
350 free: self.free,
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request351 runs: totals.runs.unwrap_or_default(),
352 added_micros: totals.added.unwrap_or_default(),
353 by_day: query(slices("substr(created_at, 1, 10) || '/' || COALESCE(task, 'other')", 400)).await?,
354 by_task: query(slices("task", 20)).await?,
355 by_repo: query(slices("repo", 20)).await?,
356 by_pull: query(slices("repo || '#' || number", 10)).await?,
357 by_model: query(slices("model", 10)).await?,
358 since: a.since,
359 }))
360 }
361
Agents as a team: lifecycle, merge queue, billing and a new shell362 async fn checkout(&self, a: CheckoutArgs) -> Result<Outcome<Checkout>> {
363 let workspace = a.workspace.to_lowercase();
364 if a.actor.role_in(&workspace) != Some(Role::Owner) {
365 return Ok(Outcome::fail(
366 FailureCode::Forbidden,
367 "Only an owner can add credit to a workspace.",
368 ));
369 }
370 let Some(stripe) = &self.stripe else {
371 return Ok(Outcome::fail(
372 FailureCode::Conflict,
373 "Payments are not set up on this g1t yet.",
374 ));
375 };
376 if !(MIN_TOP_UP_CENTS..=MAX_TOP_UP_CENTS).contains(&a.amount_cents) {
377 return Ok(Outcome::fail(
378 FailureCode::Invalid,
379 format!(
380 "Add between ${} and ${} at a time.",
381 MIN_TOP_UP_CENTS / 100,
382 MAX_TOP_UP_CENTS / 100
383 ),
384 ));
385 }
386 let customer = self.row(&workspace).await?.and_then(|row| row.customer_id);
387 let session = stripe
388 .start_checkout(
389 &workspace,
390 a.amount_cents,
391 customer.as_deref(),
392 &a.return_url,
393 )
394 .await?;
395 let Some(url) = session.url else {
396 return Err(worker::Error::RustError(
397 "the card processor returned no payment page".into(),
398 ));
399 };
400 self.db
401 .prepare(
402 "INSERT INTO checkouts (id, workspace, amount_cents, created_by, created_at)
403 VALUES (?, ?, ?, ?, ?)",
404 )
405 .bind(&[
406 session.id.into(),
407 workspace.into(),
408 a.amount_cents.into(),
409 a.actor.username.into(),
410 rfc3339(now_ms()).into(),
411 ])?
412 .run()
413 .await?;
414 Ok(Outcome::Ok(Checkout { url }))
415 }
416
417 /// Credits a payment if the processor says it was made and it has not
418 /// been credited before. The amount credited is what the processor
419 /// says was paid, not what anyone here remembers asking for.
420 async fn confirm(&self, a: ConfirmArgs) -> 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 let (Some(stripe), Some(checkout)) = (
426 &self.stripe,
427 self.db
428 .prepare(
429 "SELECT workspace, created_by FROM checkouts
430 WHERE id = ? AND workspace = ? AND status = 'open'",
431 )
432 .bind(&[a.session.as_str().into(), workspace.as_str().into()])?
433 .first::<CheckoutRow>(None)
434 .await?,
435 ) else {
436 // Unknown, someone else's, or already credited: nothing to do.
437 return Ok(Outcome::Ok(self.standing(&workspace).await?));
438 };
439 let session = stripe.session(&a.session).await?;
440 let paid = session
441 .amount_total
442 .filter(|_| session.payment_status == "paid");
443 if let Some(cents) = paid {
444 // Only whoever flips it from open to paid enters the credit.
445 let claimed = self
446 .db
447 .prepare(
448 "UPDATE checkouts SET status = 'paid' WHERE id = ? AND status = 'open'
449 RETURNING id",
450 )
451 .bind(&[a.session.as_str().into()])?
452 .first::<Touched>(None)
453 .await?;
454 if claimed.is_some() {
455 self.enter(
456 &checkout.workspace,
457 EntryKind::TopUp,
458 i64::from(cents) * MICROS_PER_DOLLAR / 100,
459 "Credit added by card",
460 &session.id,
461 None,
462 None,
463 Some(&checkout.created_by),
464 session.customer.as_deref(),
465 )
466 .await?;
467 }
468 }
469 Ok(Outcome::Ok(self.standing(&workspace).await?))
470 }
471
472 /// A refusal if the workspace has no credit to start an agent with.
473 async fn out_of_credit<T>(&self, workspace: &str) -> Result<Option<Outcome<T>>> {
Free while g1t is being built out; agents can check out their own forks474 // While g1t is being built out, no one needs credit.
475 if self.free {
476 return Ok(None);
477 }
Agents as a team: lifecycle, merge queue, billing and a new shell478 let balance = self
479 .row(workspace)
480 .await?
481 .map_or(0, |row| row.balance_micros);
482 Ok((balance <= 0).then(|| {
483 Outcome::fail(
484 FailureCode::PaymentRequired,
485 format!(
486 "The {workspace} workspace has no agent credit. An owner can add some under Billing on the workspace's page."
487 ),
488 )
489 }))
490 }
491
A free allowance on g1t's models, so anyone can try its agents492 /// A workspace's free allowance on g1t's hosted models: what its runs
493 /// there have cost against its share, and the pool everyone draws on.
494 async fn trial(&self, a: TrialArgs) -> Result<Trial> {
495 let workspace = a.workspace.to_lowercase();
496 let Some(config) = &self.trial else {
497 return Ok(Trial {
498 open: false,
499 used_micros: 0,
500 limit_micros: 0,
501 ends_at: None,
502 reason: Some("off".to_owned()),
503 });
504 };
505 let used = self
506 .db
507 .prepare(
508 "SELECT SUM(cost_micros) AS micros FROM ledger
509 WHERE kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' AND workspace = ?",
510 )
511 .bind(&[workspace.as_str().into()])?
512 .first::<Sum>(None)
513 .await?
514 .and_then(|sum| sum.micros)
515 .unwrap_or_default();
516 // Everyone's, but for the workspaces open to hosted models anyway.
517 let exempt: Vec<String> = a.exempt.iter().map(|name| name.trim().to_lowercase()).collect();
518 let marks = vec!["?"; exempt.len().max(1)].join(", ");
519 let mut values: Vec<JsValue> = exempt.iter().map(|name| JsValue::from(name.as_str())).collect();
520 if values.is_empty() {
521 values.push(JsValue::from(""));
522 }
523 let pooled = self
524 .db
525 .prepare(format!(
526 "SELECT SUM(cost_micros) AS micros FROM ledger
527 WHERE kind = 'usage' AND COALESCE(billed_to, 'g1t') = 'g1t' AND workspace NOT IN ({marks})"
528 ))
529 .bind(&values)?
530 .first::<Sum>(None)
531 .await?
532 .and_then(|sum| sum.micros)
533 .unwrap_or_default();
534 let reason = if rfc3339(now_ms()) >= config.until {
535 Some("ended")
536 } else if used >= config.per_workspace_micros {
537 Some("used")
538 } else if pooled >= config.total_micros {
539 Some("pool")
540 } else {
541 None
542 };
543 Ok(Trial {
544 open: reason.is_none(),
545 used_micros: used,
546 limit_micros: config.per_workspace_micros,
547 ends_at: Some(config.until.clone()),
548 reason: reason.map(str::to_owned),
549 })
550 }
551
Agents as a team: lifecycle, merge queue, billing and a new shell552 async fn can_start(&self, a: CanStartArgs) -> Result<Outcome<bool>> {
553 if self.stripe.is_none() {
554 return Ok(Outcome::Ok(true));
555 }
556 Ok(self
557 .out_of_credit(&a.workspace.to_lowercase())
558 .await?
559 .unwrap_or(Outcome::Ok(true)))
560 }
561
562 async fn start_run(&self, a: StartRunArgs) -> Result<Outcome<Option<RunTicket>>> {
563 if self.stripe.is_none() {
564 return Ok(Outcome::Ok(None));
565 }
566 let workspace = a.workspace.to_lowercase();
567 if let Some(refused) = self.out_of_credit(&workspace).await? {
568 return Ok(refused);
569 }
570 let now = now_ms();
571 let run_id = new_id("run", now);
572 let mut bytes = [0u8; 32];
573 getrandom::getrandom(&mut bytes).expect("no source of randomness");
574 let token = hex::encode(bytes);
575 self.db
576 .prepare(
Integrations: your own model provider, alerts that open issues, tickets agents read577 "INSERT INTO runs (id, workspace, repo, number, task, model, token_hash, created_at, billed_to)
578 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
Agents as a team: lifecycle, merge queue, billing and a new shell579 )
580 .bind(&[
581 run_id.as_str().into(),
582 workspace.into(),
583 format!("{}/{}", a.repo.namespace, a.repo.name).into(),
584 a.number.into(),
585 a.task.into(),
586 a.model.into(),
587 hash(&token).into(),
588 rfc3339(now).into(),
Integrations: your own model provider, alerts that open issues, tickets agents read589 if a.billed_to == "workspace" { "workspace" } else { "g1t" }.into(),
Agents as a team: lifecycle, merge queue, billing and a new shell590 ])?
591 .run()
592 .await?;
593 Ok(Outcome::Ok(Some(RunTicket { run_id, token })))
594 }
595
596 async fn finish_run(&self, a: FinishRunArgs) -> Result<Outcome<bool>> {
597 let run = self
598 .db
599 .prepare(
Integrations: your own model provider, alerts that open issues, tickets agents read600 "SELECT workspace, repo, number, task, model, token_hash, billed_to FROM runs
Agents as a team: lifecycle, merge queue, billing and a new shell601 WHERE id = ? AND finished_at IS NULL",
602 )
603 .bind(&[a.run_id.as_str().into()])?
604 .first::<RunRow>(None)
605 .await?;
606 let Some(run) = run.filter(|run| run.token_hash == hash(&a.token)) else {
607 return Ok(Outcome::fail(FailureCode::NotFound, "Run not found."));
608 };
609 if !a.cost_usd.is_finite() || a.cost_usd < 0.0 {
610 return Ok(Outcome::fail(FailureCode::Invalid, "That is not a cost."));
611 }
612 // Only whoever closes the run charges for it.
613 let claimed = self
614 .db
615 .prepare(
616 "UPDATE runs SET finished_at = ? WHERE id = ? AND finished_at IS NULL RETURNING id",
617 )
618 .bind(&[rfc3339(now_ms()).into(), a.run_id.as_str().into()])?
619 .first::<Touched>(None)
620 .await?;
621 if claimed.is_none() {
622 return Ok(Outcome::Ok(false));
623 }
Integrations: your own model provider, alerts that open issues, tickets agents read624 // On the workspace's own provider, the model was paid for there:
625 // g1t charges its fee, and keeps the provider's cost to show.
Free while g1t is being built out; agents can check out their own forks626 let charge = if self.free {
627 // Recorded, with what it cost, but not charged.
628 0
629 } else if run.own_provider() {
Integrations: your own model provider, alerts that open issues, tickets agents read630 self.orchestration_fee_micros
631 } else {
632 charge_micros(a.cost_usd, self.margin_percent)
633 };
634 let mut description = match run.task.as_str() {
Agents as a team: lifecycle, merge queue, billing and a new shell635 "plan" => format!("Planning for {}", run.repo),
636 "review" => format!("Review of {}#{}", run.repo, run.number),
637 "update" => format!("Catching up {}#{}", run.repo, run.number),
638 _ => format!("Work on {}#{}", run.repo, run.number),
639 };
Integrations: your own model provider, alerts that open issues, tickets agents read640 if run.own_provider() {
641 description.push_str(", on your own model provider");
642 }
Free while g1t is being built out; agents can check out their own forks643 if self.free {
644 description.push_str(" (free while g1t is being built out)");
645 }
Agents as a team: lifecycle, merge queue, billing and a new shell646 self.enter(
647 &run.workspace,
648 EntryKind::Usage,
649 -charge,
650 &description,
651 &a.run_id,
652 Some(&run),
653 Some(charge_micros(a.cost_usd, 0)),
654 None,
655 None,
656 )
657 .await?;
658 Ok(Outcome::Ok(true))
659 }
660}
661
662fn members_only<T>() -> Outcome<T> {
663 Outcome::fail(
664 FailureCode::Forbidden,
665 "Only members can see a workspace's billing.",
666 )
667}
668
669#[event(fetch)]
670async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> {
671 let Some(method) = rpc_method(&request) else {
672 return Response::error("Not found", 404);
673 };
674 let body: serde_json::Value = request.json().await?;
675 let billing = Billing {
676 db: env.d1("DB")?,
677 stripe: env
678 .secret("STRIPE_SECRET_KEY")
679 .ok()
680 .map(|key| key.to_string())
681 .filter(|key| !key.is_empty())
682 .map(Stripe::new),
683 margin_percent: env
684 .var("MARGIN_PERCENT")
685 .ok()
686 .and_then(|percent| percent.to_string().parse().ok())
687 .unwrap_or(20),
Integrations: your own model provider, alerts that open issues, tickets agents read688 orchestration_fee_micros: env
689 .var("ORCHESTRATION_FEE_MICROS")
690 .ok()
691 .and_then(|fee| fee.to_string().parse().ok())
692 .unwrap_or(100_000),
Free while g1t is being built out; agents can check out their own forks693 free: env.var("FREE_WHILE_BUILDING").is_ok_and(|v| v.to_string() == "true"),
Paid features: a workspace turns on Deployments with a monthly plan694 deployments_monthly_cents: env
695 .var("DEPLOYMENTS_MONTHLY_CENTS")
696 .ok()
697 .and_then(|cents| cents.to_string().parse().ok())
698 .unwrap_or(500),
A free allowance on g1t's models, so anyone can try its agents699 trial: {
700 let number = |name: &str| env.var(name).ok().and_then(|v| v.to_string().parse::<i64>().ok());
701 match (
702 number("TRIAL_WORKSPACE_MICROS"),
703 number("TRIAL_TOTAL_MICROS"),
704 env.var("TRIAL_UNTIL").ok().map(|v| v.to_string()),
705 ) {
706 (Some(per_workspace_micros), Some(total_micros), Some(until))
707 if per_workspace_micros > 0 && !until.is_empty() =>
708 {
709 Some(TrialConfig {
710 per_workspace_micros,
711 total_micros,
712 until,
713 })
714 }
715 _ => None,
716 }
717 },
Agents as a team: lifecycle, merge queue, billing and a new shell718 };
719 match method.as_str() {
720 "status" => reply(&billing.status()),
721 "account" => reply(&billing.account(args(body)?).await?),
722 "ledger" => reply(&billing.ledger(args(body)?).await?),
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request723 "usage" => reply(&billing.usage(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell724 "checkout" => reply(&billing.checkout(args(body)?).await?),
725 "confirm" => reply(&billing.confirm(args(body)?).await?),
726 "can_start" => reply(&billing.can_start(args(body)?).await?),
A free allowance on g1t's models, so anyone can try its agents727 "trial" => reply(&billing.trial(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell728 "start_run" => reply(&billing.start_run(args(body)?).await?),
729 "finish_run" => reply(&billing.finish_run(args(body)?).await?),
Paid features: a workspace turns on Deployments with a monthly plan730 "features" => reply(&billing.features(args(body)?).await?),
731 "subscribe" => reply(&billing.subscribe(args(body)?).await?),
732 "confirm_subscription" => reply(&billing.confirm_subscription(args(body)?).await?),
733 "cancel_subscription" => reply(&billing.cancel_subscription(args(body)?).await?),
734 "has_feature" => reply(&billing.has_feature(args(body)?).await?),
735 "charge_feature" => reply(&billing.charge_feature(args(body)?).await?),
Agents as a team: lifecycle, merge queue, billing and a new shell736 _ => Response::error("Unknown method", 404),
737 }
738}
739
740#[cfg(test)]
741mod tests {
742 use super::*;
743
744 #[test]
745 fn a_run_is_charged_its_cost_plus_the_margin() {
746 // $0.05 at 20% is six cents.
747 assert_eq!(charge_micros(0.05, 20), 60_000);
748 assert_eq!(charge_micros(1.0, 20), 1_200_000);
749 assert_eq!(charge_micros(0.05, 0), 50_000);
750 }
751
752 #[test]
753 fn fractions_of_a_millionth_round_up_and_nothing_costs_less_than_nothing() {
754 assert_eq!(charge_micros(0.000_000_4, 20), 2);
755 assert_eq!(charge_micros(0.0, 20), 0);
756 assert_eq!(charge_micros(-3.0, 20), 0);
757 }
758
759 #[test]
760 fn an_absurd_cost_is_capped() {
761 assert_eq!(charge_micros(1e9, 20), 120 * MICROS_PER_DOLLAR);
762 }
763}