Skip to content

g1t/packages/contracts/src/billing.ts

1,612 lines64,726 bytesCodeBlame
1import type { ComputeKind, Reservation } from "./compute";
2import type { User, Viewer } from "./identity";
3import type { RepoPath } from "./repos";
4import type { Result } from "./result";
5
6/** Millionths of a US dollar in one dollar: the unit money is held in. */
7export const MICROS_PER_DOLLAR = 1_000_000;
8
9/** Whether workspaces are charged for agents at all, and with real money. */
10export type BillingStatus = {
11 /**
12 * False when no card processor is configured: nothing is charged, and who
13 * may run agents is decided some other way.
14 */
15 enabled: boolean;
16 /** False while the card processor is in its test mode, where cards are not real. */
17 live: boolean;
18 /**
19 * True while g1t is being built out: runs are recorded with what they
20 * cost, but nothing is charged and no credit is needed. Not forever.
21 */
22 free?: boolean;
23};
24
25/** A workspace's standing. */
26export type BillingAccount = {
27 workspace: string;
28 /**
29 * Credit left, in millionths of a dollar. Can dip below zero by the cost
30 * of the runs that were under way when it ran out.
31 */
32 balanceMicros: number;
33 status: BillingStatus;
34 /** What is added to a run's cost, in percent. */
35 marginPercent: number;
36 /** The card charged near the limit and when a month closes, if one is saved. */
37 card?: { brand: string; last4: string; expMonth: number; expYear: number } | null;
38};
39
40/** One line of a workspace's statement. */
41export type LedgerEntry = {
42 id: string;
43 /** Credit bought with a card, or an agent's run. */
44 kind: "top_up" | "usage";
45 /** Positive for credit added, negative for usage. */
46 amountMicros: number;
47 description: string;
48 /** For usage: the repository and pull request the agent worked on. */
49 repo: string | null;
50 number: number | null;
51 /** For usage: `implement`, `review` or `update`. */
52 task: string | null;
53 /** For usage: the model, by its public name. */
54 model: string | null;
55 /** For usage: who paid the model provider. */
56 billedTo: "g1t" | "workspace";
57 /** For a top-up: the username of whoever paid. */
58 createdBy: string | null;
59 /** RFC 3339. */
60 createdAt: string;
61 /** The workspace the line belongs to, which tells an enterprise's lines apart. */
62 workspace?: string | null;
63 /** For usage: what the plan's included usage paid of it. `amountMicros` is what is left to pay. */
64 creditMicros?: number;
65 /** For usage: what the workspace's trial credit paid of it. */
66 trialMicros?: number;
67 /** For usage: what g1t's open-source pool paid of it. */
68 ossMicros?: number;
69 /** For usage: what g1t covered itself, such as a trial's last run past its credit. */
70 givenMicros?: number;
71 /** For usage: what the account's discount took off its price. */
72 discountMicros?: number;
73 /** For a credit from g1t, and for what of one expired or was revoked: its kind. */
74 creditKind?: CreditKind;
75};
76
77/**
78 * Why g1t gave a workspace credit. Promotional (a welcome, a referral) and
79 * goodwill (an apology) are given away when spent; a refund gives back
80 * money already paid, and never expires.
81 */
82export type CreditKind = "promotional" | "goodwill" | "refund" | "purchased";
83
84/** One credit g1t gave, with what of it was used: spent before anything paid in advance, the soonest-expiring first. */
85export type CreditGrant = {
86 /** `crd_…`, the grant's ledger reference. */
87 id: string;
88 workspace: string;
89 kind: CreditKind;
90 amountMicros: number;
91 usedMicros: number;
92 /** What can still be spent: nothing once it expired or was revoked. */
93 leftMicros: number;
94 note: string;
95 /** A refund: what it refunds, and the day of it. */
96 refundFor?: string | null;
97 refundDay?: string | null;
98 /** RFC 3339; null never expires. */
99 expiresAt: string | null;
100 createdBy: string;
101 createdAt: string;
102 state: "open" | "used" | "expired" | "revoked";
103 closedAt?: string | null;
104 closedNote?: string | null;
105 closedBy?: string | null;
106 /** What expiring or revoking took off the balance. */
107 closedMicros?: number;
108 /** What it pays for: all usage, or models only (spent first). */
109 scope?: "all" | "models";
110 /** Where it came from. */
111 source?: "staff" | "purchase" | "promo_code" | "upgrade";
112};
113
114/** A workspace's credits from g1t, newest first. */
115export type Credits = { grants: CreditGrant[]; leftMicros: number };
116
117/** One month's credits of one kind: given, spent that month, and taken back unused. */
118export type CreditMonth = {
119 month: string;
120 kind: CreditKind;
121 givenMicros: number;
122 grants: number;
123 usedMicros: number;
124 expiredMicros: number;
125 revokedMicros: number;
126};
127
128/** Every credit g1t gave (at most 200, filtered), the last 12 months by kind, and who gave them. */
129export type AdminCredits = { grants: CreditGrant[]; months: CreditMonth[]; staff: string[] };
130
131/** What a credit from sudo is, past its amount and note. */
132export type CreditOptions = {
133 kind: CreditKind;
134 /** RFC 3339; never for a refund. */
135 expiresAt?: string | null;
136 /** A refund: what it is for, and the day refunded (`YYYY-MM-DD`). */
137 refundFor?: string | null;
138 refundDay?: string | null;
139};
140
141/** What lets a sandbox, and nothing else, report what its run cost. */
142export type RunTicket = { runId: string; token: string };
143
144/**
145 * What agents cost, charged to the workspace they worked for. A workspace
146 * buys credit; each run deducts its cost plus g1t's margin; with no credit,
147 * no agent starts.
148 */
149/**
150 * The free allowance on g1t's hosted models for a workspace not otherwise
151 * open to them: a few dollars of model cost each, out of one pool, until a
152 * date. Mirrors `Trial` in `crates/contracts/src/billing.rs`.
153 */
154/**
155 * How an account is charged. Standard unless g1t set otherwise in sudo:
156 * custom terms are a discount (0 to 100%), a ceiling, or both. A 100%
157 * discount charges nothing and shows the usage at its price. `comped` is
158 * from before discounts and reads as 100%; billing no longer writes it.
159 */
160export type Terms = {
161 kind: "standard" | "comped" | "custom";
162 discountPercent: number;
163 ceilingMicros: number | null;
164 note: string;
165 until: string | null;
166 setBy: string | null;
167 setAt: string | null;
168};
169
170/**
171 * Who pays: a workspace's own account, or an enterprise's, which pays for
172 * several workspaces with one bill and one limit.
173 */
174export type PayingAccount = {
175 id: string;
176 kind: "workspace" | "enterprise";
177 name: string;
178 terms: Terms;
179 workspaces: string[];
180 /** Where an enterprise's invoices go. */
181 billingEmail?: string | null;
182 /** An enterprise's invoices, newest first. */
183 invoices?: EnterpriseInvoice[];
184 createdAt: string;
185 /** What g1t staff set for the account beyond its terms. */
186 allowances?: Allowances;
187};
188
189/** Set per account by g1t staff in sudo, on top of its terms. */
190export type Allowances = {
191 /** The g1t plan without its monthly price; usage is charged as usual. Comped accounts have it anyway. */
192 plan: boolean;
193 /** Each public repository's monthly cap on g1t's open-source pool; null for the default. */
194 ossRepoMicros: number | null;
195 /** Each workspace's trial credit, outside the monthly pool; null for the default. */
196 trialMicros: number | null;
197 /** Agents at once, in place of the plan's (2 in the first month or on the trial, then 10); null for the default. */
198 maxConcurrentAgents?: number | null;
199 /** One run's spend cap, in place of the owners' and the default $2; null for none. */
200 runCapMicros?: number | null;
201 /** What one issue's agents may spend in all, in place of the owners' and the default $10; null for none. */
202 issueCapMicros?: number | null;
203 /** Days of audit log its workspaces keep, in place of the plan's (7 free, 90 on the plan), longer or shorter; null for the plan's. */
204 auditRetentionDays?: number | null;
205 /** A hold on new compute, with why; null for none. */
206 hold?: string | null;
207};
208
209// --- Entitlements, and compute started under a reservation ------------------
210//
211// Every service that starts compute asks billing first:
212// 1. `entitlements(workspace)`: what it may do at all, its caps, and whether compute is paused.
213// 2. `reserve(...)`: holds the estimate against what may pay for it, so starts at the same moment
214// cannot overshoot together. Answers who pays first, or refuses with a stable code
215// (`not_paid`, `trial_used`, `limit`, `paused`, `oss_pool_empty`) and a message for the owner.
216// 3. `settle(reservationId, actualMicros)`: releases the hold. The charge goes on the ledger the usual way.
217// A reservation never settled lapses after `RESERVATION_HOURS`.
218
219/** A reservation that is never settled stops holding after this long. */
220export const RESERVATION_HOURS = 3;
221/** What a ceiling reads as when there is none (g1t's own workspaces). */
222export const UNLIMITED_MICROS = 1_000_000_000_000_000;
223
224/** What a workspace pays g1t on, as far as compute is concerned. Mirrors `PlanKind`. */
225export type PlanKind = "free" | "paid" | "internal" | "enterprise";
226
227// `ComputeKind` (what compute is for), `PaidBy` (who pays first: credit, trial, oss, on_demand) and
228// `Reservation` are in `./compute`, with the gate that calls `reserve` and `settle`.
229
230/** One level reached: 50, 75, 90 or 100 percent. */
231export type UsageAlert = {
232 /** `included` (the plan's included usage), `spend_limit` or `ceiling`. */
233 meter: "included" | "spend_limit" | "ceiling" | string;
234 level: number;
235 usedMicros: number;
236 limitMicros: number;
237 message: string;
238};
239
240/** An hour's spend well above the workspace's usual: new compute waits for an owner. */
241export type Spike = {
242 id: string;
243 /** `open` (waiting), `continued` (keep going) or `stopped`. */
244 status: "open" | "continued" | "stopped" | string;
245 hourMicros: number;
246 averageMicros: number;
247 detectedAt: string;
248 decidedBy?: string | null;
249 decidedAt?: string | null;
250 /** While continued: until when, unless spend doubles again first. */
251 until?: string | null;
252};
253
254/** What a workspace may do now. Mirrors `Entitlements` in `crates/contracts/src/billing.rs`. */
255export type Entitlements = {
256 workspace: string;
257 plan: PlanKind;
258 /** May start sandboxes, models, deployments and semantic search at all: paid, internal, enterprise, or free with trial credit left. */
259 compute: boolean;
260 /** The one-time trial credit left; 0 if none or used. */
261 trialMicrosLeft: number;
262 /** A card check has been done; the trial and the open-source pool need it. */
263 trialVerified: boolean;
264 /** A paid workspace still in its first billing cycle. */
265 firstMonth: boolean;
266 /** 2 in the first month or on the trial, 10 after; staff can override it. */
267 maxConcurrentAgents: number;
268 /** 60 in the first month or on the trial; otherwise the guardrails' own caps. */
269 maxRunMinutes: number;
270 /** One run's spend cap, $2 by default; staff can override it. */
271 runCapMicros: number;
272 /** Agent spend on one issue in all, $10 by default. */
273 issueCapMicros: number;
274 /** g1t's ceiling on usage not yet paid for; `UNLIMITED_MICROS` for g1t's own; 0 for free. */
275 ceilingMicros: number;
276 /** Usage not yet paid for this month, prepayment taken off. */
277 exposureMicros: number;
278 /** Why new compute is paused, for the owner; null when it is not. */
279 paused: string | null;
280 /** What open reservations hold now. */
281 heldMicros?: number;
282 /** Paid in advance and not used yet. */
283 prepaidMicros?: number;
284 /** The plan's included usage each month, and what of it is used. */
285 includedMicros?: number;
286 includedUsedMicros?: number;
287 /** How far back the audit log can be read and exported, and what is kept: the plan's days, or what g1t staff set for the account. */
288 auditRetentionDays: number;
289 /** Whether `auditRetentionDays` is what staff set for the account rather than the plan's. */
290 auditRetentionCustom?: boolean;
291 /** Private repository storage free for every workspace: past it, the plan pays and a free workspace's pushes stop. */
292 freePrivateStorageBytes: number;
293 /** The last daily measure of the workspace's private repositories (a lower bound). */
294 privateStorageBytes: number;
295 /** On a paid plan: package storage past the free amounts is charged, never refused. */
296 hasPlan?: boolean;
297 /** Package storage free for every workspace (public, and private): past it a free workspace's pushes are refused. */
298 packagePublicFreeBytes?: number;
299 packagePrivateFreeBytes?: number;
300 /** What g1t's open-source pool paid for the workspace this month. */
301 ossPaidMicros: number;
302 /** Deploy build time this month, every second of it metered. */
303 buildSecondsUsed?: number;
304 /** Git operations this month, and how many are free for every workspace. */
305 gitOperations?: number;
306 gitOperationsIncluded?: number;
307 /** The smallest amount a card is charged when a month closes. */
308 minChargeMicros: number;
309 /** A spend spike waiting for an owner, or decided. */
310 spike?: Spike | null;
311 /** Where usage stands against what is included and the limits, from 50%. */
312 alerts?: UsageAlert[];
313};
314
315/** A hold on a start's estimated cost, as billing answers it (`Reservation` in `./compute`, and more). */
316export type ReservationHeld = Reservation & {
317 /** What is held, at cost; may be less than the estimate for a free workspace's last bit of trial. */
318 heldMicros?: number;
319 /** When the hold lapses if never settled. */
320 expiresAt?: string;
321};
322
323/** A request to g1t: a higher limit, or help with usage past what was meant. */
324export type LimitRequest = {
325 id: string;
326 workspace: string;
327 kind: "limit" | "overage" | string;
328 amountMicros: number;
329 reason: string;
330 expectedMonthlyMicros: number;
331 status: "open" | "approved" | "declined" | string;
332 decidedMicros?: number | null;
333 decidedBy?: string | null;
334 /** The answer, as the owner sees it. */
335 answer?: string | null;
336 createdBy: string;
337 createdAt: string;
338 decidedAt?: string | null;
339};
340
341/** What staff see beside a request. */
342export type WorkspaceHistory = {
343 plan: PlanKind | null;
344 months: MonthFigures[];
345 paidClearedMicros: number;
346 payments: number;
347 disputes: number;
348 declines: number;
349 firstSeen: string | null;
350 ceilingMicros: number | null;
351 maxCeilingMicros: number | null;
352 spendLimitMicros: number | null;
353 lastHourMicros: number;
354 averageHourMicros: number;
355 lastDayMicros: number;
356};
357
358export type LimitRequestReview = { request: LimitRequest; history: WorkspaceHistory };
359
360/** What a one-time goodwill credit comes to: the margin on the overage, always, plus its cost up to the cap. */
361export type Goodwill = {
362 overageMicros: number;
363 marginMicros: number;
364 costMicros: number;
365 creditMicros: number;
366 absorbedMicros: number;
367};
368
369/** A workspace whose month went well past its usual, or hit a spike. */
370export type Overage = {
371 workspace: string;
372 plan: PlanKind;
373 typicalMonthMicros: number;
374 thisMonthMicros: number;
375 costMicros: number;
376 marginMicros: number;
377 spike: Spike | null;
378 topEntries: LedgerEntry[];
379 goodwill: Goodwill;
380 goodwillAvailable: boolean;
381 lastGoodwillAt: string | null;
382 request: LimitRequest | null;
383};
384
385/** One workspace's recent pace. */
386export type Velocity = {
387 workspace: string;
388 plan: PlanKind;
389 lastHourMicros: number;
390 averageHourMicros: number;
391 lastDayMicros: number;
392 thisMonthMicros: number;
393 ratio: number;
394 spike: Spike | null;
395 firstSeen: string | null;
396};
397
398/** g1t's capped budgets for free usage this month. */
399export type Pools = {
400 month: string;
401 trialGrantedMicros: number;
402 trialPoolMicros: number;
403 trialGrants: number;
404 ossUsedMicros: number;
405 ossPoolMicros: number;
406 ossRepoMicros: number;
407};
408
409export type AccountSummary = {
410 account: PayingAccount;
411 limit: Limit;
412 chargedMicros: number;
413 costMicros: number;
414 paidMicros: number;
415 /** The same figures for each of the account's workspaces that has any. */
416 byWorkspace: WorkspaceFigures[];
417 /** The last six months, oldest first. */
418 months?: MonthFigures[];
419};
420
421/** One workspace's share of an `AccountSummary`. */
422export type WorkspaceFigures = { workspace: string; chargedMicros: number; costMicros: number; paidMicros: number };
423
424export type StripeStatus = {
425 /** `test` or `live`, from the key; `off` without one. */
426 mode: "test" | "live" | "off" | string;
427 /** Whether `STRIPE_WEBHOOK_SECRET` is set, so events can be checked. */
428 secretSet: boolean;
429 /** The destination at billing's address in Stripe, as Stripe has it. */
430 webhook: { url: string; endpointId: string; status: "enabled" | "disabled" | string; events: string[]; createdAt: string } | null;
431 /** Events billing handles that the destination does not send. */
432 missingEvents: string[];
433 recentEvents: { id: string; kind: string; outcome: string; receivedAt: string }[];
434 error: string | null;
435};
436
437/** An enterprise's invoice: one line per workspace, paid on Stripe's page. */
438export type EnterpriseInvoice = {
439 invoiceId: string;
440 hostedUrl: string | null;
441 amountMicros: number;
442 status: "open" | "paid" | "overdue" | "void" | string;
443 period: string;
444 lines: { workspace: string; amountMicros: number }[];
445 createdAt: string;
446};
447
448/** A workspace's invoice: monthly, or when charged near its limit. Itemised, in Stripe's billing page. */
449export type WorkspaceInvoice = {
450 invoiceId: string;
451 workspace: string;
452 reason: "month" | "threshold" | string;
453 period: string;
454 amountMicros: number;
455 status: "paid" | "open" | "failed" | "void" | string;
456 hostedUrl: string | null;
457 pdfUrl: string | null;
458 lines: { description: string; amountMicros: number }[];
459 createdAt: string;
460 /** The card processing fee on top of `amountMicros` when charged to a card, and the tax Stripe added once known. */
461 feeMicros?: number;
462 taxMicros?: number;
463};
464
465/** A month of the ledger, grouped by day or project, a line per kind of charge. */
466export type Statement = {
467 month: string;
468 months: string[];
469 groups: {
470 key: string;
471 label: string;
472 /** `coveredMicros`: what the plan's included usage, the trial, the open-source pool or g1t paid, not in `chargedMicros`. */
473 /** `priceMicros`: usage at its price; `discountMicros`: what the account's discount took off it. */
474 lines: {
475 kind: string;
476 count: number;
477 chargedMicros: number;
478 costMicros: number;
479 coveredMicros?: number;
480 priceMicros?: number;
481 discountMicros?: number;
482 /** On `Tax` and `Card processing fees` lines: what was paid with payments on top of what reached the balance. Never charged. */
483 passedMicros?: number;
484 }[];
485 chargedMicros: number;
486 priceMicros?: number;
487 discountMicros?: number;
488 }[];
489 totals: {
490 chargedMicros: number;
491 paidMicros: number;
492 costMicros: number;
493 entries: number;
494 /** Usage at price, and what the discount took off: charged is the price less the discount and what paid for it. */
495 priceMicros?: number;
496 discountMicros?: number;
497 /** The account's discount now, in percent; absent without one. */
498 discountPercent?: number | null;
499 /** What paid for usage before it was charged, such as "Paid by g1t's open-source pool". */
500 covered?: { source: "included" | "trial" | "oss_pool" | "given" | string; label: string; micros: number }[];
501 /** Owed when the month closed but under the minimum charge: on the next invoice. */
502 carriedMicros?: number;
503 /** Tax and card processing fees paid with the month's payments, on top of `paidMicros`. */
504 taxMicros?: number;
505 cardFeeMicros?: number;
506 };
507};
508
509export type MonthFigures = {
510 month: string;
511 /** Usage charged, after what paid for it first. */
512 chargedMicros: number;
513 /** What usage cost g1t: never a workspace's own model provider. */
514 costMicros: number;
515 paidMicros: number;
516 /** The plan's monthly price, paid. */
517 plansMicros?: number;
518 /** What g1t gave at price (internal use, trials, the open-source pool, goodwill, covered). Not margin. */
519 givenMicros?: number;
520};
521
522/** What g1t gave this month from one source. */
523export type GivenFigures = { source: "internal" | "trial" | "oss_pool" | "goodwill" | "covered" | string; label: string; micros: number; costMicros: number };
524
525/** One internal workspace's use this month, and why it is not charged. */
526export type InternalUse = { workspace: string; reason: string; costMicros: number; entries: number };
527
528export type SignalKind = "at_limit" | "near_ceiling" | "declined" | "growing" | "established" | "first_payment" | "high_spend" | "cost_over_revenue";
529
530/** Why a workspace is worth reaching out to. */
531export type Signal = {
532 workspace: string;
533 kind: SignalKind;
534 detail: string;
535 valueMicros: number;
536 stage: string | null;
537 owner: string | null;
538 nextStep?: string | null;
539 /** When the next step is due, YYYY-MM-DD. */
540 nextAt?: string | null;
541};
542
543/** One invoice g1t has sent, a workspace's or an enterprise's. */
544export type InvoiceSummary = {
545 invoiceId: string;
546 kind: "workspace" | "enterprise";
547 account: string;
548 name: string;
549 reason: string;
550 period: string;
551 amountMicros: number;
552 status: string;
553 hostedUrl: string | null;
554 createdAt: string;
555 paidAt: string | null;
556};
557
558export type SalesStage = "none" | "lead" | "contacted" | "negotiating" | "won" | "lost" | "churn_risk";
559
560export type SalesRecord = {
561 workspace: string;
562 stage: SalesStage | string;
563 owner: string | null;
564 nextStep: string | null;
565 nextAt: string | null;
566 notes: { id: string; text: string; by: string; createdAt: string }[];
567 updatedAt: string | null;
568};
569
570export type Overview = {
571 month: string;
572 months: MonthFigures[];
573 byKind: { kind: string; chargedMicros: number; costMicros: number }[];
574 payingWorkspaces: number;
575 stopped: number;
576 nearCeiling: number;
577 declined: number;
578 openInvoicesMicros: number;
579 followUpsDue: number;
580 /** g1t's capped budgets for free usage, this month. */
581 pools?: Pools | null;
582 /** Usage charged plus the plan's price paid, this month. */
583 revenueMicros?: number;
584 activePlans?: number;
585 planMrrMicros?: number;
586 /** What g1t gave this month, by source, apart from its margin. */
587 given?: GivenFigures[];
588 /** g1t's own and Flagon's workspaces: what their use cost, and why they are not charged. */
589 internal?: InternalUse[];
590 openRequests?: number;
591 overages?: number;
592 openSpikes?: number;
593};
594
595/** A customer's Stripe billing page, for staff to send them. */
596export type BillingLink = {
597 /** One-time and short-lived, signed in already. */
598 portalUrl: string;
599 /** The page's sign-in, which does not expire: the customer signs in by email. */
600 loginUrl: string | null;
601 customerEmail: string | null;
602 expiresNote: string;
603};
604
605export type AdminAction = { id: string; account: string; action: string; detail: string; by: string; createdAt: string };
606
607export type AccountDetail = {
608 summary: AccountSummary;
609 workspaces: Limit[];
610 ledger: LedgerEntry[];
611 audit: AdminAction[];
612};
613
614/** Staff-only billing, for sudo.g1t.sh. Every change names who made it. */
615export interface BillingAdminApi {
616 accounts(query?: string): Promise<AccountSummary[]>;
617 account(id: string): Promise<Result<AccountDetail>>;
618 setTerms(id: string, terms: Terms, by: string): Promise<Result<PayingAccount>>;
619 /** Team on or off without charge, and the account's share of the pools. Needs a note. */
620 setAllowances(id: string, allowances: Allowances, note: string, by: string): Promise<Result<PayingAccount>>;
621 createEnterprise(name: string, workspaces: string[], by: string): Promise<Result<PayingAccount>>;
622 attach(workspace: string, account: string | null, by: string): Promise<Result<PayingAccount>>;
623 /** Credit for a workspace: promotional, goodwill or a refund; the owners are emailed. */
624 credit(workspace: string, amountMicros: number, note: string, by: string, options?: CreditOptions): Promise<Result<LedgerEntry>>;
625 /** Every credit g1t gave, filtered, with each month's totals by kind. */
626 credits(filter?: { workspace?: string | null; kind?: CreditKind | null; month?: string | null; by?: string | null }): Promise<AdminCredits>;
627 /** What is left of a credit, taken back, with why. */
628 revokeCredit(id: string, note: string, by: string): Promise<Result<CreditGrant>>;
629 /** A test workspace's billing wiped, to start again as a new customer. Only on Stripe's test key; never comped or enterprise. Logged. */
630 resetBilling(workspace: string, confirm: string, note: string, by: string): Promise<Result<BillingReset>>;
631 /** The workspace's Stripe billing page, to send to the customer. Logged. */
632 billingLink(workspace: string, by: string): Promise<Result<BillingLink>>;
633 /** Where billing stands with Stripe; with `setup`, registers the webhook first. */
634 /** Stripe's state for billing; `fix` enables the destination and adds missing events first. */
635 stripe(fix?: boolean, by?: string): Promise<StripeStatus>;
636 /** Where an enterprise's invoices go; makes its Stripe customer. */
637 enterpriseBilling(id: string, email: string, by: string): Promise<Result<PayingAccount>>;
638 /** The enterprise's billing address and tax ID, on its Stripe customer: Stripe Tax works its invoices out from them. */
639 enterpriseAddress(id: string, address: PostalAddress, taxIdType: string | null, taxId: string | null, by: string): Promise<Result<boolean>>;
640 /** Sends an enterprise its invoice now, for what its workspaces owe. */
641 invoiceEnterprise(id: string, by: string): Promise<Result<EnterpriseInvoice>>;
642 /** Exactly these workspaces' accounts, such as one page of the list. */
643 accountsFor(workspaces: string[]): Promise<AccountSummary[]>;
644 /** Every workspace worth reaching out to, most urgent first. */
645 signals(): Promise<Signal[]>;
646 /** The business at a glance. */
647 overview(): Promise<Overview>;
648 /** A workspace's sales record. */
649 sales(workspace: string): Promise<SalesRecord>;
650 setSales(workspace: string, record: { stage: string; owner?: string | null; nextStep?: string | null; nextAt?: string | null }, by: string): Promise<Result<SalesRecord>>;
651 addNote(workspace: string, text: string, by: string): Promise<Result<SalesRecord>>;
652 /** A workspace's invoices from g1t, for staff. */
653 workspaceInvoices(workspace: string): Promise<WorkspaceInvoice[]>;
654 /** Every invoice g1t has sent, newest first. */
655 allInvoices(filter?: { status?: string; month?: string }): Promise<InvoiceSummary[]>;
656 /** Every change made in sudo and by Stripe, newest first, 100 at a time. */
657 audit(filter?: { by?: string; action?: string; before?: string }): Promise<AdminAction[]>;
658 /** Limit and overage requests, with each workspace's history; `open` by default. */
659 limitRequests(status?: "open" | "approved" | "declined" | "all"): Promise<LimitRequestReview[]>;
660 /** Approve (at the amount asked, or another) or decline; the owner is told in the app and by email. */
661 decideLimitRequest(id: string, decision: "approve" | "decline", amountMicros: number | null, note: string, by: string): Promise<Result<LimitRequest>>;
662 /** The Overages queue. */
663 overages(): Promise<Overage[]>;
664 /** A goodwill credit; no amount is the one-click credit. Larger, or a second in 12 months, needs a reason. */
665 goodwill(workspace: string, amountMicros: number | null, reason: string, by: string, day?: string | null): Promise<Result<LedgerEntry>>;
666 /** Workspaces spending in the last day, fastest first. */
667 velocity(): Promise<Velocity[]>;
668 /** Money that reached g1t outside the card pages, such as a bank transfer: entered as a payment. */
669 recordPayment(workspace: string, amountMicros: number, reference: string, note: string, by: string): Promise<Result<LedgerEntry>>;
670 /** Costs & margin: Cloudflare's bill against what g1t charged, over the last `days` (7 to 90, 30 by default). */
671 costs(days?: number): Promise<CostsReport>;
672 /** The open margin alerts, for the banner on every page. */
673 costAlerts(): Promise<MarginAlert[]>;
674 /** g1t's own spend against its caps: the daily breaker and comped budgets. */
675 spendCaps(): Promise<SpendCaps>;
676 /** Lets hosted-model runs start again for the rest of today (UTC); needs a note. */
677 liftBreaker(note: string, by: string): Promise<Result<SpendCaps>>;
678 /** Approve or reject a price proposal; a rejection needs a note. An approved rise waits out the notice period. */
679 decideProposal(id: string, decision: "approve" | "reject", note: string, by: string): Promise<Result<PriceProposal>>;
680 setCostSettings(settings: CostSettings, by: string): Promise<Result<CostSettings>>;
681 setCostMapping(mapping: CostMappingInput, by: string): Promise<Result<CostMapping>>;
682 /** Reads Cloudflare's bill and reconciles now, as the daily run does. */
683 runCosts(by: string): Promise<Result<CostsRun>>;
684}
685
686/** How much a workspace has earned g1t's trust with money. */
687export type Trust = "new" | "paid" | "established" | "reviewed" | "internal";
688
689/**
690 * How far a workspace's unpaid usage has gone this month, and where its
691 * work stops: past `ceilingMicros`, no new sandboxes, builds or app
692 * requests. Usage counts at its cost to g1t or its charge, whichever is
693 * more, so it counts while g1t is free too.
694 */
695export type Limit = {
696 workspace: string;
697 /** The account that pays: the workspace's own (`ws_<slug>`), or its enterprise's. */
698 account: string;
699 accountName: string;
700 trust: Trust;
701 exposureMicros: number;
702 /** The lower of g1t's ceiling and the owner's spend limit; null for g1t's own. */
703 ceilingMicros: number | null;
704 trustCeilingMicros: number | null;
705 spendLimitMicros: number | null;
706 state: "ok" | "warning" | "stopped";
707 message: string | null;
708 /** Charged this month: what the spend limit is measured against. */
709 spentMicros?: number;
710 /** True while the owners have not chosen a limit, so the automatic one applies: $200, or twice last month's spend. */
711 defaultSpendLimit?: boolean;
712 /** The most owners may set their own limit to without asking: the highest ceiling ever, plus what is prepaid. */
713 availableMicros?: number | null;
714 /** How the ceiling grows from here, in a sentence. */
715 growth?: string | null;
716 /** Paid in advance and not used yet; raises what can be used before work stops by as much. */
717 prepaidMicros?: number;
718 /** The highest ceiling the workspace has had. */
719 maxCeilingMicros?: number | null;
720 /** The most owners may raise the limit to themselves, once: twice the highest ceiling. Null once used. */
721 raiseOnceMicros?: number | null;
722 /** When the one-time raise was used. */
723 raisedAt?: string | null;
724 /** A paid workspace's first billing cycle, on the starting ceiling. */
725 firstMonth?: boolean;
726 /** The budget's alerts, in percent of the spend limit: some of 50, 75, 90 and 100. */
727 alertLevels?: number[];
728 /** Whether usage pauses at the spend limit (the default); off, it only alerts. */
729 pauseAtLimit?: boolean;
730 /** An HTTPS address told of each budget alert. */
731 budgetWebhook?: string | null;
732};
733
734/** One metered unit: what it costs g1t and what it is sold at; the price follows the cost. */
735export type Price = {
736 meter:
737 | "sandbox_second"
738 | "build_second"
739 | "app_requests"
740 | "app_cpu"
741 | "app_month"
742 | "custom_domain_month"
743 | "private_storage"
744 | "embedding_tokens"
745 | "scan_cpu"
746 | "scan_rows"
747 | string;
748 title: string;
749 unit: string;
750 costMicros: number;
751 markupPercent: number;
752 priceMicros: number;
753 /** `list`: Cloudflare's published price. `cloudflare`: measured from Cloudflare's bill. */
754 source: "list" | "cloudflare" | string;
755 checkedAt: string | null;
756 updatedAt: string;
757};
758
759export type PriceChange = {
760 meter: string;
761 oldCostMicros: number;
762 newCostMicros: number;
763 markupPercent: number;
764 /** The markup before, when the change was to the markup rather than the cost. */
765 oldMarkupPercent?: number;
766 reason: string;
767 createdAt: string;
768 /** When a change still to come takes effect: a rise is announced before it is charged. */
769 effectiveAt?: string;
770};
771
772export type PriceBook = {
773 prices: Price[];
774 changes: PriceChange[];
775 modelMarginPercent: number;
776 /** Every plan, as sold now. */
777 plans?: FeaturePlan[];
778 /** What is free, and the capped budgets that pay for it. */
779 free?: FreeTier | null;
780};
781
782/** One kind of meter's usage this month, from `usage_meters`. */
783export type MeterUsage = {
784 /** `agents`, `builds`, `requests`, `domains`, `git_storage` or `search_scans`. */
785 key: string;
786 label: string;
787 /** At price (cost plus 20%, on the account's terms), before what paid for it. */
788 micros: number;
789 /** How much, when it is known: `12 runs`, `41 build minutes`. */
790 quantity?: string | null;
791};
792
793/** What g1t gives without a plan; each is paid for by a capped budget. */
794export type FreeTier = {
795 /** Each new workspace's trial credit, once. */
796 trialWorkspaceMicros: number;
797 /** Trial grants each month, in all; new trials wait when it is spent. */
798 trialMonthlyPoolMicros: number;
799 /** g1t's open-source pool each month, and any one repository's share. */
800 ossPoolMicros: number;
801 ossRepoMicros: number;
802 /** Private repository storage free for every workspace. Past it, the plan pays; a free workspace's pushes stop. */
803 freePrivateStorageBytes: number;
804 /** Days of audit log a free workspace keeps. */
805 auditRetentionDays: number;
806 /** Days of audit log the g1t plan keeps, and g1t's own and enterprise workspaces; longer by arrangement. */
807 planAuditRetentionDays?: number;
808 /** The smallest amount a card is charged when a month closes; less carries over. */
809 minChargeMicros: number;
810 /** Git operations free for every workspace each month. Past it, the plan pays; a free workspace is slowed down. */
811 gitOperationsIncluded?: number;
812 /** A new paid workspace's ceiling in its first month. */
813 paidStartCeilingMicros?: number;
814 /** The most a one-click goodwill credit can cost g1t. */
815 overageForgiveCostMicros?: number;
816};
817
818/**
819 * A workspace's trial credit: one grant per workspace, made the first time
820 * it uses something, out of a pool that resets each calendar month. Mirrors
821 * `Trial` in `crates/contracts/src/billing.rs`.
822 */
823export type Trial = {
824 open: boolean;
825 usedMicros: number;
826 limitMicros: number;
827 /** No longer used: trials do not end on a date. */
828 endsAt: string | null;
829 /** Why it is closed: `off`, `used` (this workspace's grant is spent) or `pool` (this month's are given out). */
830 reason: "off" | "ended" | "used" | "pool" | null;
831 /** Whether the workspace has its grant already. */
832 granted?: boolean;
833 /** With `pool`: when new trials start again, the first of next month. */
834 waitsUntil?: string | null;
835};
836
837/**
838 * What a workspace pays a monthly price for: the g1t plan (`plan`), and the
839 * Security and quality activation (`security`), sold on its own. Deployments
840 * are part of the plan; `has_feature` for `deployments` answers whether the
841 * workspace has the plan. Mirrors `Feature` in `crates/contracts/src/billing.rs`.
842 */
843export type Feature = "plan" | "deployments" | "security";
844
845/**
846 * What deployments cost g1t, in millionths of a dollar: fallbacks for when
847 * billing's price book cannot be read. Not an allowance: on the plan every
848 * unit is metered from the first, at cost plus 20%, and drawn from the
849 * plan's included usage first. Projects, previews and the apps behind them
850 * are not metered at all. Mirrors `deployment_costs`.
851 */
852export const DEPLOYMENT_COSTS = {
853 microsPerMillionRequests: 300_000,
854 microsPerMillionCpuMs: 20_000,
855 /** One second of a build's sandbox: a fallback; billing charges the price book's `build_second`. */
856 microsPerBuildSecond: 15,
857 /** One custom domain for a month. */
858 microsPerDomainMonth: 100_000,
859} as const;
860
861export type FeaturePlan = {
862 feature: Feature;
863 title: string;
864 /** Charged every month while the plan is on, in cents, excluding tax. */
865 monthlyCents: number;
866 /** The card processing fee on top each month, in cents (0 when off), excluding tax. */
867 cardFeeCents?: number;
868 /** What the price includes, one line each. */
869 includes: string[];
870 /** How usage past the allowance is charged. */
871 overage: string;
872};
873
874export type SubscriptionStatus = "active" | "canceling" | "past_due" | "canceled";
875
876export type Subscription = {
877 feature: Feature;
878 status: SubscriptionStatus;
879 /** RFC 3339: when the period paid for ends. */
880 periodEnd: string | null;
881 startedBy: string;
882 startedAt: string;
883};
884
885/** A feature as a workspace sees it. */
886export type FeatureState = {
887 plan: FeaturePlan;
888 subscription: Subscription | null;
889 /** Whether the feature works for the workspace now. */
890 on: boolean;
891 /** On without a plan: comped terms, or given by g1t. Nothing to pay or turn off. */
892 included?: boolean;
893};
894
895export interface BillingApi {
896 status(): Promise<BillingStatus>;
897 /** Members of the workspace only. */
898 account(workspace: string, viewer: Viewer): Promise<Result<BillingAccount>>;
899 /** Newest first. Members of the workspace only. */
900 ledger(workspace: string, viewer: Viewer): Promise<Result<LedgerEntry[]>>;
901 /** Credits from g1t, newest first, with what is left of each. Members only. */
902 credits(workspace: string, viewer: Viewer): Promise<Result<Credits>>;
903 /** A month of the ledger, grouped by `day` (default) or `project`. Members only. */
904 statement(workspace: string, viewer: Viewer, month?: string | null, group?: "day" | "project"): Promise<Result<Statement>>;
905 /** One statement line's entries, 50 at a time; `before` is the last id seen. */
906 statementEntries(
907 workspace: string,
908 viewer: Viewer,
909 filter: { month: string; kind: string; day?: string | null; project?: string | null; before?: string | null },
910 ): Promise<Result<LedgerEntry[]>>;
911 /** What the workspace's agents cost since `since`, broken down. Members only. */
912 usage(workspace: string, viewer: Viewer, since: string): Promise<Result<Usage>>;
913 /**
914 * The model tokens the workspace's runs used, day by day over the last
915 * `days` (42, at most 366), for everyone or for one `person`. Members
916 * only; a member may ask only for themselves, an owner for anyone.
917 */
918 tokenUsage(workspace: string, viewer: User, options?: { person?: string; days?: number }): Promise<Result<TokenUsage>>;
919 /**
920 * What one model answer used, added to its run's count for the day. The
921 * model proxy sends it; for usage views only, as runs are priced from AI
922 * Gateway. False when there was nothing to count.
923 */
924 recordTokens(usage: {
925 workspace: string;
926 /** The model session's id, one per run. */
927 session: string;
928 /** The person the run is for, by username. */
929 person?: string | null;
930 model: string;
931 tier?: "small" | "large" | "frontier" | null;
932 input: number;
933 output: number;
934 cacheRead: number;
935 cacheWrite: number;
936 }): Promise<Result<boolean>>;
937 /**
938 * Prepays usage ($25 at least) and returns the page to send the person to:
939 * by card with 3-D Secure, or by bank transfer from $1,000. Owners only.
940 * The payment's id comes back to `returnUrl` as `session`.
941 */
942 checkout(
943 actor: User,
944 workspace: string,
945 amountCents: number,
946 returnUrl: string,
947 method?: "card" | "bank_transfer",
948 ): Promise<Result<{ url: string }>>;
949 /**
950 * Stripe's hosted billing page for the workspace: card, invoices, billing
951 * email and address. g1t never handles card numbers. Owners only.
952 */
953 billingPortal(actor: User, workspace: string, returnUrl: string): Promise<Result<{ url: string }>>;
954 /** Credits a payment once the processor says it was made. Safe to repeat. */
955 confirm(workspace: string, viewer: Viewer, session: string): Promise<Result<BillingAccount>>;
956 /**
957 * Whether a workspace may start an agent now, asked before anything is
958 * opened for it. A failure, with the reason to show, when it has no credit.
959 */
960 canStart(workspace: string): Promise<Result<boolean>>;
961 /** A workspace's free allowance on g1t's hosted models; `exempt` are open to them anyway. */
962 trial(workspace: string, exempt: string[]): Promise<Trial>;
963 /**
964 * Asks whether a workspace may start an agent and opens the run it will be
965 * charged for. Null when billing is off; a failure when there is no credit.
966 */
967 /** Every paid feature and the workspace's plan for each. Members only. */
968 features(workspace: string, viewer: Viewer): Promise<Result<FeatureState[]>>;
969 /**
970 * Starts the card page for a feature's monthly plan. Owners only. The
971 * page's id comes back to `returnUrl` as `session`.
972 */
973 subscribe(actor: User, workspace: string, feature: Feature, returnUrl: string): Promise<Result<{ url: string }>>;
974 /** Turns the feature on once the plan is paid for. Safe to repeat. */
975 confirmSubscription(workspace: string, viewer: Viewer, session: string): Promise<Result<FeatureState>>;
976 /** Ends a plan at the end of its period, or (`resume`) takes that back. Owners only. */
977 cancelSubscription(actor: User, workspace: string, feature: Feature, resume?: boolean): Promise<Result<FeatureState>>;
978 /** Which of the workspaces are free (on no paid plan); none where payments are not set up. */
979 freeWorkspaces(workspaces: string[]): Promise<string[]>;
980 /** Whether a feature works for a workspace now; a failure with the reason when not. */
981 hasFeature(workspace: string, feature: Feature): Promise<Result<boolean>>;
982 /**
983 * Usage past a plan's allowance, charged from credit at cost plus the
984 * margin, once per `reference`. False if it was charged before.
985 */
986 chargeFeature(charge: {
987 workspace: string;
988 feature: Feature;
989 costMicros: number;
990 description: string;
991 repo?: string | null;
992 reference: string;
993 /** For a build: how long it ran, so the plan's included build time pays for what it can. */
994 buildSeconds?: number | null;
995 }): Promise<Result<boolean>>;
996 /**
997 * What a source cost g1t so far this month, so the workspace's limit
998 * counts it now. Replaces the last report. Billing charges `context`
999 * and `security` itself once the month is over; `deployments` charges
1000 * its own.
1001 */
1002 notePending(
1003 workspace: string,
1004 source: "deployments" | "domains" | "context" | "security",
1005 costMicros: number,
1006 /** How much of it, for the Billing page: `1.2 million requests and 3.4 million CPU ms`. */
1007 detail?: string | null,
1008 ): Promise<boolean>;
1009 /**
1010 * This month's usage, one line per kind of meter, at what it is charged
1011 * before the plan's included usage or a pool paid for it. Members only.
1012 */
1013 usageMeters(workspace: string, viewer: Viewer): Promise<Result<MeterUsage[]>>;
1014 /** What the workspace may do now: its plan, caps, pause, trial, and what the plan gives it. */
1015 entitlements(workspace: string): Promise<Entitlements>;
1016 /**
1017 * Holds a start's estimated cost before the work starts. A failure's code says why not:
1018 * `paused`, `limit`, `not_paid`, `trial_used` or `oss_pool_empty`, with a message for the owner.
1019 */
1020 reserve(reservation: {
1021 workspace: string;
1022 repo: RepoPath;
1023 public: boolean;
1024 kind: ComputeKind;
1025 /** The most the work is expected to cost g1t, before the margin. */
1026 estimateMicros: number;
1027 }): Promise<Result<ReservationHeld>>;
1028 /** Releases a reservation's hold with what the work cost g1t, before the margin. Safe to repeat. */
1029 settle(reservationId: string, actualMicros: number): Promise<Result<boolean>>;
1030 /** Stripe's page to save and verify a card (3-D Secure, never charged). Owners only. */
1031 cardCheck(actor: User, workspace: string, returnUrl: string): Promise<Result<{ url: string }>>;
1032 /** Records the card check once Stripe says it passed, and grants the trial if it can. Safe to repeat. */
1033 confirmCardCheck(workspace: string, viewer: Viewer, session: string): Promise<Result<Entitlements>>;
1034 /** An owner asks for a higher limit, or for help with usage past what was meant. */
1035 requestLimit(
1036 actor: User,
1037 workspace: string,
1038 request: { kind: "limit" | "overage"; amountMicros: number; reason: string; expectedMonthlyMicros: number },
1039 ): Promise<Result<LimitRequest>>;
1040 /** The workspace's requests and their answers, newest first. Members only. */
1041 limitRequests(workspace: string, viewer: Viewer): Promise<Result<LimitRequest[]>>;
1042 /**
1043 * The owners' own caps on agents: one run's spend ($0.10 to $100) and one issue's ($1 to $1,000).
1044 * Null goes back to the default ($2 and $10). A cap staff set wins. Owners only.
1045 */
1046 setCaps(actor: User, workspace: string, caps: { runCapMicros: number | null; issueCapMicros: number | null }): Promise<Result<Entitlements>>;
1047 /** An owner's answer to a spend spike: keep going for 24 hours, or stop. */
1048 confirmSpike(actor: User, workspace: string, keepGoing: boolean): Promise<Result<Entitlements>>;
1049 /** Every metered price and the recent changes. Public. */
1050 prices(): Promise<PriceBook>;
1051 /** A workspace's limit, for its members. */
1052 limit(workspace: string, viewer: Viewer): Promise<Result<Limit>>;
1053 /** The same, for the services that enforce it. */
1054 checkLimit(workspace: string): Promise<Result<Limit>>;
1055 /**
1056 * The owners' own monthly limit, up to what is available; null goes back
1057 * to the default, and `useFullLimit` uses everything available. Owners only.
1058 */
1059 setSpendLimit(
1060 actor: User,
1061 workspace: string,
1062 spendLimitMicros: number | null,
1063 useFullLimit?: boolean,
1064 /** Use the one-time raise: up to twice the highest ceiling, once per workspace. */
1065 raiseOnce?: boolean,
1066 ): Promise<Result<Limit>>;
1067 /** The workspace's invoices from g1t, newest first. Members only. */
1068 invoices(workspace: string, viewer: Viewer): Promise<Result<WorkspaceInvoice[]>>;
1069 /**
1070 * How long a sandbox ran for a workspace, reported when it stops. Its
1071 * cost is recorded and every second is charged, from the first. False if
1072 * `reference` was recorded before.
1073 */
1074 recordSandbox(usage: {
1075 workspace: string;
1076 seconds: number;
1077 description: string;
1078 repo?: string | null;
1079 reference: string;
1080 /** What ran; checks, workflows and the merge queue on public repositories may use the open-source pool. */
1081 kind?: ComputeKind | null;
1082 /** vCPU-seconds used, when the sandbox can tell: the run is priced on its own CPU. */
1083 cpuSeconds?: number | null;
1084 /** The reservation it started under, settled with this cost. */
1085 reservationId?: string | null;
1086 /** It ran on one of the workspace's self-hosted runners: its minutes go on usage at $0. */
1087 selfHosted?: boolean;
1088 /** The machine it ran on, by label (`g1t-4core`); absent, the standard one. */
1089 instance?: string | null;
1090 }): Promise<Result<boolean>>;
1091 startRun(run: {
1092 workspace: string;
1093 repo: RepoPath;
1094 number: number;
1095 task: string;
1096 model: string;
1097 /** `workspace` when the run uses the workspace's own model provider. */
1098 billedTo?: "g1t" | "workspace";
1099 /**
1100 * The model session's id: the run is settled at AI Gateway's price by
1101 * it, and on the workspace's own provider its tokens are counted under
1102 * it for the agent rate.
1103 */
1104 session?: string | null;
1105 /** The tier g1t routed the run to: `small`, `large` or `frontier`. */
1106 tier?: "small" | "large" | "frontier" | null;
1107 }): Promise<Result<RunTicket | null>>;
1108 /** Usage over a range of days (`YYYY-MM-DD`, both included), at price, by product, meter, project and day. Members only. */
1109 usageReport(
1110 workspace: string,
1111 viewer: Viewer,
1112 range: { from: string; until: string; products?: string[]; projects?: string[] },
1113 ): Promise<Result<UsageReport>>;
1114 /** The workspace's prepaid AI credit, auto-reload and prices. Members only. */
1115 aiCredit(workspace: string, viewer: Viewer): Promise<Result<AiCredit>>;
1116 /** Stripe's page to buy AI credit ( to ,000, the card fee on its own line). Owners only. The page's id comes back to `returnUrl` as `ai_credit`. */
1117 buyAiCredit(actor: User, workspace: string, amountCents: number, returnUrl: string): Promise<Result<{ url: string }>>;
1118 /** Credits a purchase once Stripe says it was paid, once. Safe to repeat. */
1119 confirmAiCredit(workspace: string, viewer: Viewer, session: string): Promise<Result<AiCredit>>;
1120 /** Auto-reload's settings. Owners only. */
1121 setAiReload(
1122 actor: User,
1123 workspace: string,
1124 reload: { enabled: boolean; thresholdMicros: number; targetMicros: number; monthlyMaxMicros: number },
1125 ): Promise<Result<AiCredit>>;
1126 /** The monthly budget: the spend limit, its alerts, whether usage pauses at 100%, and a webhook. Owners only. */
1127 setBudget(
1128 actor: User,
1129 workspace: string,
1130 budget: { amountMicros: number | null; alerts: number[]; pauseAtLimit: boolean; webhook: string | null; keepLimit?: boolean },
1131 ): Promise<Result<Limit>>;
1132 /** Invoice details from the Stripe customer, the default payment method, invoices and the next invoice. Members only. */
1133 billingDetails(workspace: string, viewer: Viewer): Promise<Result<BillingDetails>>;
1134 /** Saves invoice details on the Stripe customer; absent fields stay, empty clears. Owners only. */
1135 setBillingDetails(actor: User, workspace: string, details: BillingDetailsInput): Promise<Result<BillingDetails>>;
1136}
1137
1138
1139/** One slice of usage: what it was for, what it cost, how many runs. */
1140export type UsageSlice = { key: string; micros: number; runs: number };
1141
1142/** The model tokens runs used over a window of days. */
1143export type TokenUsage = {
1144 /** `YYYY-MM-DD`, the first day counted. */
1145 since: string;
1146 /** The window's length: 42 unless asked, 366 at most. */
1147 days: number;
1148 /** Null for the whole workspace. */
1149 person: string | null;
1150 totalTokens: number;
1151 inputTokens: number;
1152 outputTokens: number;
1153 cacheReadTokens: number;
1154 cacheWriteTokens: number;
1155 /** What those runs were charged, as `usage` measures it. */
1156 costMicros: number;
1157 /** Days in the window with any tokens. */
1158 activeDays: number;
1159 /** Every day in the window, oldest first, zeros included. */
1160 byDay: { day: string; tokens: number }[];
1161};
1162
1163/** What a workspace's agents cost over a period. */
1164export type Usage = {
1165 since: string;
1166 /** Charged, including g1t's margin. */
1167 spentMicros: number;
1168 /** What g1t's usage came to at price, less what was charged: the plan's included usage, the trial, a pool or a free period paid it. Usage at price is `spentMicros` plus this. */
1169 coveredMicros?: number;
1170 /** What the account's discount took off the price; usage at price is spent + covered + this. */
1171 discountMicros?: number;
1172 /** The account's discount now, in percent; with one, the slices are at price. */
1173 discountPercent?: number | null;
1174 /** Usage at price: spent + covered + discount, from the same ledger lines. The one usage figure every page shows. */
1175 priceMicros?: number;
1176 /** What g1t's model provider charged, before the margin. */
1177 costMicros: number;
1178 /** What runs on the workspace's own provider cost there, estimated. Not charged by g1t. */
1179 providerMicros: number;
1180 /** What the runs used, at cost: g1t's models and the workspace's own provider together. */
1181 usedMicros: number;
1182 /** g1t charges nothing for now; the slices then measure usage at cost. */
1183 free: boolean;
1184 runs: number;
1185 /** Spend per day and task, keyed `YYYY-MM-DD/task`. */
1186 byDay: UsageSlice[];
1187 byTask: UsageSlice[];
1188 byRepo: UsageSlice[];
1189 /** Keyed `namespace/name#number`. */
1190 byPull: UsageSlice[];
1191 byModel: UsageSlice[];
1192 /** Credit bought in the period. */
1193 addedMicros: number;
1194};
1195
1196/** One of g1t's products (a "bucket") on one day. Money in micros. */
1197export type CostDay = { day: string; bucket: string; cfCostMicros: number; ownCostMicros: number; valueMicros: number; cashMicros: number };
1198
1199/** One product over the range: what customers were charged at price against what it cost. */
1200export type ProductMargin = {
1201 bucket: string;
1202 title: string;
1203 /** Cloudflare's bill, or g1t's own figure where Cloudflare does not bill it (`costSource`). */
1204 costMicros: number;
1205 cfCostMicros: number;
1206 ownCostMicros: number;
1207 valueMicros: number;
1208 marginMicros: number;
1209 marginPercent: number | null;
1210 costSource: "cloudflare" | "ledger" | string;
1211 /** Running g1t, paid for by the plan. */
1212 overhead: boolean;
1213};
1214
1215/** All of g1t: money in (usage and the plan) against every cost. */
1216export type OverallMargin = {
1217 usageMicros: number;
1218 plansMicros: number;
1219 costMicros: number;
1220 marginMicros: number;
1221 marginPercent: number | null;
1222 /** Of costMicros, what went on usage g1t gave away on purpose: comped workspaces, free periods, the trial and the open-source pool. */
1223 givenMicros?: number;
1224 /** Money in against costMicros - givenMicros. */
1225 soldMarginMicros?: number;
1226 soldMarginPercent?: number | null;
1227 /** Usage sold: usageMicros against what that usage cost, less what was given. */
1228 usageCostMicros?: number;
1229 usageMarginMicros?: number;
1230 usageMarginPercent?: number | null;
1231 /** Running g1t: plansMicros against the platform's cost, less its given share. */
1232 runningCostMicros?: number;
1233 /** Cost no mapping names, less its given share. */
1234 unmappedCostMicros?: number;
1235 /** givenMicros by why. Free is free periods, free allowances and overruns g1t covered. */
1236 givenCompedMicros?: number;
1237 givenFreeMicros?: number;
1238 givenTrialMicros?: number;
1239 givenPoolMicros?: number;
1240 /** What discounts on an account's terms took below cost plus the margin: given, not margin lost. */
1241 givenDiscountMicros?: number;
1242 /** Credits from g1t spent on usage, by kind: given, never money in. Refunds come off money in instead. */
1243 givenCreditPromotionalMicros?: number;
1244 givenCreditGoodwillMicros?: number;
1245 /** Credits over the range: given (every kind), spent on usage, and refunds' money given back. */
1246 creditsGivenMicros?: number;
1247 creditsUsedMicros?: number;
1248 creditsRefundedMicros?: number;
1249 /** costMicros by who g1t pays: Cloudflare's bill (billed, after included allowances) and model providers (tokens, not on Cloudflare's bill). */
1250 /** What the plan's included usage paid for, at price: money in for usage, paid out of plansMicros. */
1251 includedMicros?: number;
1252 cloudflareCostMicros?: number;
1253 modelsCostMicros?: number;
1254 /** Tax collected with payments over the range, net of refunds: owed to tax authorities, never cash or revenue. */
1255 taxCollectedMicros?: number;
1256 /** Card processing fees passed on with card payments, net of refunds: they pay Stripe's fee, not revenue. */
1257 cardFeesMicros?: number;
1258};
1259
1260/** A count, cost or leak that does not add up. */
1261export type CostDrift = {
1262 bucket: string;
1263 title: string;
1264 kind: "count" | "cost" | "leak" | string;
1265 ours: number;
1266 cloudflare: number;
1267 deltaPercent: number | null;
1268 detail: string;
1269 foundAt: string;
1270};
1271
1272export type MarginAlert = {
1273 id: string;
1274 kind: "margin" | "overall" | "leak" | "drift" | "workspace" | string;
1275 /** The product, or the workspace. */
1276 subject: string;
1277 detail: string;
1278 since: string;
1279 openedAt: string;
1280 emailedAt: string | null;
1281};
1282
1283/** A change to a price, measured from what Cloudflare charged. */
1284export type PriceProposal = {
1285 id: string;
1286 meter: string;
1287 title: string;
1288 unit: string;
1289 currentCostMicros: number;
1290 proposedCostMicros: number;
1291 changePercent: number;
1292 markupPercent: number;
1293 reason: string;
1294 source: "keeper" | "reconciler" | string;
1295 /** Far off the current cost: look before approving. */
1296 suspect: boolean;
1297 status: "open" | "applied" | "approved" | "rejected" | "superseded" | string;
1298 createdAt: string;
1299 decidedAt: string | null;
1300 decidedBy: string | null;
1301 note: string | null;
1302 effectiveAt: string | null;
1303};
1304
1305/** One version of one meter's price; never changed once written. */
1306export type PriceVersion = {
1307 id: string;
1308 meter: string;
1309 version: number;
1310 costMicros: number;
1311 markupPercent: number;
1312 priceMicros: number;
1313 effectiveAt: string;
1314 reason: string;
1315 createdBy: string;
1316 appliedAt: string | null;
1317};
1318
1319/** What `resetBilling` removed. */
1320export type BillingReset = { workspace: string; rows: number; refreshed?: boolean };
1321
1322export type WorkspaceCost = { workspace: string; costMicros: number; revenueMicros: number; givenMicros?: number; internal: boolean };
1323
1324export type CostLineSummary = {
1325 product: string;
1326 meter: string;
1327 rawName: string;
1328 unit: string;
1329 source: string;
1330 quantity: number;
1331 costMicros: number;
1332 /** Absent when no mapping claims it. */
1333 bucket: string | null;
1334};
1335
1336export type CostMapping = {
1337 product: string;
1338 meter: string;
1339 bucket: string;
1340 priceMeter: string | null;
1341 ownMeter: string | null;
1342 scaleToOwn: boolean;
1343 driftPercent: number;
1344 note: string;
1345 updatedAt: string;
1346 updatedBy: string;
1347};
1348
1349export type CostMappingInput = {
1350 product: string;
1351 meter: string;
1352 bucket?: string;
1353 priceMeter?: string | null;
1354 ownMeter?: string | null;
1355 scaleToOwn?: boolean;
1356 driftPercent?: number | null;
1357 note?: string;
1358 remove?: boolean;
1359};
1360
1361export type CostSettings = {
1362 autoApply: boolean;
1363 autoApplyPercent: number;
1364 noticeDays: number;
1365 marginFloorPercent: number;
1366 alertDays: number;
1367 minDailyCostMicros: number;
1368 anomalyFactor: number;
1369 anomalyFloorMicros: number;
1370 /** Pass Stripe's card fee on as its own line when AI credit is bought by card. */
1371 cardFee: boolean;
1372};
1373
1374export type CostsReport = {
1375 configured: boolean;
1376 fetchedAt: string | null;
1377 since: string;
1378 until: string;
1379 days: CostDay[];
1380 products: ProductMargin[];
1381 overall: OverallMargin;
1382 drift: CostDrift[];
1383 alerts: MarginAlert[];
1384 proposals: PriceProposal[];
1385 versions: PriceVersion[];
1386 topWorkspaces: WorkspaceCost[];
1387 lines: CostLineSummary[];
1388 mappings: CostMapping[];
1389 settings: CostSettings;
1390 /** g1t's own spend against its two caps. */
1391 caps: SpendCaps;
1392};
1393
1394/** What g1t pays for itself, at cost, against its caps (billing's `budget`). */
1395export type SpendCaps = {
1396 /** Today (UTC), YYYY-MM-DD, and this month, YYYY-MM. */
1397 day: string;
1398 month: string;
1399 /** What g1t paid for itself today across every workspace. */
1400 todayMicros: number;
1401 /** `PLATFORM_DAILY_SPEND_CAP_MICROS`; 0: no breaker. */
1402 dailyCapMicros: number;
1403 /** New hosted-model agent runs g1t would pay for are paused. */
1404 tripped: boolean;
1405 trippedAt: string | null;
1406 liftedBy: string | null;
1407 liftedAt: string | null;
1408 liftNote: string | null;
1409 /** This month so far, by what paid: comped, trial, oss, given, unpaid. */
1410 monthBuckets: { bucket: string; title: string; micros: number }[];
1411 comped: CompedBudget[];
1412 /** Free workspaces' share of reconciled costs this month (git, storage, platform). */
1413 freeTierMicros: number;
1414 /** Cloudflare's subscriptions a month: read from Cloudflare each day, else `CLOUDFLARE_FIXED_MONTHLY_MICROS`, an estimate. */
1415 fixedMonthlyMicros: number;
1416 fixedSource?: "cloudflare" | "estimate" | string;
1417 fixedReadAt?: string | null;
1418 /** Each subscription, when read from Cloudflare. */
1419 fixedItems?: { name: string; monthlyMicros: number }[];
1420 /** Money in this month, through the last reconciled day. */
1421 revenueMicros: number;
1422};
1423
1424/** A comped account's monthly budget, at cost. */
1425export type CompedBudget = {
1426 account: string;
1427 name: string;
1428 usedMicros: number;
1429 /** 0: no budget. */
1430 ceilingMicros: number;
1431 /** `COMPED_MONTHLY_CEILING_MICROS`, not the account's own limit. */
1432 defaultCeiling: boolean;
1433 /** 50, 75, 90, 100, or 0. */
1434 level: number;
1435};
1436
1437export type CostsRun = { lines: number; days: number; proposals: number; alerts: number; problems: string[] };
1438
1439/** The product families the Usage page groups meters into, in order. */
1440export const PRODUCTS = [
1441 { key: "agent", label: "Agent" },
1442 { key: "sandboxes", label: "Sandboxes" },
1443 { key: "gateway", label: "AI Gateway" },
1444 { key: "deployments", label: "Deployments" },
1445 { key: "git_storage", label: "Git & storage" },
1446 { key: "packages", label: "Packages" },
1447 { key: "security", label: "Security & quality" },
1448 { key: "search", label: "Search" },
1449] as const;
1450
1451export type ProductKey = (typeof PRODUCTS)[number]["key"];
1452
1453/** What usage came to over a range, and what paid for it: price − discount − included − credits = charged. */
1454export type UsageTotals = {
1455 /** Usage at price, pending usage included. */
1456 priceMicros: number;
1457 discountMicros: number;
1458 /** Paid by the plan's included usage, the trial and g1t's pools. */
1459 includedMicros: number;
1460 /** Paid by AI credit and credit from g1t. */
1461 creditsMicros: number;
1462 /** Left for the workspace to pay. */
1463 chargedMicros: number;
1464 /** Metered this month, charged when it closes. */
1465 pendingMicros: number;
1466 costMicros: number;
1467};
1468
1469export type UsageDay = { day: string; product: string; micros: number };
1470
1471export type UsageAllowance = { used: number; of: number; unit: string };
1472
1473export type ProjectUsage = { project: string; micros: number; quantity: number };
1474
1475/** One meter over a range. */
1476export type MeterLine = {
1477 key: string;
1478 label: string;
1479 product: string;
1480 /** `tokens`, `seconds`, `bytes`, `operations`, `requests` or `entries`. */
1481 unit: string;
1482 quantity: number;
1483 micros: number;
1484 pendingMicros?: number;
1485 /** Every day of the range, oldest first, at price. */
1486 daily: number[];
1487 allowance?: UsageAllowance | null;
1488 byProject: ProjectUsage[];
1489 /** How the quantity is counted, when that needs saying (the agent rate's token weights). */
1490 note?: string | null;
1491};
1492
1493export type FeatureUsage = { key: string; label: string; micros: number; count: number };
1494
1495export type ProductUsage = { key: string; label: string; micros: number; meters: MeterLine[]; features?: FeatureUsage[] };
1496
1497/** The tokens one model used over a range, as the model proxy counted them. */
1498export type ModelTokens = { model: string; input: number; output: number; cacheRead: number; cacheWrite: number };
1499
1500export type UsageReport = {
1501 from: string;
1502 until: string;
1503 totals: UsageTotals;
1504 days: UsageDay[];
1505 products: ProductUsage[];
1506 projects: string[];
1507 /** Agent tokens by model over the range, most first. */
1508 models?: ModelTokens[];
1509 /** The plan's included usage this month, in micros. */
1510 included?: UsageAllowance | null;
1511 discountPercent?: number | null;
1512 aiCreditMicros: number;
1513 creditMicros: number;
1514 trialMicros?: number | null;
1515 plan: PlanKind;
1516 free: boolean;
1517};
1518
1519export type AiReload = {
1520 enabled: boolean;
1521 thresholdMicros: number;
1522 targetMicros: number;
1523 monthlyMaxMicros: number;
1524 reloadedMicros?: number;
1525 failedAt?: string | null;
1526 error?: string | null;
1527};
1528
1529export type CardFee = { on: boolean; percentMicros: number; fixedCents: number };
1530
1531/** Prepaid AI credit: what Agent and AI Gateway usage draws on. */
1532export type AiCredit = {
1533 balanceMicros: number;
1534 purchasedMicros: number;
1535 givenMicros: number;
1536 grants: CreditGrant[];
1537 /** A 100% discount pays for AI usage: nothing to buy. */
1538 freeViaDiscount: boolean;
1539 /** Invoiced after use (an enterprise). */
1540 postpaid: boolean;
1541 /** New runs on g1t's models are refused for want of credit. */
1542 blocked: boolean;
1543 canBuy: boolean;
1544 presetsCents: number[];
1545 minCents: number;
1546 maxCents: number;
1547 cardFee: CardFee;
1548 reload: AiReload;
1549 /** The agent rate per million tokens, at price. */
1550 agentRateMicros: number;
1551 modelMarkupPercent: number;
1552 gatewayMarkupPercent: number;
1553 upgradeCreditMicros: number;
1554 expiresDays: number;
1555};
1556
1557export type PostalAddress = { line1: string; line2: string; city: string; state: string; postalCode: string; country: string };
1558
1559export type PaymentMethod = {
1560 kind: string;
1561 brand?: string | null;
1562 last4?: string | null;
1563 expMonth?: number | null;
1564 expYear?: number | null;
1565};
1566
1567export type StripeInvoice = {
1568 id: string;
1569 number?: string | null;
1570 status: string;
1571 totalCents: number;
1572 currency: string;
1573 createdAt: string;
1574 description?: string | null;
1575 hostedUrl?: string | null;
1576 pdfUrl?: string | null;
1577};
1578
1579export type UpcomingInvoice = { closesAt: string; subscriptionsMicros: number; usageMicros: number; totalMicros: number };
1580
1581export type BillingDetails = {
1582 customer: boolean;
1583 email: string | null;
1584 name: string | null;
1585 address: PostalAddress | null;
1586 taxIdType: string | null;
1587 taxId: string | null;
1588 poNumber: string | null;
1589 language: string | null;
1590 paymentMethod: PaymentMethod | null;
1591 invoices: StripeInvoice[];
1592 upcoming: UpcomingInvoice;
1593 unavailable?: string | null;
1594 /** Whether Stripe Tax can place the customer from the address; without it nothing is charged. */
1595 taxLocation?: boolean;
1596 /** Set when g1t did not charge for want of a billing address. */
1597 taxAddressNeededAt?: string | null;
1598 /** Stripe's check of the tax ID: pending, verified, unverified or unavailable. */
1599 taxIdStatus?: string | null;
1600 /** none, exempt or reverse, as set at Stripe. */
1601 taxExempt?: string | null;
1602};
1603
1604export type BillingDetailsInput = {
1605 email?: string;
1606 name?: string;
1607 address?: PostalAddress;
1608 taxIdType?: string;
1609 taxId?: string;
1610 poNumber?: string;
1611 language?: string;
1612};