flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/packages/contracts/src/billing.ts

409 lines15,752 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 /** The card charged near the limit and when a month closes, if one is saved. */
38 card?: { brand: string; last4: string; expMonth: number; expYear: number } | null;
39};
40
41/** One line of a workspace's statement. */
42export type LedgerEntry = {
43 id: string;
44 /** Credit bought with a card, or an agent's run. */
45 kind: "top_up" | "usage";
46 /** Positive for credit added, negative for usage. */
47 amountMicros: number;
48 description: string;
49 /** For usage: the repository and pull request the agent worked on. */
50 repo: string | null;
51 number: number | null;
52 /** For usage: `implement`, `review` or `update`. */
53 task: string | null;
54 /** For usage: the model, by its public name. */
55 model: string | null;
56 /** For usage: who paid the model provider. */
57 billedTo: "g1t" | "workspace";
58 /** For a top-up: the username of whoever paid. */
59 createdBy: string | null;
60 /** RFC 3339. */
61 createdAt: string;
62 /** The workspace the line belongs to, which tells an enterprise's lines apart. */
63 workspace?: string | null;
64};
65
66/** What lets a sandbox, and nothing else, report what its run cost. */
67export type RunTicket = { runId: string; token: string };
68
69/**
70 * What agents cost, charged to the workspace they worked for. A workspace
71 * buys credit; each run deducts its cost plus g1t's margin; with no credit,
72 * no agent starts.
73 */
74/**
75 * The free allowance on g1t's hosted models for a workspace not otherwise
76 * open to them: a few dollars of model cost each, out of one pool, until a
77 * date. Mirrors `Trial` in `crates/contracts/src/billing.rs`.
78 */
79/** How an account is charged. Standard unless g1t set otherwise in sudo. */
80export type Terms = {
81 kind: "standard" | "comped" | "custom";
82 discountPercent: number;
83 ceilingMicros: number | null;
84 note: string;
85 until: string | null;
86 setBy: string | null;
87 setAt: string | null;
88};
89
90/**
91 * Who pays: a workspace's own account, or an enterprise's, which pays for
92 * several workspaces with one bill and one limit.
93 */
94export type PayingAccount = {
95 id: string;
96 kind: "workspace" | "enterprise";
97 name: string;
98 terms: Terms;
99 workspaces: string[];
100 /** Where an enterprise's invoices go. */
101 billingEmail?: string | null;
102 /** An enterprise's invoices, newest first. */
103 invoices?: EnterpriseInvoice[];
104 createdAt: string;
105};
106
107export type AccountSummary = {
108 account: PayingAccount;
109 limit: Limit;
110 chargedMicros: number;
111 costMicros: number;
112 paidMicros: number;
113 /** The same figures for each of the account's workspaces that has any. */
114 byWorkspace: WorkspaceFigures[];
115};
116
117/** One workspace's share of an `AccountSummary`. */
118export type WorkspaceFigures = { workspace: string; chargedMicros: number; costMicros: number; paidMicros: number };
119
120export type StripeStatus = {
121 /** `test` or `live`, from the key; `off` without one. */
122 mode: "test" | "live" | "off" | string;
123 webhook: { url: string; endpointId: string; events: string[]; createdBy: string; createdAt: string } | null;
124 recentEvents: { id: string; kind: string; outcome: string; receivedAt: string }[];
125 error: string | null;
126};
127
128/** An enterprise's invoice: one line per workspace, paid on Stripe's page. */
129export type EnterpriseInvoice = {
130 invoiceId: string;
131 hostedUrl: string | null;
132 amountMicros: number;
133 status: "open" | "paid" | "overdue" | "void" | string;
134 period: string;
135 lines: { workspace: string; amountMicros: number }[];
136 createdAt: string;
137};
138
139/** A customer's Stripe billing page, for staff to send them. */
140export type BillingLink = {
141 /** One-time and short-lived, signed in already. */
142 portalUrl: string;
143 /** The page's sign-in, which does not expire: the customer signs in by email. */
144 loginUrl: string | null;
145 customerEmail: string | null;
146 expiresNote: string;
147};
148
149export type AdminAction = { id: string; account: string; action: string; detail: string; by: string; createdAt: string };
150
151export type AccountDetail = {
152 summary: AccountSummary;
153 workspaces: Limit[];
154 ledger: LedgerEntry[];
155 audit: AdminAction[];
156};
157
158/** Staff-only billing, for sudo.g1t.sh. Every change names who made it. */
159export interface BillingAdminApi {
160 accounts(query?: string): Promise<AccountSummary[]>;
161 account(id: string): Promise<Result<AccountDetail>>;
162 setTerms(id: string, terms: Terms, by: string): Promise<Result<PayingAccount>>;
163 createEnterprise(name: string, workspaces: string[], by: string): Promise<Result<PayingAccount>>;
164 attach(workspace: string, account: string | null, by: string): Promise<Result<PayingAccount>>;
165 credit(workspace: string, amountMicros: number, note: string, by: string): Promise<Result<LedgerEntry>>;
166 /** The workspace's Stripe billing page, to send to the customer. Logged. */
167 billingLink(workspace: string, by: string): Promise<Result<BillingLink>>;
168 /** Where billing stands with Stripe; with `setup`, registers the webhook first. */
169 stripe(setup?: boolean, by?: string): Promise<StripeStatus>;
170 /** Where an enterprise's invoices go; makes its Stripe customer. */
171 enterpriseBilling(id: string, email: string, by: string): Promise<Result<PayingAccount>>;
172 /** Sends an enterprise its invoice now, for what its workspaces owe. */
173 invoiceEnterprise(id: string, by: string): Promise<Result<EnterpriseInvoice>>;
174 /** Exactly these workspaces' accounts, such as one page of the list. */
175 accountsFor(workspaces: string[]): Promise<AccountSummary[]>;
176}
177
178/** How much a workspace has earned g1t's trust with money. */
179export type Trust = "new" | "paid" | "reviewed" | "internal";
180
181/**
182 * How far a workspace's unpaid usage has gone this month, and where its
183 * work stops: past `ceilingMicros`, no new sandboxes, builds or app
184 * requests. Usage counts at its cost to g1t or its charge, whichever is
185 * more, so it counts while g1t is free too.
186 */
187export type Limit = {
188 workspace: string;
189 /** The account that pays: the workspace's own (`ws_<slug>`), or its enterprise's. */
190 account: string;
191 accountName: string;
192 trust: Trust;
193 exposureMicros: number;
194 /** The lower of g1t's ceiling and the owner's spend limit; null for g1t's own. */
195 ceilingMicros: number | null;
196 trustCeilingMicros: number | null;
197 spendLimitMicros: number | null;
198 state: "ok" | "warning" | "stopped";
199 message: string | null;
200};
201
202/** One metered unit: what it costs g1t and what it is sold at; the price follows the cost. */
203export type Price = {
204 meter: "sandbox_second" | "build_second" | "app_requests" | "app_cpu" | "app_month" | string;
205 title: string;
206 unit: string;
207 costMicros: number;
208 markupPercent: number;
209 priceMicros: number;
210 /** `list`: Cloudflare's published price. `cloudflare`: measured from Cloudflare's bill. */
211 source: "list" | "cloudflare" | string;
212 checkedAt: string | null;
213 updatedAt: string;
214};
215
216export type PriceChange = {
217 meter: string;
218 oldCostMicros: number;
219 newCostMicros: number;
220 markupPercent: number;
221 reason: string;
222 createdAt: string;
223};
224
225export type PriceBook = { prices: Price[]; changes: PriceChange[]; modelMarginPercent: number };
226
227export type Trial = {
228 open: boolean;
229 usedMicros: number;
230 limitMicros: number;
231 endsAt: string | null;
232 /** Why it is closed: `off`, `ended`, `used` (this workspace's) or `pool` (everyone's). */
233 reason: "off" | "ended" | "used" | "pool" | null;
234};
235
236/**
237 * A paid feature a workspace turns on with a monthly plan, as Cloudflare's
238 * Workers for Platforms or Vercel's Pro are bought. Never free: neither
239 * `free` nor the model allowance covers it. Mirrors `Feature` in
240 * `crates/contracts/src/billing.rs`.
241 */
242export type Feature = "deployments";
243
244/** What the Deployments plan includes each month. Mirrors `deployments_allowance`. */
245export const DEPLOYMENTS_ALLOWANCE = {
246 apps: 10,
247 requests: 1_000_000,
248 cpuMs: 3_000_000,
249 /** What Cloudflare charges g1t past that, in millionths of a dollar. */
250 microsPerAppMonth: 20_000,
251 microsPerMillionRequests: 300_000,
252 microsPerMillionCpuMs: 20_000,
253 /** One second of a build's sandbox; builds are charged, not included. */
254 microsPerBuildSecond: 21,
255} as const;
256
257export type FeaturePlan = {
258 feature: Feature;
259 title: string;
260 /** Charged every month while the plan is on, in cents. */
261 monthlyCents: number;
262 /** What the price includes, one line each. */
263 includes: string[];
264 /** How usage past the allowance is charged. */
265 overage: string;
266};
267
268export type SubscriptionStatus = "active" | "canceling" | "past_due" | "canceled";
269
270export type Subscription = {
271 feature: Feature;
272 status: SubscriptionStatus;
273 /** RFC 3339: when the period paid for ends. */
274 periodEnd: string | null;
275 startedBy: string;
276 startedAt: string;
277};
278
279/** A feature as a workspace sees it. */
280export type FeatureState = {
281 plan: FeaturePlan;
282 subscription: Subscription | null;
283 /** Whether the feature works for the workspace now. */
284 on: boolean;
285};
286
287export interface BillingApi {
288 status(): Promise<BillingStatus>;
289 /** Members of the workspace only. */
290 account(workspace: string, viewer: Viewer): Promise<Result<BillingAccount>>;
291 /** Newest first. Members of the workspace only. */
292 ledger(workspace: string, viewer: Viewer): Promise<Result<LedgerEntry[]>>;
293 /** What the workspace's agents cost since `since`, broken down. Members only. */
294 usage(workspace: string, viewer: Viewer, since: string): Promise<Result<Usage>>;
295 /**
296 * Starts a card payment for credit and returns the page to send the
297 * person to. Owners only. The payment's id comes back to `returnUrl` as
298 * `session`.
299 */
300 checkout(actor: User, workspace: string, amountCents: number, returnUrl: string): Promise<Result<{ url: string }>>;
301 /**
302 * Stripe's hosted billing page for the workspace: card, invoices, billing
303 * email and address. g1t never handles card numbers. Owners only.
304 */
305 billingPortal(actor: User, workspace: string, returnUrl: string): Promise<Result<{ url: string }>>;
306 /** Credits a payment once the processor says it was made. Safe to repeat. */
307 confirm(workspace: string, viewer: Viewer, session: string): Promise<Result<BillingAccount>>;
308 /**
309 * Whether a workspace may start an agent now, asked before anything is
310 * opened for it. A failure, with the reason to show, when it has no credit.
311 */
312 canStart(workspace: string): Promise<Result<boolean>>;
313 /** A workspace's free allowance on g1t's hosted models; `exempt` are open to them anyway. */
314 trial(workspace: string, exempt: string[]): Promise<Trial>;
315 /**
316 * Asks whether a workspace may start an agent and opens the run it will be
317 * charged for. Null when billing is off; a failure when there is no credit.
318 */
319 /** Every paid feature and the workspace's plan for each. Members only. */
320 features(workspace: string, viewer: Viewer): Promise<Result<FeatureState[]>>;
321 /**
322 * Starts the card page for a feature's monthly plan. Owners only. The
323 * page's id comes back to `returnUrl` as `session`.
324 */
325 subscribe(actor: User, workspace: string, feature: Feature, returnUrl: string): Promise<Result<{ url: string }>>;
326 /** Turns the feature on once the plan is paid for. Safe to repeat. */
327 confirmSubscription(workspace: string, viewer: Viewer, session: string): Promise<Result<FeatureState>>;
328 /** Ends a plan at the end of its period, or (`resume`) takes that back. Owners only. */
329 cancelSubscription(actor: User, workspace: string, feature: Feature, resume?: boolean): Promise<Result<FeatureState>>;
330 /** Whether a feature works for a workspace now; a failure with the reason when not. */
331 hasFeature(workspace: string, feature: Feature): Promise<Result<boolean>>;
332 /**
333 * Usage past a plan's allowance, charged from credit at cost plus the
334 * margin, once per `reference`. False if it was charged before.
335 */
336 chargeFeature(charge: {
337 workspace: string;
338 feature: Feature;
339 costMicros: number;
340 description: string;
341 repo?: string | null;
342 reference: string;
343 }): Promise<Result<boolean>>;
344 /**
345 * Usage this month to be charged later (app traffic past a plan), so the
346 * workspace's limit counts it now. Replaces the last report.
347 */
348 notePending(workspace: string, source: "deployments", costMicros: number): Promise<boolean>;
349 /** Every metered price and the recent changes. Public. */
350 prices(): Promise<PriceBook>;
351 /** A workspace's limit, for its members. */
352 limit(workspace: string, viewer: Viewer): Promise<Result<Limit>>;
353 /** The same, for the services that enforce it. */
354 checkLimit(workspace: string): Promise<Result<Limit>>;
355 /** The owner's own monthly ceiling, under g1t's; null removes it. Owners only. */
356 setSpendLimit(actor: User, workspace: string, spendLimitMicros: number | null): Promise<Result<Limit>>;
357 /**
358 * How long a sandbox ran for a workspace, reported when it stops. Its
359 * cost is always recorded; seconds past the month's free minutes are
360 * charged. False if `reference` was recorded before.
361 */
362 recordSandbox(usage: {
363 workspace: string;
364 seconds: number;
365 description: string;
366 repo?: string | null;
367 reference: string;
368 }): Promise<Result<boolean>>;
369 startRun(run: {
370 workspace: string;
371 repo: RepoPath;
372 number: number;
373 task: string;
374 model: string;
375 /** `workspace` when the run uses the workspace's own model provider. */
376 billedTo?: "g1t" | "workspace";
377 /** The model session's id, so the run can be settled at AI Gateway's price. */
378 session?: string | null;
379 }): Promise<Result<RunTicket | null>>;
380}
381
382
383/** One slice of usage: what it was for, what it cost, how many runs. */
384export type UsageSlice = { key: string; micros: number; runs: number };
385
386/** What a workspace's agents cost over a period. */
387export type Usage = {
388 since: string;
389 /** Charged, including g1t's margin. */
390 spentMicros: number;
391 /** What g1t's model provider charged, before the margin. */
392 costMicros: number;
393 /** What runs on the workspace's own provider cost there, estimated. Not charged by g1t. */
394 providerMicros: number;
395 /** What the runs used, at cost: g1t's models and the workspace's own provider together. */
396 usedMicros: number;
397 /** g1t charges nothing for now; the slices then measure usage at cost. */
398 free: boolean;
399 runs: number;
400 /** Spend per day and task, keyed `YYYY-MM-DD/task`. */
401 byDay: UsageSlice[];
402 byTask: UsageSlice[];
403 byRepo: UsageSlice[];
404 /** Keyed `namespace/name#number`. */
405 byPull: UsageSlice[];
406 byModel: UsageSlice[];
407 /** Credit bought in the period. */
408 addedMicros: number;
409};