Skip to content
1,377 linesCodeBlameRaw
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";
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};
461
462/** A month of the ledger, grouped by day or project, a line per kind of charge. */
463export type Statement = {
464 month: string;
465 months: string[];
466 groups: {
467 key: string;
468 label: string;
469 /** `coveredMicros`: what the plan's included usage, the trial, the open-source pool or g1t paid, not in `chargedMicros`. */
470 /** `priceMicros`: usage at its price; `discountMicros`: what the account's discount took off it. */
471 lines: {
472 kind: string;
473 count: number;
474 chargedMicros: number;
475 costMicros: number;
476 coveredMicros?: number;
477 priceMicros?: number;
478 discountMicros?: number;
479 }[];
480 chargedMicros: number;
481 priceMicros?: number;
482 discountMicros?: number;
483 }[];
484 totals: {
485 chargedMicros: number;
486 paidMicros: number;
487 costMicros: number;
488 entries: number;
489 /** Usage at price, and what the discount took off: charged is the price less the discount and what paid for it. */
490 priceMicros?: number;
491 discountMicros?: number;
492 /** The account's discount now, in percent; absent without one. */
493 discountPercent?: number | null;
494 /** What paid for usage before it was charged, such as "Paid by g1t's open-source pool". */
495 covered?: { source: "included" | "trial" | "oss_pool" | "given" | string; label: string; micros: number }[];
496 /** Owed when the month closed but under the minimum charge: on the next invoice. */
497 carriedMicros?: number;
498 };
499};
500
501export type MonthFigures = {
502 month: string;
503 /** Usage charged, after what paid for it first. */
504 chargedMicros: number;
505 /** What usage cost g1t: never a workspace's own model provider. */
506 costMicros: number;
507 paidMicros: number;
508 /** The plan's monthly price, paid. */
509 plansMicros?: number;
510 /** What g1t gave at price (internal use, trials, the open-source pool, goodwill, covered). Not margin. */
511 givenMicros?: number;
512};
513
514/** What g1t gave this month from one source. */
515export type GivenFigures = { source: "internal" | "trial" | "oss_pool" | "goodwill" | "covered" | string; label: string; micros: number; costMicros: number };
516
517/** One internal workspace's use this month, and why it is not charged. */
518export type InternalUse = { workspace: string; reason: string; costMicros: number; entries: number };
519
520export type SignalKind = "at_limit" | "near_ceiling" | "declined" | "growing" | "established" | "first_payment" | "high_spend" | "cost_over_revenue";
521
522/** Why a workspace is worth reaching out to. */
523export type Signal = {
524 workspace: string;
525 kind: SignalKind;
526 detail: string;
527 valueMicros: number;
528 stage: string | null;
529 owner: string | null;
530 nextStep?: string | null;
531 /** When the next step is due, YYYY-MM-DD. */
532 nextAt?: string | null;
533};
534
535/** One invoice g1t has sent, a workspace's or an enterprise's. */
536export type InvoiceSummary = {
537 invoiceId: string;
538 kind: "workspace" | "enterprise";
539 account: string;
540 name: string;
541 reason: string;
542 period: string;
543 amountMicros: number;
544 status: string;
545 hostedUrl: string | null;
546 createdAt: string;
547 paidAt: string | null;
548};
549
550export type SalesStage = "none" | "lead" | "contacted" | "negotiating" | "won" | "lost" | "churn_risk";
551
552export type SalesRecord = {
553 workspace: string;
554 stage: SalesStage | string;
555 owner: string | null;
556 nextStep: string | null;
557 nextAt: string | null;
558 notes: { id: string; text: string; by: string; createdAt: string }[];
559 updatedAt: string | null;
560};
561
562export type Overview = {
563 month: string;
564 months: MonthFigures[];
565 byKind: { kind: string; chargedMicros: number; costMicros: number }[];
566 payingWorkspaces: number;
567 stopped: number;
568 nearCeiling: number;
569 declined: number;
570 openInvoicesMicros: number;
571 followUpsDue: number;
572 /** g1t's capped budgets for free usage, this month. */
573 pools?: Pools | null;
574 /** Usage charged plus the plan's price paid, this month. */
575 revenueMicros?: number;
576 activePlans?: number;
577 planMrrMicros?: number;
578 /** What g1t gave this month, by source, apart from its margin. */
579 given?: GivenFigures[];
580 /** g1t's own and Flagon's workspaces: what their use cost, and why they are not charged. */
581 internal?: InternalUse[];
582 openRequests?: number;
583 overages?: number;
584 openSpikes?: number;
585};
586
587/** A customer's Stripe billing page, for staff to send them. */
588export type BillingLink = {
589 /** One-time and short-lived, signed in already. */
590 portalUrl: string;
591 /** The page's sign-in, which does not expire: the customer signs in by email. */
592 loginUrl: string | null;
593 customerEmail: string | null;
594 expiresNote: string;
595};
596
597export type AdminAction = { id: string; account: string; action: string; detail: string; by: string; createdAt: string };
598
599export type AccountDetail = {
600 summary: AccountSummary;
601 workspaces: Limit[];
602 ledger: LedgerEntry[];
603 audit: AdminAction[];
604};
605
606/** Staff-only billing, for sudo.g1t.sh. Every change names who made it. */
607export interface BillingAdminApi {
608 accounts(query?: string): Promise<AccountSummary[]>;
609 account(id: string): Promise<Result<AccountDetail>>;
610 setTerms(id: string, terms: Terms, by: string): Promise<Result<PayingAccount>>;
611 /** Team on or off without charge, and the account's share of the pools. Needs a note. */
612 setAllowances(id: string, allowances: Allowances, note: string, by: string): Promise<Result<PayingAccount>>;
613 createEnterprise(name: string, workspaces: string[], by: string): Promise<Result<PayingAccount>>;
614 attach(workspace: string, account: string | null, by: string): Promise<Result<PayingAccount>>;
615 /** Credit for a workspace: promotional, goodwill or a refund; the owners are emailed. */
616 credit(workspace: string, amountMicros: number, note: string, by: string, options?: CreditOptions): Promise<Result<LedgerEntry>>;
617 /** Every credit g1t gave, filtered, with each month's totals by kind. */
618 credits(filter?: { workspace?: string | null; kind?: CreditKind | null; month?: string | null; by?: string | null }): Promise<AdminCredits>;
619 /** What is left of a credit, taken back, with why. */
620 revokeCredit(id: string, note: string, by: string): Promise<Result<CreditGrant>>;
621 /** A test workspace's billing wiped, to start again as a new customer. Only on Stripe's test key; never comped or enterprise. Logged. */
622 resetBilling(workspace: string, confirm: string, note: string, by: string): Promise<Result<BillingReset>>;
623 /** The workspace's Stripe billing page, to send to the customer. Logged. */
624 billingLink(workspace: string, by: string): Promise<Result<BillingLink>>;
625 /** Where billing stands with Stripe; with `setup`, registers the webhook first. */
626 /** Stripe's state for billing; `fix` enables the destination and adds missing events first. */
627 stripe(fix?: boolean, by?: string): Promise<StripeStatus>;
628 /** Where an enterprise's invoices go; makes its Stripe customer. */
629 enterpriseBilling(id: string, email: string, by: string): Promise<Result<PayingAccount>>;
630 /** Sends an enterprise its invoice now, for what its workspaces owe. */
631 invoiceEnterprise(id: string, by: string): Promise<Result<EnterpriseInvoice>>;
632 /** Exactly these workspaces' accounts, such as one page of the list. */
633 accountsFor(workspaces: string[]): Promise<AccountSummary[]>;
634 /** Every workspace worth reaching out to, most urgent first. */
635 signals(): Promise<Signal[]>;
636 /** The business at a glance. */
637 overview(): Promise<Overview>;
638 /** A workspace's sales record. */
639 sales(workspace: string): Promise<SalesRecord>;
640 setSales(workspace: string, record: { stage: string; owner?: string | null; nextStep?: string | null; nextAt?: string | null }, by: string): Promise<Result<SalesRecord>>;
641 addNote(workspace: string, text: string, by: string): Promise<Result<SalesRecord>>;
642 /** A workspace's invoices from g1t, for staff. */
643 workspaceInvoices(workspace: string): Promise<WorkspaceInvoice[]>;
644 /** Every invoice g1t has sent, newest first. */
645 allInvoices(filter?: { status?: string; month?: string }): Promise<InvoiceSummary[]>;
646 /** Every change made in sudo and by Stripe, newest first, 100 at a time. */
647 audit(filter?: { by?: string; action?: string; before?: string }): Promise<AdminAction[]>;
648 /** Limit and overage requests, with each workspace's history; `open` by default. */
649 limitRequests(status?: "open" | "approved" | "declined" | "all"): Promise<LimitRequestReview[]>;
650 /** Approve (at the amount asked, or another) or decline; the owner is told in the app and by email. */
651 decideLimitRequest(id: string, decision: "approve" | "decline", amountMicros: number | null, note: string, by: string): Promise<Result<LimitRequest>>;
652 /** The Overages queue. */
653 overages(): Promise<Overage[]>;
654 /** A goodwill credit; no amount is the one-click credit. Larger, or a second in 12 months, needs a reason. */
655 goodwill(workspace: string, amountMicros: number | null, reason: string, by: string, day?: string | null): Promise<Result<LedgerEntry>>;
656 /** Workspaces spending in the last day, fastest first. */
657 velocity(): Promise<Velocity[]>;
658 /** Money that reached g1t outside the card pages, such as a bank transfer: entered as a payment. */
659 recordPayment(workspace: string, amountMicros: number, reference: string, note: string, by: string): Promise<Result<LedgerEntry>>;
660 /** Costs & margin: Cloudflare's bill against what g1t charged, over the last `days` (7 to 90, 30 by default). */
661 costs(days?: number): Promise<CostsReport>;
662 /** The open margin alerts, for the banner on every page. */
663 costAlerts(): Promise<MarginAlert[]>;
664 /** g1t's own spend against its caps: the daily breaker and comped budgets. */
665 spendCaps(): Promise<SpendCaps>;
666 /** Lets hosted-model runs start again for the rest of today (UTC); needs a note. */
667 liftBreaker(note: string, by: string): Promise<Result<SpendCaps>>;
668 /** Approve or reject a price proposal; a rejection needs a note. An approved rise waits out the notice period. */
669 decideProposal(id: string, decision: "approve" | "reject", note: string, by: string): Promise<Result<PriceProposal>>;
670 setCostSettings(settings: CostSettings, by: string): Promise<Result<CostSettings>>;
671 setCostMapping(mapping: CostMappingInput, by: string): Promise<Result<CostMapping>>;
672 /** Reads Cloudflare's bill and reconciles now, as the daily run does. */
673 runCosts(by: string): Promise<Result<CostsRun>>;
674}
675
676/** How much a workspace has earned g1t's trust with money. */
677export type Trust = "new" | "paid" | "established" | "reviewed" | "internal";
678
679/**
680 * How far a workspace's unpaid usage has gone this month, and where its
681 * work stops: past `ceilingMicros`, no new sandboxes, builds or app
682 * requests. Usage counts at its cost to g1t or its charge, whichever is
683 * more, so it counts while g1t is free too.
684 */
685export type Limit = {
686 workspace: string;
687 /** The account that pays: the workspace's own (`ws_<slug>`), or its enterprise's. */
688 account: string;
689 accountName: string;
690 trust: Trust;
691 exposureMicros: number;
692 /** The lower of g1t's ceiling and the owner's spend limit; null for g1t's own. */
693 ceilingMicros: number | null;
694 trustCeilingMicros: number | null;
695 spendLimitMicros: number | null;
696 state: "ok" | "warning" | "stopped";
697 message: string | null;
698 /** Charged this month: what the spend limit is measured against. */
699 spentMicros?: number;
700 /** True while the owners have not chosen a limit, so the automatic one applies: $200, or twice last month's spend. */
701 defaultSpendLimit?: boolean;
702 /** The most owners may set their own limit to without asking: the highest ceiling ever, plus what is prepaid. */
703 availableMicros?: number | null;
704 /** How the ceiling grows from here, in a sentence. */
705 growth?: string | null;
706 /** Paid in advance and not used yet; raises what can be used before work stops by as much. */
707 prepaidMicros?: number;
708 /** The highest ceiling the workspace has had. */
709 maxCeilingMicros?: number | null;
710 /** The most owners may raise the limit to themselves, once: twice the highest ceiling. Null once used. */
711 raiseOnceMicros?: number | null;
712 /** When the one-time raise was used. */
713 raisedAt?: string | null;
714 /** A paid workspace's first billing cycle, on the starting ceiling. */
715 firstMonth?: boolean;
716};
717
718/** One metered unit: what it costs g1t and what it is sold at; the price follows the cost. */
719export type Price = {
720 meter:
721 | "sandbox_second"
722 | "build_second"
723 | "app_requests"
724 | "app_cpu"
725 | "app_month"
726 | "custom_domain_month"
727 | "private_storage"
728 | "embedding_tokens"
729 | "scan_cpu"
730 | "scan_rows"
731 | string;
732 title: string;
733 unit: string;
734 costMicros: number;
735 markupPercent: number;
736 priceMicros: number;
737 /** `list`: Cloudflare's published price. `cloudflare`: measured from Cloudflare's bill. */
738 source: "list" | "cloudflare" | string;
739 checkedAt: string | null;
740 updatedAt: string;
741};
742
743export type PriceChange = {
744 meter: string;
745 oldCostMicros: number;
746 newCostMicros: number;
747 markupPercent: number;
748 /** The markup before, when the change was to the markup rather than the cost. */
749 oldMarkupPercent?: number;
750 reason: string;
751 createdAt: string;
752 /** When a change still to come takes effect: a rise is announced before it is charged. */
753 effectiveAt?: string;
754};
755
756export type PriceBook = {
757 prices: Price[];
758 changes: PriceChange[];
759 modelMarginPercent: number;
760 /** Every plan, as sold now. */
761 plans?: FeaturePlan[];
762 /** What is free, and the capped budgets that pay for it. */
763 free?: FreeTier | null;
764};
765
766/** One kind of meter's usage this month, from `usage_meters`. */
767export type MeterUsage = {
768 /** `agents`, `builds`, `requests`, `domains`, `git_storage` or `search_scans`. */
769 key: string;
770 label: string;
771 /** At price (cost plus 20%, on the account's terms), before what paid for it. */
772 micros: number;
773 /** How much, when it is known: `12 runs`, `41 build minutes`. */
774 quantity?: string | null;
775};
776
777/** What g1t gives without a plan; each is paid for by a capped budget. */
778export type FreeTier = {
779 /** Each new workspace's trial credit, once. */
780 trialWorkspaceMicros: number;
781 /** Trial grants each month, in all; new trials wait when it is spent. */
782 trialMonthlyPoolMicros: number;
783 /** g1t's open-source pool each month, and any one repository's share. */
784 ossPoolMicros: number;
785 ossRepoMicros: number;
786 /** Private repository storage free for every workspace. Past it, the plan pays; a free workspace's pushes stop. */
787 freePrivateStorageBytes: number;
788 /** Days of audit log a free workspace keeps. */
789 auditRetentionDays: number;
790 /** Days of audit log the g1t plan keeps, and g1t's own and enterprise workspaces; longer by arrangement. */
791 planAuditRetentionDays?: number;
792 /** The smallest amount a card is charged when a month closes; less carries over. */
793 minChargeMicros: number;
794 /** Git operations free for every workspace each month. Past it, the plan pays; a free workspace is slowed down. */
795 gitOperationsIncluded?: number;
796 /** A new paid workspace's ceiling in its first month. */
797 paidStartCeilingMicros?: number;
798 /** The most a one-click goodwill credit can cost g1t. */
799 overageForgiveCostMicros?: number;
800};
801
802/**
803 * A workspace's trial credit: one grant per workspace, made the first time
804 * it uses something, out of a pool that resets each calendar month. Mirrors
805 * `Trial` in `crates/contracts/src/billing.rs`.
806 */
807export type Trial = {
808 open: boolean;
809 usedMicros: number;
810 limitMicros: number;
811 /** No longer used: trials do not end on a date. */
812 endsAt: string | null;
813 /** Why it is closed: `off`, `used` (this workspace's grant is spent) or `pool` (this month's are given out). */
814 reason: "off" | "ended" | "used" | "pool" | null;
815 /** Whether the workspace has its grant already. */
816 granted?: boolean;
817 /** With `pool`: when new trials start again, the first of next month. */
818 waitsUntil?: string | null;
819};
820
821/**
822 * What a workspace pays a monthly price for: the g1t plan (`plan`), and the
823 * Security and quality activation (`security`), sold on its own. Deployments
824 * are part of the plan; `has_feature` for `deployments` answers whether the
825 * workspace has the plan. Mirrors `Feature` in `crates/contracts/src/billing.rs`.
826 */
827export type Feature = "plan" | "deployments" | "security";
828
829/**
830 * What deployments cost g1t, in millionths of a dollar: fallbacks for when
831 * billing's price book cannot be read. Not an allowance: on the plan every
832 * unit is metered from the first, at cost plus 20%, and drawn from the
833 * plan's included usage first. Projects, previews and the apps behind them
834 * are not metered at all. Mirrors `deployment_costs`.
835 */
836export const DEPLOYMENT_COSTS = {
837 microsPerMillionRequests: 300_000,
838 microsPerMillionCpuMs: 20_000,
839 /** One second of a build's sandbox: a fallback; billing charges the price book's `build_second`. */
840 microsPerBuildSecond: 15,
841 /** One custom domain for a month. */
842 microsPerDomainMonth: 100_000,
843} as const;
844
845export type FeaturePlan = {
846 feature: Feature;
847 title: string;
848 /** Charged every month while the plan is on, in cents. */
849 monthlyCents: number;
850 /** What the price includes, one line each. */
851 includes: string[];
852 /** How usage past the allowance is charged. */
853 overage: string;
854};
855
856export type SubscriptionStatus = "active" | "canceling" | "past_due" | "canceled";
857
858export type Subscription = {
859 feature: Feature;
860 status: SubscriptionStatus;
861 /** RFC 3339: when the period paid for ends. */
862 periodEnd: string | null;
863 startedBy: string;
864 startedAt: string;
865};
866
867/** A feature as a workspace sees it. */
868export type FeatureState = {
869 plan: FeaturePlan;
870 subscription: Subscription | null;
871 /** Whether the feature works for the workspace now. */
872 on: boolean;
873 /** On without a plan: comped terms, or given by g1t. Nothing to pay or turn off. */
874 included?: boolean;
875};
876
877export interface BillingApi {
878 status(): Promise<BillingStatus>;
879 /** Members of the workspace only. */
880 account(workspace: string, viewer: Viewer): Promise<Result<BillingAccount>>;
881 /** Newest first. Members of the workspace only. */
882 ledger(workspace: string, viewer: Viewer): Promise<Result<LedgerEntry[]>>;
883 /** Credits from g1t, newest first, with what is left of each. Members only. */
884 credits(workspace: string, viewer: Viewer): Promise<Result<Credits>>;
885 /** A month of the ledger, grouped by `day` (default) or `project`. Members only. */
886 statement(workspace: string, viewer: Viewer, month?: string | null, group?: "day" | "project"): Promise<Result<Statement>>;
887 /** One statement line's entries, 50 at a time; `before` is the last id seen. */
888 statementEntries(
889 workspace: string,
890 viewer: Viewer,
891 filter: { month: string; kind: string; day?: string | null; project?: string | null; before?: string | null },
892 ): Promise<Result<LedgerEntry[]>>;
893 /** What the workspace's agents cost since `since`, broken down. Members only. */
894 usage(workspace: string, viewer: Viewer, since: string): Promise<Result<Usage>>;
895 /**
896 * The model tokens the workspace's runs used, day by day over the last
897 * `days` (42, at most 366), for everyone or for one `person`. Members
898 * only; a member may ask only for themselves, an owner for anyone.
899 */
900 tokenUsage(workspace: string, viewer: User, options?: { person?: string; days?: number }): Promise<Result<TokenUsage>>;
901 /**
902 * What one model answer used, added to its run's count for the day. The
903 * model proxy sends it; for usage views only, as runs are priced from AI
904 * Gateway. False when there was nothing to count.
905 */
906 recordTokens(usage: {
907 workspace: string;
908 /** The model session's id, one per run. */
909 session: string;
910 /** The person the run is for, by username. */
911 person?: string | null;
912 model: string;
913 tier?: "small" | "large" | null;
914 input: number;
915 output: number;
916 cacheRead: number;
917 cacheWrite: number;
918 }): Promise<Result<boolean>>;
919 /**
920 * Prepays usage ($25 at least) and returns the page to send the person to:
921 * by card with 3-D Secure, or by bank transfer from $1,000. Owners only.
922 * The payment's id comes back to `returnUrl` as `session`.
923 */
924 checkout(
925 actor: User,
926 workspace: string,
927 amountCents: number,
928 returnUrl: string,
929 method?: "card" | "bank_transfer",
930 ): Promise<Result<{ url: string }>>;
931 /**
932 * Stripe's hosted billing page for the workspace: card, invoices, billing
933 * email and address. g1t never handles card numbers. Owners only.
934 */
935 billingPortal(actor: User, workspace: string, returnUrl: string): Promise<Result<{ url: string }>>;
936 /** Credits a payment once the processor says it was made. Safe to repeat. */
937 confirm(workspace: string, viewer: Viewer, session: string): Promise<Result<BillingAccount>>;
938 /**
939 * Whether a workspace may start an agent now, asked before anything is
940 * opened for it. A failure, with the reason to show, when it has no credit.
941 */
942 canStart(workspace: string): Promise<Result<boolean>>;
943 /** A workspace's free allowance on g1t's hosted models; `exempt` are open to them anyway. */
944 trial(workspace: string, exempt: string[]): Promise<Trial>;
945 /**
946 * Asks whether a workspace may start an agent and opens the run it will be
947 * charged for. Null when billing is off; a failure when there is no credit.
948 */
949 /** Every paid feature and the workspace's plan for each. Members only. */
950 features(workspace: string, viewer: Viewer): Promise<Result<FeatureState[]>>;
951 /**
952 * Starts the card page for a feature's monthly plan. Owners only. The
953 * page's id comes back to `returnUrl` as `session`.
954 */
955 subscribe(actor: User, workspace: string, feature: Feature, returnUrl: string): Promise<Result<{ url: string }>>;
956 /** Turns the feature on once the plan is paid for. Safe to repeat. */
957 confirmSubscription(workspace: string, viewer: Viewer, session: string): Promise<Result<FeatureState>>;
958 /** Ends a plan at the end of its period, or (`resume`) takes that back. Owners only. */
959 cancelSubscription(actor: User, workspace: string, feature: Feature, resume?: boolean): Promise<Result<FeatureState>>;
960 /** Whether a feature works for a workspace now; a failure with the reason when not. */
961 hasFeature(workspace: string, feature: Feature): Promise<Result<boolean>>;
962 /**
963 * Usage past a plan's allowance, charged from credit at cost plus the
964 * margin, once per `reference`. False if it was charged before.
965 */
966 chargeFeature(charge: {
967 workspace: string;
968 feature: Feature;
969 costMicros: number;
970 description: string;
971 repo?: string | null;
972 reference: string;
973 /** For a build: how long it ran, so the plan's included build time pays for what it can. */
974 buildSeconds?: number | null;
975 }): Promise<Result<boolean>>;
976 /**
977 * What a source cost g1t so far this month, so the workspace's limit
978 * counts it now. Replaces the last report. Billing charges `context`
979 * and `security` itself once the month is over; `deployments` charges
980 * its own.
981 */
982 notePending(
983 workspace: string,
984 source: "deployments" | "domains" | "context" | "security",
985 costMicros: number,
986 /** How much of it, for the Billing page: `1.2 million requests and 3.4 million CPU ms`. */
987 detail?: string | null,
988 ): Promise<boolean>;
989 /**
990 * This month's usage, one line per kind of meter, at what it is charged
991 * before the plan's included usage or a pool paid for it. Members only.
992 */
993 usageMeters(workspace: string, viewer: Viewer): Promise<Result<MeterUsage[]>>;
994 /** What the workspace may do now: its plan, caps, pause, trial, and what the plan gives it. */
995 entitlements(workspace: string): Promise<Entitlements>;
996 /**
997 * Holds a start's estimated cost before the work starts. A failure's code says why not:
998 * `paused`, `limit`, `not_paid`, `trial_used` or `oss_pool_empty`, with a message for the owner.
999 */
1000 reserve(reservation: {
1001 workspace: string;
1002 repo: RepoPath;
1003 public: boolean;
1004 kind: ComputeKind;
1005 /** The most the work is expected to cost g1t, before the margin. */
1006 estimateMicros: number;
1007 }): Promise<Result<ReservationHeld>>;
1008 /** Releases a reservation's hold with what the work cost g1t, before the margin. Safe to repeat. */
1009 settle(reservationId: string, actualMicros: number): Promise<Result<boolean>>;
1010 /** Stripe's page to save and verify a card (3-D Secure, never charged). Owners only. */
1011 cardCheck(actor: User, workspace: string, returnUrl: string): Promise<Result<{ url: string }>>;
1012 /** Records the card check once Stripe says it passed, and grants the trial if it can. Safe to repeat. */
1013 confirmCardCheck(workspace: string, viewer: Viewer, session: string): Promise<Result<Entitlements>>;
1014 /** An owner asks for a higher limit, or for help with usage past what was meant. */
1015 requestLimit(
1016 actor: User,
1017 workspace: string,
1018 request: { kind: "limit" | "overage"; amountMicros: number; reason: string; expectedMonthlyMicros: number },
1019 ): Promise<Result<LimitRequest>>;
1020 /** The workspace's requests and their answers, newest first. Members only. */
1021 limitRequests(workspace: string, viewer: Viewer): Promise<Result<LimitRequest[]>>;
1022 /**
1023 * The owners' own caps on agents: one run's spend ($0.10 to $100) and one issue's ($1 to $1,000).
1024 * Null goes back to the default ($2 and $10). A cap staff set wins. Owners only.
1025 */
1026 setCaps(actor: User, workspace: string, caps: { runCapMicros: number | null; issueCapMicros: number | null }): Promise<Result<Entitlements>>;
1027 /** An owner's answer to a spend spike: keep going for 24 hours, or stop. */
1028 confirmSpike(actor: User, workspace: string, keepGoing: boolean): Promise<Result<Entitlements>>;
1029 /** Every metered price and the recent changes. Public. */
1030 prices(): Promise<PriceBook>;
1031 /** A workspace's limit, for its members. */
1032 limit(workspace: string, viewer: Viewer): Promise<Result<Limit>>;
1033 /** The same, for the services that enforce it. */
1034 checkLimit(workspace: string): Promise<Result<Limit>>;
1035 /**
1036 * The owners' own monthly limit, up to what is available; null goes back
1037 * to the default, and `useFullLimit` uses everything available. Owners only.
1038 */
1039 setSpendLimit(
1040 actor: User,
1041 workspace: string,
1042 spendLimitMicros: number | null,
1043 useFullLimit?: boolean,
1044 /** Use the one-time raise: up to twice the highest ceiling, once per workspace. */
1045 raiseOnce?: boolean,
1046 ): Promise<Result<Limit>>;
1047 /** The workspace's invoices from g1t, newest first. Members only. */
1048 invoices(workspace: string, viewer: Viewer): Promise<Result<WorkspaceInvoice[]>>;
1049 /**
1050 * How long a sandbox ran for a workspace, reported when it stops. Its
1051 * cost is recorded and every second is charged, from the first. False if
1052 * `reference` was recorded before.
1053 */
1054 recordSandbox(usage: {
1055 workspace: string;
1056 seconds: number;
1057 description: string;
1058 repo?: string | null;
1059 reference: string;
1060 /** What ran; checks, workflows and the merge queue on public repositories may use the open-source pool. */
1061 kind?: ComputeKind | null;
1062 /** vCPU-seconds used, when the sandbox can tell: the run is priced on its own CPU. */
1063 cpuSeconds?: number | null;
1064 /** The reservation it started under, settled with this cost. */
1065 reservationId?: string | null;
1066 /** It ran on one of the workspace's self-hosted runners: its minutes go on usage at $0. */
1067 selfHosted?: boolean;
1068 /** The machine it ran on, by label (`g1t-4core`); absent, the standard one. */
1069 instance?: string | null;
1070 }): Promise<Result<boolean>>;
1071 startRun(run: {
1072 workspace: string;
1073 repo: RepoPath;
1074 number: number;
1075 task: string;
1076 model: string;
1077 /** `workspace` when the run uses the workspace's own model provider. */
1078 billedTo?: "g1t" | "workspace";
1079 /** The model session's id, so the run can be settled at AI Gateway's price. */
1080 session?: string | null;
1081 /** `small` or `large`: the tier g1t routed the run to, on its hosted models. */
1082 tier?: "small" | "large" | null;
1083 }): Promise<Result<RunTicket | null>>;
1084}
1085
1086
1087/** One slice of usage: what it was for, what it cost, how many runs. */
1088export type UsageSlice = { key: string; micros: number; runs: number };
1089
1090/** The model tokens runs used over a window of days. */
1091export type TokenUsage = {
1092 /** `YYYY-MM-DD`, the first day counted. */
1093 since: string;
1094 /** The window's length: 42 unless asked, 366 at most. */
1095 days: number;
1096 /** Null for the whole workspace. */
1097 person: string | null;
1098 totalTokens: number;
1099 inputTokens: number;
1100 outputTokens: number;
1101 cacheReadTokens: number;
1102 cacheWriteTokens: number;
1103 /** What those runs were charged, as `usage` measures it. */
1104 costMicros: number;
1105 /** Days in the window with any tokens. */
1106 activeDays: number;
1107 /** Every day in the window, oldest first, zeros included. */
1108 byDay: { day: string; tokens: number }[];
1109};
1110
1111/** What a workspace's agents cost over a period. */
1112export type Usage = {
1113 since: string;
1114 /** Charged, including g1t's margin. */
1115 spentMicros: number;
1116 /** 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. */
1117 coveredMicros?: number;
1118 /** What the account's discount took off the price; usage at price is spent + covered + this. */
1119 discountMicros?: number;
1120 /** The account's discount now, in percent; with one, the slices are at price. */
1121 discountPercent?: number | null;
1122 /** What g1t's model provider charged, before the margin. */
1123 costMicros: number;
1124 /** What runs on the workspace's own provider cost there, estimated. Not charged by g1t. */
1125 providerMicros: number;
1126 /** What the runs used, at cost: g1t's models and the workspace's own provider together. */
1127 usedMicros: number;
1128 /** g1t charges nothing for now; the slices then measure usage at cost. */
1129 free: boolean;
1130 runs: number;
1131 /** Spend per day and task, keyed `YYYY-MM-DD/task`. */
1132 byDay: UsageSlice[];
1133 byTask: UsageSlice[];
1134 byRepo: UsageSlice[];
1135 /** Keyed `namespace/name#number`. */
1136 byPull: UsageSlice[];
1137 byModel: UsageSlice[];
1138 /** Credit bought in the period. */
1139 addedMicros: number;
1140};
1141
1142/** One of g1t's products (a "bucket") on one day. Money in micros. */
1143export type CostDay = { day: string; bucket: string; cfCostMicros: number; ownCostMicros: number; valueMicros: number; cashMicros: number };
1144
1145/** One product over the range: what customers were charged at price against what it cost. */
1146export type ProductMargin = {
1147 bucket: string;
1148 title: string;
1149 /** Cloudflare's bill, or g1t's own figure where Cloudflare does not bill it (`costSource`). */
1150 costMicros: number;
1151 cfCostMicros: number;
1152 ownCostMicros: number;
1153 valueMicros: number;
1154 marginMicros: number;
1155 marginPercent: number | null;
1156 costSource: "cloudflare" | "ledger" | string;
1157 /** Running g1t, paid for by the plan. */
1158 overhead: boolean;
1159};
1160
1161/** All of g1t: money in (usage and the plan) against every cost. */
1162export type OverallMargin = {
1163 usageMicros: number;
1164 plansMicros: number;
1165 costMicros: number;
1166 marginMicros: number;
1167 marginPercent: number | null;
1168 /** Of costMicros, what went on usage g1t gave away on purpose: comped workspaces, free periods, the trial and the open-source pool. */
1169 givenMicros?: number;
1170 /** Money in against costMicros - givenMicros. */
1171 soldMarginMicros?: number;
1172 soldMarginPercent?: number | null;
1173 /** Usage sold: usageMicros against what that usage cost, less what was given. */
1174 usageCostMicros?: number;
1175 usageMarginMicros?: number;
1176 usageMarginPercent?: number | null;
1177 /** Running g1t: plansMicros against the platform's cost, less its given share. */
1178 runningCostMicros?: number;
1179 /** Cost no mapping names, less its given share. */
1180 unmappedCostMicros?: number;
1181 /** givenMicros by why. Free is free periods, free allowances and overruns g1t covered. */
1182 givenCompedMicros?: number;
1183 givenFreeMicros?: number;
1184 givenTrialMicros?: number;
1185 givenPoolMicros?: number;
1186 /** What discounts on an account's terms took below cost plus the margin: given, not margin lost. */
1187 givenDiscountMicros?: number;
1188 /** Credits from g1t spent on usage, by kind: given, never money in. Refunds come off money in instead. */
1189 givenCreditPromotionalMicros?: number;
1190 givenCreditGoodwillMicros?: number;
1191 /** Credits over the range: given (every kind), spent on usage, and refunds' money given back. */
1192 creditsGivenMicros?: number;
1193 creditsUsedMicros?: number;
1194 creditsRefundedMicros?: number;
1195 /** costMicros by who g1t pays: Cloudflare's bill (billed, after included allowances) and model providers (tokens, not on Cloudflare's bill). */
1196 /** What the plan's included usage paid for, at price: money in for usage, paid out of plansMicros. */
1197 includedMicros?: number;
1198 cloudflareCostMicros?: number;
1199 modelsCostMicros?: number;
1200};
1201
1202/** A count, cost or leak that does not add up. */
1203export type CostDrift = {
1204 bucket: string;
1205 title: string;
1206 kind: "count" | "cost" | "leak" | string;
1207 ours: number;
1208 cloudflare: number;
1209 deltaPercent: number | null;
1210 detail: string;
1211 foundAt: string;
1212};
1213
1214export type MarginAlert = {
1215 id: string;
1216 kind: "margin" | "overall" | "leak" | "drift" | "workspace" | string;
1217 /** The product, or the workspace. */
1218 subject: string;
1219 detail: string;
1220 since: string;
1221 openedAt: string;
1222 emailedAt: string | null;
1223};
1224
1225/** A change to a price, measured from what Cloudflare charged. */
1226export type PriceProposal = {
1227 id: string;
1228 meter: string;
1229 title: string;
1230 unit: string;
1231 currentCostMicros: number;
1232 proposedCostMicros: number;
1233 changePercent: number;
1234 markupPercent: number;
1235 reason: string;
1236 source: "keeper" | "reconciler" | string;
1237 /** Far off the current cost: look before approving. */
1238 suspect: boolean;
1239 status: "open" | "applied" | "approved" | "rejected" | "superseded" | string;
1240 createdAt: string;
1241 decidedAt: string | null;
1242 decidedBy: string | null;
1243 note: string | null;
1244 effectiveAt: string | null;
1245};
1246
1247/** One version of one meter's price; never changed once written. */
1248export type PriceVersion = {
1249 id: string;
1250 meter: string;
1251 version: number;
1252 costMicros: number;
1253 markupPercent: number;
1254 priceMicros: number;
1255 effectiveAt: string;
1256 reason: string;
1257 createdBy: string;
1258 appliedAt: string | null;
1259};
1260
1261/** What `resetBilling` removed. */
1262export type BillingReset = { workspace: string; rows: number; refreshed?: boolean };
1263
1264export type WorkspaceCost = { workspace: string; costMicros: number; revenueMicros: number; givenMicros?: number; internal: boolean };
1265
1266export type CostLineSummary = {
1267 product: string;
1268 meter: string;
1269 rawName: string;
1270 unit: string;
1271 source: string;
1272 quantity: number;
1273 costMicros: number;
1274 /** Absent when no mapping claims it. */
1275 bucket: string | null;
1276};
1277
1278export type CostMapping = {
1279 product: string;
1280 meter: string;
1281 bucket: string;
1282 priceMeter: string | null;
1283 ownMeter: string | null;
1284 scaleToOwn: boolean;
1285 driftPercent: number;
1286 note: string;
1287 updatedAt: string;
1288 updatedBy: string;
1289};
1290
1291export type CostMappingInput = {
1292 product: string;
1293 meter: string;
1294 bucket?: string;
1295 priceMeter?: string | null;
1296 ownMeter?: string | null;
1297 scaleToOwn?: boolean;
1298 driftPercent?: number | null;
1299 note?: string;
1300 remove?: boolean;
1301};
1302
1303export type CostSettings = {
1304 autoApply: boolean;
1305 autoApplyPercent: number;
1306 noticeDays: number;
1307 marginFloorPercent: number;
1308 alertDays: number;
1309 minDailyCostMicros: number;
1310 anomalyFactor: number;
1311 anomalyFloorMicros: number;
1312};
1313
1314export type CostsReport = {
1315 configured: boolean;
1316 fetchedAt: string | null;
1317 since: string;
1318 until: string;
1319 days: CostDay[];
1320 products: ProductMargin[];
1321 overall: OverallMargin;
1322 drift: CostDrift[];
1323 alerts: MarginAlert[];
1324 proposals: PriceProposal[];
1325 versions: PriceVersion[];
1326 topWorkspaces: WorkspaceCost[];
1327 lines: CostLineSummary[];
1328 mappings: CostMapping[];
1329 settings: CostSettings;
1330 /** g1t's own spend against its two caps. */
1331 caps: SpendCaps;
1332};
1333
1334/** What g1t pays for itself, at cost, against its caps (billing's `budget`). */
1335export type SpendCaps = {
1336 /** Today (UTC), YYYY-MM-DD, and this month, YYYY-MM. */
1337 day: string;
1338 month: string;
1339 /** What g1t paid for itself today across every workspace. */
1340 todayMicros: number;
1341 /** `PLATFORM_DAILY_SPEND_CAP_MICROS`; 0: no breaker. */
1342 dailyCapMicros: number;
1343 /** New hosted-model agent runs g1t would pay for are paused. */
1344 tripped: boolean;
1345 trippedAt: string | null;
1346 liftedBy: string | null;
1347 liftedAt: string | null;
1348 liftNote: string | null;
1349 /** This month so far, by what paid: comped, trial, oss, given, unpaid. */
1350 monthBuckets: { bucket: string; title: string; micros: number }[];
1351 comped: CompedBudget[];
1352 /** Free workspaces' share of reconciled costs this month (git, storage, platform). */
1353 freeTierMicros: number;
1354 /** Cloudflare's subscriptions a month: read from Cloudflare each day, else `CLOUDFLARE_FIXED_MONTHLY_MICROS`, an estimate. */
1355 fixedMonthlyMicros: number;
1356 fixedSource?: "cloudflare" | "estimate" | string;
1357 fixedReadAt?: string | null;
1358 /** Each subscription, when read from Cloudflare. */
1359 fixedItems?: { name: string; monthlyMicros: number }[];
1360 /** Money in this month, through the last reconciled day. */
1361 revenueMicros: number;
1362};
1363
1364/** A comped account's monthly budget, at cost. */
1365export type CompedBudget = {
1366 account: string;
1367 name: string;
1368 usedMicros: number;
1369 /** 0: no budget. */
1370 ceilingMicros: number;
1371 /** `COMPED_MONTHLY_CEILING_MICROS`, not the account's own limit. */
1372 defaultCeiling: boolean;
1373 /** 50, 75, 90, 100, or 0. */
1374 level: number;
1375};
1376
1377export type CostsRun = { lines: number; days: number; proposals: number; alerts: number; problems: string[] };