pr_01m47d24b0e6n91zwymwxg0vpx/packages/contracts/src/billing.ts

264 lines10,023 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
96export type Trial = {
97 open: boolean;
98 usedMicros: number;
99 limitMicros: number;
100 endsAt: string | null;
101 /** Why it is closed: `off`, `ended`, `used` (this workspace's) or `pool` (everyone's). */
102 reason: "off" | "ended" | "used" | "pool" | null;
103};
104
105/**
106 * A paid feature a workspace turns on with a monthly plan, as Cloudflare's
107 * Workers for Platforms or Vercel's Pro are bought. Never free: neither
108 * `free` nor the model allowance covers it. Mirrors `Feature` in
109 * `crates/contracts/src/billing.rs`.
110 */
111export type Feature = "deployments";
112
113/** What the Deployments plan includes each month. Mirrors `deployments_allowance`. */
114export const DEPLOYMENTS_ALLOWANCE = {
115 apps: 10,
116 requests: 1_000_000,
117 cpuMs: 3_000_000,
118 /** What Cloudflare charges g1t past that, in millionths of a dollar. */
119 microsPerAppMonth: 20_000,
120 microsPerMillionRequests: 300_000,
121 microsPerMillionCpuMs: 20_000,
122 /** One second of a build's sandbox; builds are charged, not included. */
123 microsPerBuildSecond: 21,
124} as const;
125
126export type FeaturePlan = {
127 feature: Feature;
128 title: string;
129 /** Charged every month while the plan is on, in cents. */
130 monthlyCents: number;
131 /** What the price includes, one line each. */
132 includes: string[];
133 /** How usage past the allowance is charged. */
134 overage: string;
135};
136
137export type SubscriptionStatus = "active" | "canceling" | "past_due" | "canceled";
138
139export type Subscription = {
140 feature: Feature;
141 status: SubscriptionStatus;
142 /** RFC 3339: when the period paid for ends. */
143 periodEnd: string | null;
144 startedBy: string;
145 startedAt: string;
146};
147
148/** A feature as a workspace sees it. */
149export type FeatureState = {
150 plan: FeaturePlan;
151 subscription: Subscription | null;
152 /** Whether the feature works for the workspace now. */
153 on: boolean;
154};
155
156export interface BillingApi {
157 status(): Promise<BillingStatus>;
158 /** Members of the workspace only. */
159 account(workspace: string, viewer: Viewer): Promise<Result<BillingAccount>>;
160 /** Newest first. Members of the workspace only. */
161 ledger(workspace: string, viewer: Viewer): Promise<Result<LedgerEntry[]>>;
162 /** What the workspace's agents cost since `since`, broken down. Members only. */
163 usage(workspace: string, viewer: Viewer, since: string): Promise<Result<Usage>>;
164 /**
165 * Starts a card payment for credit and returns the page to send the
166 * person to. Owners only. The payment's id comes back to `returnUrl` as
167 * `session`.
168 */
169 checkout(actor: User, workspace: string, amountCents: number, returnUrl: string): Promise<Result<{ url: string }>>;
170 /** Credits a payment once the processor says it was made. Safe to repeat. */
171 confirm(workspace: string, viewer: Viewer, session: string): Promise<Result<BillingAccount>>;
172 /**
173 * Whether a workspace may start an agent now, asked before anything is
174 * opened for it. A failure, with the reason to show, when it has no credit.
175 */
176 canStart(workspace: string): Promise<Result<boolean>>;
177 /** A workspace's free allowance on g1t's hosted models; `exempt` are open to them anyway. */
178 trial(workspace: string, exempt: string[]): Promise<Trial>;
179 /**
180 * Asks whether a workspace may start an agent and opens the run it will be
181 * charged for. Null when billing is off; a failure when there is no credit.
182 */
183 /** Every paid feature and the workspace's plan for each. Members only. */
184 features(workspace: string, viewer: Viewer): Promise<Result<FeatureState[]>>;
185 /**
186 * Starts the card page for a feature's monthly plan. Owners only. The
187 * page's id comes back to `returnUrl` as `session`.
188 */
189 subscribe(actor: User, workspace: string, feature: Feature, returnUrl: string): Promise<Result<{ url: string }>>;
190 /** Turns the feature on once the plan is paid for. Safe to repeat. */
191 confirmSubscription(workspace: string, viewer: Viewer, session: string): Promise<Result<FeatureState>>;
192 /** Ends a plan at the end of its period, or (`resume`) takes that back. Owners only. */
193 cancelSubscription(actor: User, workspace: string, feature: Feature, resume?: boolean): Promise<Result<FeatureState>>;
194 /** Whether a feature works for a workspace now; a failure with the reason when not. */
195 hasFeature(workspace: string, feature: Feature): Promise<Result<boolean>>;
196 /**
197 * Usage past a plan's allowance, charged from credit at cost plus the
198 * margin, once per `reference`. False if it was charged before.
199 */
200 chargeFeature(charge: {
201 workspace: string;
202 feature: Feature;
203 costMicros: number;
204 description: string;
205 repo?: string | null;
206 reference: string;
207 }): Promise<Result<boolean>>;
208 /** A workspace's limit, for its members. */
209 limit(workspace: string, viewer: Viewer): Promise<Result<Limit>>;
210 /** The same, for the services that enforce it. */
211 checkLimit(workspace: string): Promise<Result<Limit>>;
212 /** The owner's own monthly ceiling, under g1t's; null removes it. Owners only. */
213 setSpendLimit(actor: User, workspace: string, spendLimitMicros: number | null): Promise<Result<Limit>>;
214 /**
215 * How long a sandbox ran for a workspace, reported when it stops. Its
216 * cost is always recorded; seconds past the month's free minutes are
217 * charged. False if `reference` was recorded before.
218 */
219 recordSandbox(usage: {
220 workspace: string;
221 seconds: number;
222 description: string;
223 repo?: string | null;
224 reference: string;
225 }): Promise<Result<boolean>>;
226 startRun(run: {
227 workspace: string;
228 repo: RepoPath;
229 number: number;
230 task: string;
231 model: string;
232 /** `workspace` when the run uses the workspace's own model provider. */
233 billedTo?: "g1t" | "workspace";
234 }): Promise<Result<RunTicket | null>>;
235}
236
237
238/** One slice of usage: what it was for, what it cost, how many runs. */
239export type UsageSlice = { key: string; micros: number; runs: number };
240
241/** What a workspace's agents cost over a period. */
242export type Usage = {
243 since: string;
244 /** Charged, including g1t's margin. */
245 spentMicros: number;
246 /** What g1t's model provider charged, before the margin. */
247 costMicros: number;
248 /** What runs on the workspace's own provider cost there, estimated. Not charged by g1t. */
249 providerMicros: number;
250 /** What the runs used, at cost: g1t's models and the workspace's own provider together. */
251 usedMicros: number;
252 /** g1t charges nothing for now; the slices then measure usage at cost. */
253 free: boolean;
254 runs: number;
255 /** Spend per day and task, keyed `YYYY-MM-DD/task`. */
256 byDay: UsageSlice[];
257 byTask: UsageSlice[];
258 byRepo: UsageSlice[];
259 /** Keyed `namespace/name#number`. */
260 byPull: UsageSlice[];
261 byModel: UsageSlice[];
262 /** Credit bought in the period. */
263 addedMicros: number;
264};