g1t/crates/contracts/src/billing.rs

277 lines9,489 bytesCodeBlame
1//! The billing service: what agents cost, charged to the workspace they
2//! worked for.
3//!
4//! A workspace buys credit and each agent run deducts what it cost, plus
5//! g1t's margin. With no credit, no agent starts. Money is held in
6//! millionths of a US dollar, so that a run costing a fraction of a cent is
7//! recorded exactly.
8//!
9//! Each `*Args` struct is the argument of the method of the same name,
10//! served at `POST /rpc/<method>`.
11
12use serde::{Deserialize, Serialize};
13
14use crate::repos::RepoPath;
15use crate::{User, Viewer};
16
17/// Millionths of a US dollar in one dollar.
18pub const MICROS_PER_DOLLAR: i64 = 1_000_000;
19
20/// Whether workspaces are charged for agents at all, and with real money.
21/// `status` takes nothing and returns this.
22#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)]
23pub struct Status {
24 /// False when no payment provider is configured: nothing is charged,
25 /// and who may run agents is decided some other way.
26 pub enabled: bool,
27 /// False while the payment provider is in its test mode, where cards
28 /// are not real.
29 pub live: bool,
30 /// True while g1t is being built out: runs are recorded, with what
31 /// they cost, but nothing is charged and no credit is needed. Not a
32 /// promise that it stays free.
33 #[serde(default)]
34 pub free: bool,
35}
36
37/// `trial`: the free allowance on g1t's hosted models for a workspace that
38/// is not otherwise open to them, so people can try g1t's agents without a
39/// key of their own. Each workspace gets a few dollars of model cost, out
40/// of one pool, until an end date. Returns `Trial`.
41#[derive(Debug, Serialize, Deserialize)]
42#[serde(rename_all = "camelCase")]
43pub struct TrialArgs {
44 pub workspace: String,
45 /// Workspaces open to hosted models anyway, whose use is not counted
46 /// against the pool.
47 #[serde(default)]
48 pub exempt: Vec<String>,
49}
50
51#[derive(Clone, Debug, Serialize, Deserialize)]
52#[serde(rename_all = "camelCase")]
53pub struct Trial {
54 /// Whether its agents may use g1t's hosted models on the allowance now.
55 pub open: bool,
56 /// What its runs on g1t's models have cost, in millionths of a dollar.
57 pub used_micros: i64,
58 pub limit_micros: i64,
59 /// RFC 3339; when the allowance ends for everyone.
60 pub ends_at: Option<String>,
61 /// Why it is closed: `off` (no allowance), `ended`, `used` (this
62 /// workspace's is spent) or `pool` (everyone's is).
63 pub reason: Option<String>,
64}
65
66/// A workspace's standing.
67#[derive(Clone, Debug, Serialize, Deserialize)]
68#[serde(rename_all = "camelCase")]
69pub struct Account {
70 pub workspace: String,
71 /// Credit left, in millionths of a dollar. Can dip below zero by the
72 /// cost of the runs that were under way when it ran out.
73 pub balance_micros: i64,
74 pub status: Status,
75 /// What is added to a run's cost, in percent.
76 pub margin_percent: u32,
77 /// What a run on the workspace's own model provider is charged: g1t's
78 /// sandbox and orchestration, with the model paid for elsewhere.
79 pub orchestration_fee_micros: i64,
80}
81
82#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
83#[serde(rename_all = "snake_case")]
84pub enum EntryKind {
85 /// Credit bought with a card.
86 TopUp,
87 /// An agent's run.
88 Usage,
89}
90
91/// One line of a workspace's statement.
92#[derive(Clone, Debug, Serialize, Deserialize)]
93#[serde(rename_all = "camelCase")]
94pub struct LedgerEntry {
95 pub id: String,
96 pub kind: EntryKind,
97 /// Positive for credit added, negative for usage.
98 pub amount_micros: i64,
99 pub description: String,
100 /// For usage: the repository and pull request the agent worked on.
101 pub repo: Option<String>,
102 pub number: Option<u32>,
103 /// For usage: `implement`, `review` or `update`.
104 pub task: Option<String>,
105 /// For usage: the model, by its public name.
106 pub model: Option<String>,
107 /// For usage: `g1t` when g1t paid the model provider, `workspace` when
108 /// the workspace's own account did and only orchestration is charged.
109 #[serde(default = "g1t")]
110 pub billed_to: String,
111 /// For a top-up: the username of whoever paid.
112 pub created_by: Option<String>,
113 /// RFC 3339.
114 pub created_at: String,
115}
116
117fn g1t() -> String {
118 "g1t".to_owned()
119}
120
121/// `account` (`Outcome<Account>`) and `ledger` (`Outcome<Vec<LedgerEntry>>`,
122/// newest first). Members of the workspace only.
123#[derive(Debug, Serialize, Deserialize)]
124pub struct AccountArgs {
125 pub workspace: String,
126 pub viewer: Viewer,
127}
128
129/// `checkout`: starts a card payment for credit. Owners of the workspace
130/// only. Returns `Outcome<Checkout>`.
131#[derive(Debug, Serialize, Deserialize)]
132#[serde(rename_all = "camelCase")]
133pub struct CheckoutArgs {
134 pub actor: User,
135 pub workspace: String,
136 /// How much credit to buy, in cents.
137 pub amount_cents: u32,
138 /// Where the payment page sends the person afterwards. The payment's
139 /// id is appended as `session`.
140 pub return_url: String,
141}
142
143#[derive(Debug, Serialize, Deserialize)]
144pub struct Checkout {
145 /// The payment page to send the person to.
146 pub url: String,
147}
148
149/// `confirm`: credits a payment once the provider says it was made. Safe
150/// to call any number of times. Returns `Outcome<Account>`.
151#[derive(Debug, Serialize, Deserialize)]
152pub struct ConfirmArgs {
153 pub workspace: String,
154 pub viewer: Viewer,
155 /// The payment's id, as returned to `return_url`.
156 pub session: String,
157}
158
159/// `can_start`: whether a workspace may start an agent now, asked before
160/// anything is opened for it. Returns `Outcome<bool>`: a failure, with the
161/// reason to show, when it has no credit.
162#[derive(Debug, Serialize, Deserialize)]
163pub struct CanStartArgs {
164 pub workspace: String,
165}
166
167/// `start_run`: asks whether a workspace may start an agent, and opens the
168/// run it will be charged for. Called by the runner service. Returns
169/// `Outcome<Option<RunTicket>>`: no ticket when billing is off, a failure
170/// when the workspace has no credit.
171#[derive(Debug, Serialize, Deserialize)]
172pub struct StartRunArgs {
173 pub workspace: String,
174 pub repo: RepoPath,
175 pub number: u32,
176 /// `implement`, `review` or `update`.
177 pub task: String,
178 /// The model, by its public name.
179 pub model: String,
180 /// `workspace` when the run uses the workspace's own model provider.
181 /// The runner, which is TypeScript, sends it as `billedTo`.
182 #[serde(default = "g1t", alias = "billedTo")]
183 pub billed_to: String,
184}
185
186#[derive(Clone, Debug, Serialize, Deserialize)]
187#[serde(rename_all = "camelCase")]
188pub struct RunTicket {
189 pub run_id: String,
190 /// Lets the sandbox, and nothing else, report what this run cost.
191 pub token: String,
192}
193
194/// `finish_run`: what a run cost, as its sandbox reports it. Charged once.
195/// Returns `Outcome<bool>`.
196#[derive(Debug, Serialize, Deserialize)]
197#[serde(rename_all = "camelCase")]
198pub struct FinishRunArgs {
199 pub run_id: String,
200 pub token: String,
201 /// What the model provider charged, in US dollars.
202 pub cost_usd: f64,
203 #[serde(default)]
204 pub turns: u32,
205}
206
207
208/// `usage`: what a workspace's agents cost over a period, broken down.
209/// Members only. Returns `Outcome<Usage>`.
210#[derive(Debug, Serialize, Deserialize)]
211pub struct UsageArgs {
212 pub workspace: String,
213 pub viewer: Viewer,
214 /// RFC 3339: the start of the period. The period runs to now.
215 pub since: String,
216}
217
218/// One slice of usage: what it was for, what it cost, how many runs.
219#[derive(Clone, Debug, Serialize, Deserialize)]
220#[serde(rename_all = "camelCase")]
221pub struct UsageSlice {
222 pub key: String,
223 pub micros: i64,
224 pub runs: u32,
225}
226
227/// What a workspace's agents cost over a period.
228#[derive(Clone, Debug, Serialize, Deserialize)]
229#[serde(rename_all = "camelCase")]
230pub struct Usage {
231 pub since: String,
232 /// Charged, including g1t's margin.
233 pub spent_micros: i64,
234 /// What g1t's model provider charged, before the margin.
235 pub cost_micros: i64,
236 /// What runs on the workspace's own provider cost there, as the harness
237 /// estimated it. Not charged by g1t.
238 pub provider_micros: i64,
239 /// What the runs used, at cost: g1t's models and the workspace's own
240 /// provider together, whatever was charged for them.
241 pub used_micros: i64,
242 /// g1t charges nothing for now. The slices then measure usage at cost,
243 /// since every charge is zero.
244 pub free: bool,
245 pub runs: u32,
246 /// Spend per day (`YYYY-MM-DD`) and task, as `day/task` keys.
247 pub by_day: Vec<UsageSlice>,
248 /// Per task: implement, review, revise, update, plan.
249 pub by_task: Vec<UsageSlice>,
250 /// Per repository, `namespace/name`.
251 pub by_repo: Vec<UsageSlice>,
252 /// The pull requests that cost most, as `namespace/name#number`.
253 pub by_pull: Vec<UsageSlice>,
254 /// Per model, by its public name.
255 pub by_model: Vec<UsageSlice>,
256 /// Credit bought in the period.
257 pub added_micros: i64,
258}
259
260#[cfg(test)]
261mod tests {
262 use super::*;
263
264 #[test]
265 fn who_pays_is_read_as_the_runner_sends_it() {
266 let run: StartRunArgs = serde_json::from_value(serde_json::json!({
267 "workspace": "acme",
268 "repo": { "namespace": "acme", "name": "web" },
269 "number": 7,
270 "task": "implement",
271 "model": "Claude Sonnet 5.5",
272 "billedTo": "workspace",
273 }))
274 .unwrap();
275 assert_eq!(run.billed_to, "workspace");
276 }
277}