g1t/packages/contracts/src/billing.ts

298 lines11,242 bytesCodeBlame
1import type { User, Viewer } from "./identity";
2import type { RepoPath } from "./repos";
3import type { Result } from "./result";
4
5/** Millionths of a US dollar in one dollar: the unit money is held in. */
6export const MICROS_PER_DOLLAR = 1_000_000;
7
8/** Whether workspaces are charged for agents at all, and with real money. */
9export type BillingStatus = {
10 /**
11 * False when no card processor is configured: nothing is charged, and who
12 * may run agents is decided some other way.
13 */
14 enabled: boolean;
15 /** False while the card processor is in its test mode, where cards are not real. */
16 live: boolean;
17 /**
18 * True while g1t is being built out: runs are recorded with what they
19 * cost, but nothing is charged and no credit is needed. Not forever.
20 */
21 free?: boolean;
22};
23
24/** A workspace's standing. */
25export type BillingAccount = {
26 workspace: string;
27 /**
28 * Credit left, in millionths of a dollar. Can dip below zero by the cost
29 * of the runs that were under way when it ran out.
30 */
31 balanceMicros: number;
32 status: BillingStatus;
33 /** What is added to a run's cost, in percent. */
34 marginPercent: number;
35 /** What a run on the workspace's own model provider is charged instead. */
36 orchestrationFeeMicros: number;
37};
38
39/** One line of a workspace's statement. */
40export type LedgerEntry = {
41 id: string;
42 /** Credit bought with a card, or an agent's run. */
43 kind: "top_up" | "usage";
44 /** Positive for credit added, negative for usage. */
45 amountMicros: number;
46 description: string;
47 /** For usage: the repository and pull request the agent worked on. */
48 repo: string | null;
49 number: number | null;
50 /** For usage: `implement`, `review` or `update`. */
51 task: string | null;
52 /** For usage: the model, by its public name. */
53 model: string | null;
54 /** For usage: who paid the model provider. */
55 billedTo: "g1t" | "workspace";
56 /** For a top-up: the username of whoever paid. */
57 createdBy: string | null;
58 /** RFC 3339. */
59 createdAt: string;
60};
61
62/** What lets a sandbox, and nothing else, report what its run cost. */
63export type RunTicket = { runId: string; token: string };
64
65/**
66 * What agents cost, charged to the workspace they worked for. A workspace
67 * buys credit; each run deducts its cost plus g1t's margin; with no credit,
68 * no agent starts.
69 */
70/**
71 * The free allowance on g1t's hosted models for a workspace not otherwise
72 * open to them: a few dollars of model cost each, out of one pool, until a
73 * date. Mirrors `Trial` in `crates/contracts/src/billing.rs`.
74 */
75/** How much a workspace has earned g1t's trust with money. */
76export type Trust = "new" | "paid" | "reviewed" | "internal";
77
78/**
79 * How far a workspace's unpaid usage has gone this month, and where its
80 * work stops: past `ceilingMicros`, no new sandboxes, builds or app
81 * requests. Usage counts at its cost to g1t or its charge, whichever is
82 * more, so it counts while g1t is free too.
83 */
84export type Limit = {
85 workspace: string;
86 trust: Trust;
87 exposureMicros: number;
88 /** The lower of g1t's ceiling and the owner's spend limit; null for g1t's own. */
89 ceilingMicros: number | null;
90 trustCeilingMicros: number | null;
91 spendLimitMicros: number | null;
92 state: "ok" | "warning" | "stopped";
93 message: string | null;
94};
95
96/** One metered unit: what it costs g1t and what it is sold at; the price follows the cost. */
97export type Price = {
98 meter: "sandbox_second" | "build_second" | "app_requests" | "app_cpu" | "app_month" | string;
99 title: string;
100 unit: string;
101 costMicros: number;
102 markupPercent: number;
103 priceMicros: number;
104 /** `list`: Cloudflare's published price. `cloudflare`: measured from Cloudflare's bill. */
105 source: "list" | "cloudflare" | string;
106 checkedAt: string | null;
107 updatedAt: string;
108};
109
110export type PriceChange = {
111 meter: string;
112 oldCostMicros: number;
113 newCostMicros: number;
114 markupPercent: number;
115 reason: string;
116 createdAt: string;
117};
118
119export type PriceBook = { prices: Price[]; changes: PriceChange[]; modelMarginPercent: number };
120
121export type Trial = {
122 open: boolean;
123 usedMicros: number;
124 limitMicros: number;
125 endsAt: string | null;
126 /** Why it is closed: `off`, `ended`, `used` (this workspace's) or `pool` (everyone's). */
127 reason: "off" | "ended" | "used" | "pool" | null;
128};
129
130/**
131 * A paid feature a workspace turns on with a monthly plan, as Cloudflare's
132 * Workers for Platforms or Vercel's Pro are bought. Never free: neither
133 * `free` nor the model allowance covers it. Mirrors `Feature` in
134 * `crates/contracts/src/billing.rs`.
135 */
136export type Feature = "deployments";
137
138/** What the Deployments plan includes each month. Mirrors `deployments_allowance`. */
139export const DEPLOYMENTS_ALLOWANCE = {
140 apps: 10,
141 requests: 1_000_000,
142 cpuMs: 3_000_000,
143 /** What Cloudflare charges g1t past that, in millionths of a dollar. */
144 microsPerAppMonth: 20_000,
145 microsPerMillionRequests: 300_000,
146 microsPerMillionCpuMs: 20_000,
147 /** One second of a build's sandbox; builds are charged, not included. */
148 microsPerBuildSecond: 21,
149} as const;
150
151export type FeaturePlan = {
152 feature: Feature;
153 title: string;
154 /** Charged every month while the plan is on, in cents. */
155 monthlyCents: number;
156 /** What the price includes, one line each. */
157 includes: string[];
158 /** How usage past the allowance is charged. */
159 overage: string;
160};
161
162export type SubscriptionStatus = "active" | "canceling" | "past_due" | "canceled";
163
164export type Subscription = {
165 feature: Feature;
166 status: SubscriptionStatus;
167 /** RFC 3339: when the period paid for ends. */
168 periodEnd: string | null;
169 startedBy: string;
170 startedAt: string;
171};
172
173/** A feature as a workspace sees it. */
174export type FeatureState = {
175 plan: FeaturePlan;
176 subscription: Subscription | null;
177 /** Whether the feature works for the workspace now. */
178 on: boolean;
179};
180
181export interface BillingApi {
182 status(): Promise<BillingStatus>;
183 /** Members of the workspace only. */
184 account(workspace: string, viewer: Viewer): Promise<Result<BillingAccount>>;
185 /** Newest first. Members of the workspace only. */
186 ledger(workspace: string, viewer: Viewer): Promise<Result<LedgerEntry[]>>;
187 /** What the workspace's agents cost since `since`, broken down. Members only. */
188 usage(workspace: string, viewer: Viewer, since: string): Promise<Result<Usage>>;
189 /**
190 * Starts a card payment for credit and returns the page to send the
191 * person to. Owners only. The payment's id comes back to `returnUrl` as
192 * `session`.
193 */
194 checkout(actor: User, workspace: string, amountCents: number, returnUrl: string): Promise<Result<{ url: string }>>;
195 /** Credits a payment once the processor says it was made. Safe to repeat. */
196 confirm(workspace: string, viewer: Viewer, session: string): Promise<Result<BillingAccount>>;
197 /**
198 * Whether a workspace may start an agent now, asked before anything is
199 * opened for it. A failure, with the reason to show, when it has no credit.
200 */
201 canStart(workspace: string): Promise<Result<boolean>>;
202 /** A workspace's free allowance on g1t's hosted models; `exempt` are open to them anyway. */
203 trial(workspace: string, exempt: string[]): Promise<Trial>;
204 /**
205 * Asks whether a workspace may start an agent and opens the run it will be
206 * charged for. Null when billing is off; a failure when there is no credit.
207 */
208 /** Every paid feature and the workspace's plan for each. Members only. */
209 features(workspace: string, viewer: Viewer): Promise<Result<FeatureState[]>>;
210 /**
211 * Starts the card page for a feature's monthly plan. Owners only. The
212 * page's id comes back to `returnUrl` as `session`.
213 */
214 subscribe(actor: User, workspace: string, feature: Feature, returnUrl: string): Promise<Result<{ url: string }>>;
215 /** Turns the feature on once the plan is paid for. Safe to repeat. */
216 confirmSubscription(workspace: string, viewer: Viewer, session: string): Promise<Result<FeatureState>>;
217 /** Ends a plan at the end of its period, or (`resume`) takes that back. Owners only. */
218 cancelSubscription(actor: User, workspace: string, feature: Feature, resume?: boolean): Promise<Result<FeatureState>>;
219 /** Whether a feature works for a workspace now; a failure with the reason when not. */
220 hasFeature(workspace: string, feature: Feature): Promise<Result<boolean>>;
221 /**
222 * Usage past a plan's allowance, charged from credit at cost plus the
223 * margin, once per `reference`. False if it was charged before.
224 */
225 chargeFeature(charge: {
226 workspace: string;
227 feature: Feature;
228 costMicros: number;
229 description: string;
230 repo?: string | null;
231 reference: string;
232 }): Promise<Result<boolean>>;
233 /**
234 * Usage this month to be charged later (app traffic past a plan), so the
235 * workspace's limit counts it now. Replaces the last report.
236 */
237 notePending(workspace: string, source: "deployments", costMicros: number): Promise<boolean>;
238 /** Every metered price and the recent changes. Public. */
239 prices(): Promise<PriceBook>;
240 /** A workspace's limit, for its members. */
241 limit(workspace: string, viewer: Viewer): Promise<Result<Limit>>;
242 /** The same, for the services that enforce it. */
243 checkLimit(workspace: string): Promise<Result<Limit>>;
244 /** The owner's own monthly ceiling, under g1t's; null removes it. Owners only. */
245 setSpendLimit(actor: User, workspace: string, spendLimitMicros: number | null): Promise<Result<Limit>>;
246 /**
247 * How long a sandbox ran for a workspace, reported when it stops. Its
248 * cost is always recorded; seconds past the month's free minutes are
249 * charged. False if `reference` was recorded before.
250 */
251 recordSandbox(usage: {
252 workspace: string;
253 seconds: number;
254 description: string;
255 repo?: string | null;
256 reference: string;
257 }): Promise<Result<boolean>>;
258 startRun(run: {
259 workspace: string;
260 repo: RepoPath;
261 number: number;
262 task: string;
263 model: string;
264 /** `workspace` when the run uses the workspace's own model provider. */
265 billedTo?: "g1t" | "workspace";
266 /** The model session's id, so the run can be settled at AI Gateway's price. */
267 session?: string | null;
268 }): Promise<Result<RunTicket | null>>;
269}
270
271
272/** One slice of usage: what it was for, what it cost, how many runs. */
273export type UsageSlice = { key: string; micros: number; runs: number };
274
275/** What a workspace's agents cost over a period. */
276export type Usage = {
277 since: string;
278 /** Charged, including g1t's margin. */
279 spentMicros: number;
280 /** What g1t's model provider charged, before the margin. */
281 costMicros: number;
282 /** What runs on the workspace's own provider cost there, estimated. Not charged by g1t. */
283 providerMicros: number;
284 /** What the runs used, at cost: g1t's models and the workspace's own provider together. */
285 usedMicros: number;
286 /** g1t charges nothing for now; the slices then measure usage at cost. */
287 free: boolean;
288 runs: number;
289 /** Spend per day and task, keyed `YYYY-MM-DD/task`. */
290 byDay: UsageSlice[];
291 byTask: UsageSlice[];
292 byRepo: UsageSlice[];
293 /** Keyed `namespace/name#number`. */
294 byPull: UsageSlice[];
295 byModel: UsageSlice[];
296 /** Credit bought in the period. */
297 addedMicros: number;
298};