Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(billing): buy credits or auto-reload from the usage limit dialog (#8851)
Jacob Beckermane894f7aefd4d
diff --git a/.sqlx/query-33a8258315ad7db2aff6e65f58b9547a06454af3b46f8390fa0a059fa11c33ee.json b/.sqlx/query-33a8258315ad7db2aff6e65f58b9547a06454af3b46f8390fa0a059fa11c33ee.jsonnew file mode 100644index 0000000000..0a1ed369b2--- /dev/null+++ b/.sqlx/query-33a8258315ad7db2aff6e65f58b9547a06454af3b46f8390fa0a059fa11c33ee.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE ai_credit_reload\n SET status = 'failed', updated_at = NOW()\n WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "33a8258315ad7db2aff6e65f58b9547a06454af3b46f8390fa0a059fa11c33ee"+}diff --git a/.sqlx/query-39fca497572c002c867196ee262bae22e85e5ec9c68753b6a18fdb5935afe93d.json b/.sqlx/query-39fca497572c002c867196ee262bae22e85e5ec9c68753b6a18fdb5935afe93d.jsondeleted file mode 100644index 2eaed44066..0000000000--- a/.sqlx/query-39fca497572c002c867196ee262bae22e85e5ec9c68753b6a18fdb5935afe93d.json+++ /dev/null@@ -1,29 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE ai_credit_reload\n SET status = ($2::text)::ai_credit_reload_status, updated_at = NOW()\n WHERE stripe_invoice_id = $1\n AND status <> 'paid'\n AND status <> ($2::text)::ai_credit_reload_status\n RETURNING user_id, amount_cents\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "user_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "amount_cents",- "type_info": "Int8"- }- ],- "parameters": {- "Left": [- "Text",- "Text"- ]- },- "nullable": [- false,- false- ]- },- "hash": "39fca497572c002c867196ee262bae22e85e5ec9c68753b6a18fdb5935afe93d"-}diff --git a/.sqlx/query-4420bff6bddf7c7f5c1dd886322c258f062f5fd7eef77bcbd9c628b1a6e504b7.json b/.sqlx/query-4420bff6bddf7c7f5c1dd886322c258f062f5fd7eef77bcbd9c628b1a6e504b7.jsondeleted file mode 100644index c8e0d87eaa..0000000000--- a/.sqlx/query-4420bff6bddf7c7f5c1dd886322c258f062f5fd7eef77bcbd9c628b1a6e504b7.json+++ /dev/null@@ -1,24 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT COALESCE(SUM(amount_cents), 0)::bigint AS \"spent!\"\n FROM ai_credit_reload\n WHERE user_id = $1\n AND (status <> 'failed' OR stripe_invoice_id IS NOT NULL)\n AND created_at >= $2\n AND created_at < $3\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "spent!",- "type_info": "Int8"- }- ],- "parameters": {- "Left": [- "Text",- "Timestamptz",- "Timestamptz"- ]- },- "nullable": [- null- ]- },- "hash": "4420bff6bddf7c7f5c1dd886322c258f062f5fd7eef77bcbd9c628b1a6e504b7"-}diff --git a/.sqlx/query-4a50c393e27e4977ab814ba99b7081153eea11c38d163ab05d8eb92c89dc568d.json b/.sqlx/query-4a50c393e27e4977ab814ba99b7081153eea11c38d163ab05d8eb92c89dc568d.jsonnew file mode 100644index 0000000000..5d75c1dfa2--- /dev/null+++ b/.sqlx/query-4a50c393e27e4977ab814ba99b7081153eea11c38d163ab05d8eb92c89dc568d.json@@ -0,0 +1,46 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, amount_cents, stripe_invoice_id, status::text AS \"status!\",\n (status = 'pending'\n AND stripe_invoice_id IS NULL\n AND updated_at < NOW() - INTERVAL '10 minutes') AS \"orphaned!\"\n FROM ai_credit_reload\n WHERE user_id = $1\n AND kind = 'automatic'\n AND (status = 'pending'\n OR (status = 'failed' AND stripe_invoice_id IS NOT NULL))\n ORDER BY created_at\n FOR UPDATE\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "amount_cents",+ "type_info": "Int8"+ },+ {+ "ordinal": 2,+ "name": "stripe_invoice_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "status!",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "orphaned!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ null,+ null+ ]+ },+ "hash": "4a50c393e27e4977ab814ba99b7081153eea11c38d163ab05d8eb92c89dc568d"+}diff --git a/.sqlx/query-532864b237e27757186e3837f18f2b01abc52c838406382afa3874fe6e8b3b9f.json b/.sqlx/query-532864b237e27757186e3837f18f2b01abc52c838406382afa3874fe6e8b3b9f.jsonnew file mode 100644index 0000000000..9b81889a44--- /dev/null+++ b/.sqlx/query-532864b237e27757186e3837f18f2b01abc52c838406382afa3874fe6e8b3b9f.json@@ -0,0 +1,37 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE ai_credit_reload\n SET status = ($2::text)::ai_credit_reload_status,\n stripe_invoice_id = $1,\n updated_at = NOW()\n WHERE (stripe_invoice_id = $1\n OR ($4 AND id = $3 AND stripe_invoice_id IS NULL))\n AND status <> 'paid'\n AND status <> ($2::text)::ai_credit_reload_status\n RETURNING user_id, amount_cents, kind::text AS \"kind!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "amount_cents",+ "type_info": "Int8"+ },+ {+ "ordinal": 2,+ "name": "kind!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Uuid",+ "Bool"+ ]+ },+ "nullable": [+ false,+ false,+ null+ ]+ },+ "hash": "532864b237e27757186e3837f18f2b01abc52c838406382afa3874fe6e8b3b9f"+}diff --git a/.sqlx/query-57772ecc69c0f78e6fcfa8741c9ba898cc811b0a94316afe0cde43b0c4205332.json b/.sqlx/query-57772ecc69c0f78e6fcfa8741c9ba898cc811b0a94316afe0cde43b0c4205332.jsonnew file mode 100644index 0000000000..b3c371e2e2--- /dev/null+++ b/.sqlx/query-57772ecc69c0f78e6fcfa8741c9ba898cc811b0a94316afe0cde43b0c4205332.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, amount_cents, stripe_invoice_id\n FROM ai_credit_reload\n WHERE user_id = $1\n AND kind = 'purchase'\n AND status = 'failed'\n AND stripe_invoice_id IS NOT NULL\n ORDER BY created_at\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "amount_cents",+ "type_info": "Int8"+ },+ {+ "ordinal": 2,+ "name": "stripe_invoice_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ true+ ]+ },+ "hash": "57772ecc69c0f78e6fcfa8741c9ba898cc811b0a94316afe0cde43b0c4205332"+}diff --git a/.sqlx/query-6d7fde916e4f434289c7d0d58238c59fe90acc05d923b75fcf7c7946509ec22b.json b/.sqlx/query-76ef91ca9d90393d9445a26543759826fa9909362f736486d535b339479230f2.jsonsimilarity index 60%rename from .sqlx/query-6d7fde916e4f434289c7d0d58238c59fe90acc05d923b75fcf7c7946509ec22b.jsonrename to .sqlx/query-76ef91ca9d90393d9445a26543759826fa9909362f736486d535b339479230f2.jsonindex 71f7040ac9..2503c32d9c 100644--- a/.sqlx/query-6d7fde916e4f434289c7d0d58238c59fe90acc05d923b75fcf7c7946509ec22b.json+++ b/.sqlx/query-76ef91ca9d90393d9445a26543759826fa9909362f736486d535b339479230f2.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO ai_credit_ledger (id, user_id, kind, delta_cents, stripe_reference, note)\n VALUES ($1, $2, 'purchase', $3, $4, 'Automatic reload')\n ON CONFLICT (stripe_reference) WHERE stripe_reference IS NOT NULL DO NOTHING\n ",+ "query": "\n INSERT INTO ai_credit_ledger (id, user_id, kind, delta_cents, stripe_reference, note)\n VALUES ($1, $2, 'purchase', $3, $4, $5)\n ON CONFLICT (stripe_reference) WHERE stripe_reference IS NOT NULL DO NOTHING\n ","describe": {"columns": [],"parameters": {@@ -8,10 +8,11 @@"Uuid","Text","Int8",+ "Text","Text"]},"nullable": []},- "hash": "6d7fde916e4f434289c7d0d58238c59fe90acc05d923b75fcf7c7946509ec22b"+ "hash": "76ef91ca9d90393d9445a26543759826fa9909362f736486d535b339479230f2"}diff --git a/.sqlx/query-9125e357358995b562dccd6ebf9e5a4bd85f21079aef642ebe3c1beb88e5cb9b.json b/.sqlx/query-9125e357358995b562dccd6ebf9e5a4bd85f21079aef642ebe3c1beb88e5cb9b.jsondeleted file mode 100644index f8c6747dfb..0000000000--- a/.sqlx/query-9125e357358995b562dccd6ebf9e5a4bd85f21079aef642ebe3c1beb88e5cb9b.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "SELECT user_id FROM ai_credit_reload WHERE stripe_invoice_id = $1",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "user_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false- ]- },- "hash": "9125e357358995b562dccd6ebf9e5a4bd85f21079aef642ebe3c1beb88e5cb9b"-}diff --git a/.sqlx/query-9f7f82507358d2dfc46c599c91e1add20fa46128ed160a1650db83cbdcb8a9e6.json b/.sqlx/query-9f7f82507358d2dfc46c599c91e1add20fa46128ed160a1650db83cbdcb8a9e6.jsonnew file mode 100644index 0000000000..cc231e20ac--- /dev/null+++ b/.sqlx/query-9f7f82507358d2dfc46c599c91e1add20fa46128ed160a1650db83cbdcb8a9e6.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO ai_credit_reload (id, user_id, amount_cents, status, kind, purchased_by)\n VALUES ($1, $2, $3, 'pending', 'purchase', $4)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Int8",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "9f7f82507358d2dfc46c599c91e1add20fa46128ed160a1650db83cbdcb8a9e6"+}diff --git a/.sqlx/query-0948e0dd417a4583f79f1146744ad76ae030eacee66aab7caeccf67393106a18.json b/.sqlx/query-da846c9c7acf83aff9446fd6c905cc08784f137c8b2e84d028639ba60c5451d5.jsonsimilarity index 51%rename from .sqlx/query-0948e0dd417a4583f79f1146744ad76ae030eacee66aab7caeccf67393106a18.jsonrename to .sqlx/query-da846c9c7acf83aff9446fd6c905cc08784f137c8b2e84d028639ba60c5451d5.jsonindex 9ee884536e..f39c222e2f 100644--- a/.sqlx/query-0948e0dd417a4583f79f1146744ad76ae030eacee66aab7caeccf67393106a18.json+++ b/.sqlx/query-da846c9c7acf83aff9446fd6c905cc08784f137c8b2e84d028639ba60c5451d5.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT DISTINCT user_id AS \"user_id!\"\n FROM (\n SELECT user_id\n FROM ai_usage\n WHERE count_usage = TRUE\n AND created_at >= $1\n UNION ALL\n SELECT user_id\n FROM ai_credit_reload\n WHERE status = 'pending'\n AND stripe_invoice_id IS NULL\n AND updated_at < $2::timestamptz - INTERVAL '10 minutes'\n UNION ALL\n SELECT user_id\n FROM ai_billing_account\n WHERE period_start >= $1::timestamptz\n OR (period_end >= $1 AND period_end <= $2)\n ) AS candidates\n ORDER BY user_id\n ",+ "query": "\n SELECT DISTINCT user_id AS \"user_id!\"\n FROM (\n SELECT user_id\n FROM ai_usage\n WHERE count_usage = TRUE\n AND created_at >= $1\n UNION ALL\n SELECT user_id\n FROM ai_credit_reload\n WHERE kind = 'automatic'\n AND status = 'pending'\n AND stripe_invoice_id IS NULL\n AND updated_at < $2::timestamptz - INTERVAL '10 minutes'\n UNION ALL\n SELECT user_id\n FROM ai_billing_account\n WHERE period_start >= $1::timestamptz\n OR (period_end >= $1 AND period_end <= $2)\n ) AS candidates\n ORDER BY user_id\n ","describe": {"columns": [{@@ -19,5 +19,5 @@null]},- "hash": "0948e0dd417a4583f79f1146744ad76ae030eacee66aab7caeccf67393106a18"+ "hash": "da846c9c7acf83aff9446fd6c905cc08784f137c8b2e84d028639ba60c5451d5"}diff --git a/.sqlx/query-e411635c4d819f0553dad54127c3364e31c6ed47256ea54ef37d82bc7b00651e.json b/.sqlx/query-e411635c4d819f0553dad54127c3364e31c6ed47256ea54ef37d82bc7b00651e.jsonnew file mode 100644index 0000000000..313d127727--- /dev/null+++ b/.sqlx/query-e411635c4d819f0553dad54127c3364e31c6ed47256ea54ef37d82bc7b00651e.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT user_id FROM ai_credit_reload\n WHERE stripe_invoice_id = $1\n OR ($3 AND id = $2 AND stripe_invoice_id IS NULL)\n ORDER BY (stripe_invoice_id = $1) DESC NULLS LAST\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Uuid",+ "Bool"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "e411635c4d819f0553dad54127c3364e31c6ed47256ea54ef37d82bc7b00651e"+}diff --git a/.sqlx/query-e45bdf3b55302e9cdfda17334d9454086858cbde3d6a4444984e062219f1247c.json b/.sqlx/query-e45bdf3b55302e9cdfda17334d9454086858cbde3d6a4444984e062219f1247c.jsonnew file mode 100644index 0000000000..de9116cf37--- /dev/null+++ b/.sqlx/query-e45bdf3b55302e9cdfda17334d9454086858cbde3d6a4444984e062219f1247c.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE ai_credit_reload\n SET status = 'failed', stripe_invoice_id = NULL, updated_at = NOW()\n WHERE id = $1 AND kind = 'purchase' AND status <> 'paid'\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "e45bdf3b55302e9cdfda17334d9454086858cbde3d6a4444984e062219f1247c"+}diff --git a/.sqlx/query-b1d4072235ad4bed4f94f52cf60155cb3a0f95d40f2d710c6118101a3f56b224.json b/.sqlx/query-fb3a18b96714c926289eb8412c7b8dff0c04825ee10db817f7ad4d45cde85890.jsonsimilarity index 75%rename from .sqlx/query-b1d4072235ad4bed4f94f52cf60155cb3a0f95d40f2d710c6118101a3f56b224.jsonrename to .sqlx/query-fb3a18b96714c926289eb8412c7b8dff0c04825ee10db817f7ad4d45cde85890.jsonindex 7e363e47a1..2052019f1c 100644--- a/.sqlx/query-b1d4072235ad4bed4f94f52cf60155cb3a0f95d40f2d710c6118101a3f56b224.json+++ b/.sqlx/query-fb3a18b96714c926289eb8412c7b8dff0c04825ee10db817f7ad4d45cde85890.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, amount_cents, stripe_invoice_id, status::text AS \"status!\",\n (status = 'pending'\n AND stripe_invoice_id IS NULL\n AND updated_at < NOW() - INTERVAL '10 minutes') AS \"orphaned!\"\n FROM ai_credit_reload\n WHERE user_id = $1\n AND (status = 'pending'\n OR (status = 'failed' AND stripe_invoice_id IS NOT NULL))\n ORDER BY created_at\n FOR UPDATE\n ",+ "query": "\n SELECT id, amount_cents, stripe_invoice_id, status::text AS \"status!\",\n (status = 'pending'\n AND stripe_invoice_id IS NULL\n AND updated_at < NOW() - INTERVAL '10 minutes') AS \"orphaned!\"\n FROM ai_credit_reload\n WHERE user_id = $1\n AND kind = 'purchase'\n AND (status = 'pending'\n OR (status = 'failed' AND stripe_invoice_id IS NOT NULL))\n ORDER BY created_at\n FOR UPDATE\n ","describe": {"columns": [{@@ -42,5 +42,5 @@null]},- "hash": "b1d4072235ad4bed4f94f52cf60155cb3a0f95d40f2d710c6118101a3f56b224"+ "hash": "fb3a18b96714c926289eb8412c7b8dff0c04825ee10db817f7ad4d45cde85890"}diff --git a/.sqlx/query-fc9e94cb5e5dfb5cd994ee771d617a90f22e7489d6b5469c655fdd17e2d0f847.json b/.sqlx/query-fc9e94cb5e5dfb5cd994ee771d617a90f22e7489d6b5469c655fdd17e2d0f847.jsonnew file mode 100644index 0000000000..4fbeb1a82b--- /dev/null+++ b/.sqlx/query-fc9e94cb5e5dfb5cd994ee771d617a90f22e7489d6b5469c655fdd17e2d0f847.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT COALESCE(SUM(amount_cents), 0)::bigint AS \"spent!\"\n FROM ai_credit_reload\n WHERE user_id = $1\n AND (status <> 'failed' OR stripe_invoice_id IS NOT NULL)\n -- A purchase whose collector died before Stripe saw it charged\n -- nothing; a paid webhook still books it by reload id.\n AND NOT (kind = 'purchase'\n AND status = 'pending'\n AND stripe_invoice_id IS NULL\n AND updated_at < NOW() - INTERVAL '10 minutes')\n AND created_at >= $2\n AND created_at < $3\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "spent!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Timestamptz",+ "Timestamptz"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "fc9e94cb5e5dfb5cd994ee771d617a90f22e7489d6b5469c655fdd17e2d0f847"+}diff --git a/apps/web/src/features/billing-lab/create-billing-lab.test.ts b/apps/web/src/features/billing-lab/create-billing-lab.test.tsindex 0d29a6c375..18a6c0ce79 100644--- a/apps/web/src/features/billing-lab/create-billing-lab.test.ts+++ b/apps/web/src/features/billing-lab/create-billing-lab.test.ts@@ -7,7 +7,7 @@ describe('billing lab actions', () => {it('adds credits only after the simulated checkout completes', async () => {const lab = createBillingLab('credits');- const checkout = lab.usage.checkout.start(2_500);+ const checkout = lab.usage.creditPurchase.buy(2_500);await vi.runAllTimersAsync();await checkout;expect(lab.payment()).toEqual({ kind: 'credits', amountCents: 2_500 });@@ -22,7 +22,7 @@ describe('billing lab actions', () => {it('fails one checkout without changing the balance, then permits a retry', async () => {const lab = createBillingLab('pro');lab.setFailNext(true);- const failed = expect(lab.usage.checkout.start(2_500)).rejects.toThrow(+ const failed = expect(lab.usage.creditPurchase.buy(2_500)).rejects.toThrow('Simulated billing request failure');await vi.runAllTimersAsync();@@ -31,7 +31,7 @@ describe('billing lab actions', () => {expect(lab.payment()).toBeUndefined();expect(lab.failNext()).toBe(false);expect(lab.pending()).toBe(false);- const retry = lab.usage.checkout.start(2_500);+ const retry = lab.usage.creditPurchase.buy(2_500);await vi.runAllTimersAsync();await retry;expect(lab.payment()?.kind).toBe('credits');@@ -45,7 +45,7 @@ describe('billing lab actions', () => {resetsAt: '2026-11-01T00:00:00.000Z',limitReached: true,});- const checkout = lab.usage.checkout.start(2_500);+ const checkout = lab.usage.creditPurchase.buy(2_500);await vi.runAllTimersAsync();await checkout;const complete = lab.completePayment();@@ -65,11 +65,8 @@ describe('billing lab actions', () => {});});- it('rejects billing actions for a team-paid member without opening a payment flow or changing settings', async () => {+ it('rejects billing settings for a team-paid member without opening a payment flow or changing them', async () => {const lab = createBillingLab('team-member');- await expect(lab.usage.checkout.start(2_500)).rejects.toThrow(- 'Credit purchase unavailable'- );await expect(lab.usage.autoReload.save({ ...lab.state().autoReload, enabled: true })).rejects.toThrow('Auto-Reload unavailable');@@ -97,7 +94,7 @@ describe('billing lab actions', () => {);const before = lab.state().creditBalanceCents;const spent = lab.state().reloadSpentCents;- const checkout = lab.usage.checkout.start(2_500);+ const checkout = lab.usage.creditPurchase.buy(2_500);await vi.runAllTimersAsync();await checkout;const complete = lab.completePayment();diff --git a/apps/web/src/features/billing-lab/create-billing-lab.ts b/apps/web/src/features/billing-lab/create-billing-lab.tsindex 86dbe9e6b1..93e7ef8c3e 100644--- a/apps/web/src/features/billing-lab/create-billing-lab.ts+++ b/apps/web/src/features/billing-lab/create-billing-lab.ts@@ -155,15 +155,25 @@ export function createBillingLab(initial: ScenarioId) {(value) => ({ ...value, status: 'ready' }),'Usage summary loaded'),- checkout: {+ creditPurchase: {pending,supportedAmounts: () => [2_500, 5_000, 10_000],- start: async (amountCents) => {- if (!manageable()) throw new Error('Credit purchase unavailable');+ // Team members buy on the owner's card too, within the team limit.+ buy: async (amountCents) => {+ if (state().tier === 'free' || state().unlimited)+ throw new Error('Credit purchase unavailable');+ await perform('Credit purchase', () =>+ openPayment({ kind: 'credits', amountCents })+ );+ return { status: 'paid', amountCents };+ },+ // The lab has no Stripe; checkout opens its simulated payment flow.+ checkout: async (amountCents) => {+ if (!manageable()) throw new Error('Credit checkout unavailable');await perform('Credit checkout', () =>openPayment({ kind: 'credits', amountCents }));- return 'billing-lab:checkout';+ return '#billing-lab-checkout';},},autoReload: {diff --git a/apps/web/src/features/billing-lab/queries/fixture-snapshot.ts b/apps/web/src/features/billing-lab/queries/fixture-snapshot.tsindex 6dd507dac8..e4487347a3 100644--- a/apps/web/src/features/billing-lab/queries/fixture-snapshot.ts+++ b/apps/web/src/features/billing-lab/queries/fixture-snapshot.ts@@ -50,5 +50,23 @@ export function fixtureSnapshot(state: BillingSimulation): AiUsageSnapshot {suspended: state.reloadSuspended,active: state.autoReload.enabled && !state.reloadSuspended,},+ credit_purchase:+ state.tier === 'free' || state.unlimited+ ? undefined+ : {+ // Members fall back to the plan's default team limit, as on the+ // backend; a payer without a limit is uncapped.+ monthly_limit_cents:+ limit ??+ (state.role === 'member'+ ? state.tier === 'max'+ ? 100_000+ : 20_000+ : null),+ committed_cents: state.reloadSpentCents,+ resets_at: new Date(+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)+ ).toISOString(),+ },};}diff --git a/apps/web/src/features/billing-lab/views/billing-lab.tsx b/apps/web/src/features/billing-lab/views/billing-lab.tsxindex 5daee7cc78..9f23c9c3f0 100644--- a/apps/web/src/features/billing-lab/views/billing-lab.tsx+++ b/apps/web/src/features/billing-lab/views/billing-lab.tsx@@ -524,11 +524,7 @@ export function BillingLabView(props: {open={lab.limitOpen()}code={`ai_${lab.state().blockedReason ?? (lab.state().tier === 'free' ? 'free_allowance_exhausted' : 'allowance_exhausted')}`}freePlan={lab.state().tier === 'free'}- usage={{- percentage: lab.percentage(),- periodEnd: lab.state().periodEnd,- unlimited: lab.state().unlimited,- }}+ resetsAt={lab.state().periodEnd}previewNotice="Billing Lab · simulated account"onClose={() => lab.setLimitOpen(false)}onOpenSettings={() => {diff --git a/apps/web/src/features/paywall/AiUsageLimitDialog.tsx b/apps/web/src/features/paywall/AiUsageLimitDialog.tsxindex d1a0a29ffa..ac8fa177d6 100644--- a/apps/web/src/features/paywall/AiUsageLimitDialog.tsx+++ b/apps/web/src/features/paywall/AiUsageLimitDialog.tsx@@ -1,4 +1,5 @@import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { toast } from '@core/component/Toast/Toast';import { useAiUsageLimitState } from '@core/constant/AiUsageLimitState';import {enableAiUsageBilling,@@ -6,64 +7,319 @@ import {PROD_MODE_ENV,} from '@core/constant/featureFlags';import { useSettingsState } from '@core/constant/SettingsState';-import { useAiBillingSummaryQuery } from '@queries/auth';-import { Suspense } from 'solid-js';-import { isUsageAvailable, monthlyUsagePercent } from '../usage/core/usage';+import { fireAndForget } from '@core/util/fireAndForget';+import { isTauri } from '@core/util/platform';+import { ThrownResultError } from '@core/util/result';+import { getWebOrigin } from '@core/util/webOrigin';+import {+ useAiBillingPlansQuery,+ useAiBillingSummaryQuery,+ useCreateAiCreditCheckoutMutation,+ useCreateBillingPortalMutation,+ usePurchaseAiCreditsMutation,+ useUpdateAiAutoReloadMutation,+} from '@queries/auth';+import { queryReadyGate } from '@queries/gate';+import { createSignal, Suspense } from 'solid-js';+import {+ formatCreditBalance,+ isUsageAvailable,+ parseDollarInput,+ validateAutoReload,+} from '../usage/core/usage';+import { toUsageSummary } from '../usage/queries/usage-summary';import { useAiUsagePreview } from './ai-usage-preview';-import { AiUsageLimitDialogView } from './components/ai-usage-limit-dialog';+import {+ AiUsageLimitDialogView,+ type PurchaseMode,+} from './components/ai-usage-limit-dialog';++/** The server's reason for a refused purchase, as a sentence. */+function purchaseRejection(error: unknown) {+ const message =+ error instanceof ThrownResultError &&+ error.errors.find((e) => e.code === 'CREDIT_PURCHASE_REJECTED')?.message;+ return message+ ? `${message.charAt(0).toUpperCase()}${message.slice(1)}.`+ : "Couldn't buy credits. Please try again.";+}/**- * Shown when the backend refuses an AI request with a billing code. Shows the- * monthly limit and offers paid subscriptions to Free users or usage credits- * to paid users.+ * Shown when the backend refuses an AI request with a billing code. Offers+ * paid subscriptions to Free users. Paid users can buy credits once on the+ * card on file (a team member on the team's card, within its monthly credit+ * limit), and the payer can turn on Auto-Reload in one click.*/export function AiUsageLimitDialog() {const { usageLimitOpen, usageLimitCode, hideUsageLimit } =useAiUsageLimitState();const { openSettings } = useSettingsState();const summary = useAiBillingSummaryQuery({ enabled: usageLimitOpen });+ const plans = useAiBillingPlansQuery();const aiUsageBilling = useFeatureFlag(enableAiUsageBilling);const usagePreview = useAiUsagePreview();+ const autoReload = useUpdateAiAutoReloadMutation();+ const portal = useCreateBillingPortalMutation();+ const purchase = usePurchaseAiCreditsMutation();+ const checkout = useCreateAiCreditCheckoutMutation();+ const [creditsDeclined, setCreditsDeclined] = createSignal(false);+ const [mode, setMode] = createSignal<PurchaseMode>('credits');+ /** The chosen credit pack; unset shows the smallest. */+ const [packCents, setPackCents] = createSignal<number>();+ const [paymentFailed, setPaymentFailed] = createSignal(false);+ const [offerError, setOfferError] = createSignal<string>();+ /** The payer's edit to the monthly limit; unset shows the plan default. */+ const [monthlyLimitInput, setMonthlyLimitInput] = createSignal<string>();const available = () =>!usagePreview.beforeLaunch() &&isUsageAvailable(PROD_MODE_ENV && !LOCAL_ONLY, aiUsageBilling().enabled);const usageSnapshot = () =>- usagePreview.withPreview(summary.isSuccess ? summary.data : undefined);+ usagePreview.withPreview(+ queryReadyGate(summary) ? summary.data : undefined+ );const freePlan = () =>usageLimitCode() === 'ai_free_allowance_exhausted' ||usageSnapshot()?.tier === 'free';- const usage = () => {- const snapshot = usageSnapshot();- return snapshot- ? {- percentage: monthlyUsagePercent(- snapshot.used_cents,- snapshot.included_cents- ),- periodEnd: snapshot.period_end,- unlimited: snapshot.unlimited,- }- : undefined;+ const close = () => {+ hideUsageLimit();+ setPaymentFailed(false);+ setOfferError(undefined);+ setMonthlyLimitInput(undefined);+ setMode('credits');+ setPackCents(undefined);+ setCreditsDeclined(false);+ };++ /** A paid user's position and the plan catalog, when they can buy more. */+ const buyer = () => {+ // The plan catalog supplies credit packs and Auto-Reload's starting values.+ if (+ usagePreview.active() ||+ !queryReadyGate(summary) ||+ !queryReadyGate(plans)+ )+ return;+ const snapshot = summary.data;+ if (snapshot.tier === 'free' || snapshot.unlimited) return;+ return { snapshot, catalog: plans.data };+ };++ /** The monthly credit limit on one-time purchases and what is left of it. */+ const purchaseLimit = () => {+ const limit = buyer()?.snapshot.credit_purchase;+ if (!limit || limit.monthly_limit_cents == null) return;+ return {+ limitCents: limit.monthly_limit_cents,+ remainingCents: Math.max(+ 0,+ limit.monthly_limit_cents - limit.committed_cents+ ),+ };+ };++ /** The payer's starting thresholds, when one click can turn Auto-Reload on. */+ const autoReloadSettings = () => {+ const current = buyer();+ // Only the payer turns Auto-Reload on. Keep the offer while a failed+ // charge is shown: a declined reload leaves Auto-Reload active with its+ // invoice still open.+ if (+ !current?.snapshot.can_manage_billing ||+ (current.snapshot.auto_reload?.active && !paymentFailed())+ )+ return;+ return toUsageSummary(current.snapshot, current.catalog).autoReload+ .settings;+ };++ /** The chosen pack, else the smallest; a pack over the limit is never kept. */+ const selectedPack = () => {+ const packs = buyer()?.catalog.credit_packs_cents ?? [];+ const remaining = purchaseLimit()?.remainingCents;+ const fits = (cents: number) =>+ remaining === undefined || cents <= remaining;+ const chosen = packCents();+ return chosen !== undefined && fits(chosen)+ ? chosen+ : (packs.find(fits) ?? packs[0]);+ };++ /** The card on file can't be charged off-session (none on file, or it+ * needs 3-D Secure): the payer pays this pack through Stripe Checkout. */+ const checkoutCredits = async (+ amountCents: number,+ reason: 'payment_method_required' | 'authentication_required'+ ) => {+ if (!usageSnapshot()?.can_manage_billing) {+ setOfferError(+ reason === 'payment_method_required'+ ? "Your team doesn't have a card on file. Ask your team owner to add one."+ : "Your team's card needs verification. Ask your team owner to buy credits or update the card."+ );+ return;+ }+ // Come back to this page so the user can resend from where they were. The+ // native app's own origin isn't a URL Stripe can return to.+ const here = isTauri()+ ? `${getWebOrigin()}/app/settings/usage`+ : window.location.href;+ try {+ window.location.href = await checkout.mutateAsync({+ amountCents,+ successUrl: here,+ cancelUrl: here,+ });+ } catch {+ setOfferError("Couldn't open checkout. Please try again.");+ }};++ const buyCredits = async () => {+ const amountCents = selectedPack();+ if (amountCents === undefined || purchase.isPending || checkout.isPending)+ return;+ setOfferError(undefined);+ try {+ const result = await purchase.mutateAsync({ amountCents });+ if (+ result.status === 'payment_method_required' ||+ result.status === 'authentication_required'+ ) {+ await checkoutCredits(amountCents, result.status);+ return;+ }+ if (result.status === 'declined') {+ setCreditsDeclined(true);+ return;+ }+ close();+ toast.success(+ `Added ${formatCreditBalance(result.amountCents)} in credits. Resend your message.`+ );+ } catch (error) {+ setOfferError(purchaseRejection(error));+ }+ };++ const monthlyLimit = () => {+ const input = monthlyLimitInput();+ if (input !== undefined) return input;+ const limit = autoReloadSettings()?.monthlySpendLimitCents;+ return limit === null || limit === undefined ? '' : String(limit / 100);+ };++ /** Saved thresholds with the payer's monthly limit; blank means no limit. */+ const chosenSettings = () => {+ const settings = autoReloadSettings();+ if (!settings) return;+ const text = monthlyLimit().trim();+ const monthlySpendLimitCents = text ? parseDollarInput(text) : null;+ if (monthlySpendLimitCents === undefined)+ return {+ error: 'Enter a monthly spend limit in dollars, or leave it blank.',+ };+ const chosen = { ...settings, monthlySpendLimitCents, enabled: true };+ const error = validateAutoReload(chosen);+ return error ? { error } : { settings: chosen };+ };++ const turnOnAutoReload = async () => {+ const chosen = chosenSettings();+ if (!chosen || autoReload.isPending) return;+ if ('error' in chosen) {+ setOfferError(chosen.error);+ return;+ }+ setOfferError(undefined);+ try {+ const snapshot = await autoReload.mutateAsync(chosen.settings);+ // Enabling reloads right away when the balance is low. A failed charge+ // comes back as a suspended reload, and a declined one as an open+ // invoice, so only usable credits mean the user can resend.+ if (snapshot.auto_reload?.suspended || snapshot.remaining_cents <= 0) {+ setPaymentFailed(true);+ return;+ }+ close();+ toast.success('Auto-reload is on. Resend your message.');+ } catch {+ setOfferError("Couldn't turn on auto-reload. Please try again.");+ }+ };++ const addPaymentMethod = async () => {+ if (portal.isPending) return;+ try {+ window.location.href = await portal.mutateAsync({+ returnUrl: `${getWebOrigin()}/app/settings/usage`,+ });+ } catch {+ setOfferError("Couldn't open payment methods. Please try again.");+ }+ };++ const offer = () => {+ const current = buyer();+ const pack = selectedPack();+ if (!current || pack === undefined) return;+ const settings = autoReloadSettings();+ return {+ mode: settings ? mode() : ('credits' as const),+ packsCents: current.catalog.credit_packs_cents,+ packCents: pack,+ teamCard: !current.snapshot.can_manage_billing,+ limit: purchaseLimit(),+ creditsDeclined: creditsDeclined(),+ autoReload: settings && {+ minimumBalanceCents: settings.minimumBalanceCents,+ targetBalanceCents: settings.targetBalanceCents,+ monthlyLimit: monthlyLimit(),+ paymentFailed: paymentFailed(),+ },+ pending:+ autoReload.isPending ||+ portal.isPending ||+ purchase.isPending ||+ checkout.isPending,+ error: offerError(),+ };+ };+return (<Suspense fallback={null}><AiUsageLimitDialogViewopen={usageLimitOpen() && available()}code={usageLimitCode() ?? undefined}freePlan={freePlan()}- usage={usage()}+ resetsAt={usageSnapshot()?.period_end}+ offer={offer()}previewNotice={usagePreview.active()? `Developer preview: ${usagePreview.plan() === 'free' ? 'Free' : 'paid'} plan. No account billing has changed.`: undefined}- onClose={hideUsageLimit}+ onClose={close}onOpenSettings={() => {const target = freePlan() ? 'Billing' : 'Usage';- hideUsageLimit();+ close();openSettings(target);}}+ onMode={(next) => {+ setOfferError(undefined);+ setMode(next);+ }}+ onPack={(cents) => {+ setOfferError(undefined);+ setPackCents(cents);+ }}+ onBuyCredits={() => fireAndForget(buyCredits(), 'usage')}+ onMonthlyLimit={(value) => {+ setOfferError(undefined);+ setMonthlyLimitInput(value);+ }}+ onTurnOnAutoReload={() => fireAndForget(turnOnAutoReload(), 'usage')}+ onAddPaymentMethod={() => fireAndForget(addPaymentMethod(), 'usage')}/></Suspense>);diff --git a/apps/web/src/features/paywall/components/ai-usage-limit-dialog.tsx b/apps/web/src/features/paywall/components/ai-usage-limit-dialog.tsxindex 1a11fddadb..3230dca220 100644--- a/apps/web/src/features/paywall/components/ai-usage-limit-dialog.tsx+++ b/apps/web/src/features/paywall/components/ai-usage-limit-dialog.tsx@@ -1,7 +1,7 @@import type { AiDenyCode } from '@service-auth/ai-billing-types';-import { Button, Dialog, Surface } from '@ui';-import { Show, Suspense } from 'solid-js';-import { MonthlyLimit } from '../../usage/components/monthly-limit';+import { Button, Dialog, InputGroup, Surface, Tabs, TextField } from '@ui';+import { type JSX, Match, Show, Switch } from 'solid-js';+import { formatCreditBalance } from '../../usage/core/usage';const TITLES: Record<AiDenyCode, string> = {ai_allowance_exhausted: "You've used this month's included AI",@@ -10,79 +10,297 @@ const TITLES: Record<AiDenyCode, string> = {ai_overage_payment_failed: 'Your last AI usage charge failed',};+export type PurchaseMode = 'credits' | 'auto-reload';++/**+ * Ways a paid user can keep going: buy credits once on the card on file (the+ * team's card for a member), or, for the payer, turn on Auto-Reload.+ */+export type PurchaseOffer = {+ mode: PurchaseMode;+ /** Credit packs in cents, and the one selected. */+ packsCents: number[];+ packCents: number;+ /** The purchase is charged to the team owner's card. */+ teamCard: boolean;+ /** The monthly credit limit, and what is left of it; absent with no limit. */+ limit?: { limitCents: number; remainingCents: number };+ /** The last one-time charge was declined. */+ creditsDeclined: boolean;+ /** Absent when Auto-Reload is already on. */+ autoReload?: {+ minimumBalanceCents: number;+ targetBalanceCents: number;+ /** Dollars, as typed; blank means no limit. */+ monthlyLimit: string;+ /** The card on file could not be charged; offer to add a payment method. */+ paymentFailed: boolean;+ };+ pending: boolean;+ error?: string;+};+export type AiUsageLimitDialogProps = {open: boolean;code?: AiDenyCode;freePlan: boolean;- usage?: { percentage: number; periodEnd: string; unlimited: boolean };+ /** When the monthly allowance resets. */+ resetsAt?: string;+ offer?: PurchaseOffer;previewNotice?: string;onClose: () => void;onOpenSettings: () => void;+ onMode?: (mode: PurchaseMode) => void;+ onPack?: (cents: number) => void;+ onMonthlyLimit?: (value: string) => void;+ onBuyCredits?: () => void;+ onTurnOnAutoReload?: () => void;+ onAddPaymentMethod?: () => void;};+function resetLabel(resetsAt: string | undefined) {+ const date = resetsAt ? new Date(resetsAt) : undefined;+ return date && !Number.isNaN(date.getTime())+ ? date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })+ : undefined;+}++function DetailRow(props: { label: string; children: JSX.Element }) {+ return (+ <div class="flex min-h-12 items-center justify-between gap-4 px-4 py-2">+ <dt class="text-sm text-ink-muted">{props.label}</dt>+ <dd class="flex items-center text-right text-sm text-ink">+ {props.children}+ </dd>+ </div>+ );+}+export function AiUsageLimitDialogView(props: AiUsageLimitDialogProps) {+ const description = () => {+ const reset = resetLabel(props.resetsAt);+ if (props.freePlan) return 'Subscribe to a paid plan to keep going.';+ const keepGoing = props.offer+ ? 'Add credits to keep going now.'+ : 'Check your plan and usage options to keep going.';+ return reset ? `Your included AI resets ${reset}. ${keepGoing}` : keepGoing;+ };+ const autoReloadMode = () =>+ props.offer?.mode === 'auto-reload' ? props.offer.autoReload : undefined;+ const creditsMode = () =>+ props.offer?.mode === 'credits' ? props.offer : undefined;+ /** No pack fits in what is left of the monthly credit limit. */+ const limitReached = () => {+ const offer = creditsMode();+ return (+ !!offer?.limit &&+ offer.packsCents.every(+ (cents) => cents > (offer.limit?.remainingCents ?? 0)+ )+ );+ };+ /** A declined one-time charge the payer can fix with a new card. */+ const fixCard = () =>+ !!creditsMode()?.creditsDeclined && !props.offer?.teamCard;+ const error = () => {+ const offer = props.offer;+ if (offer?.error) return offer.error;+ if (autoReloadMode()?.paymentFailed)+ return "We couldn't charge your card. Add a payment method, then try again.";+ if (creditsMode()?.creditsDeclined)+ return offer?.teamCard+ ? "Your team's card was declined. Ask your team owner to update it."+ : 'Your card was declined. Add a payment method, then try again.';+ if (limitReached() && offer?.limit) {+ const limit = formatCreditBalance(offer.limit.limitCents);+ const reset = resetLabel(props.resetsAt);+ return offer.teamCard+ ? `Your team has used its ${limit} monthly credit limit${reset ? `. It resets ${reset}` : ''}. Ask your team owner to raise it.`+ : `You've used your ${limit} monthly credit limit. Raise it in usage settings.`;+ }+ };+ const primaryLabel = () => {+ const offer = props.offer;+ if (!offer) return props.freePlan ? 'View plans' : 'Open usage settings';+ if (offer.mode === 'credits') {+ if (fixCard()) return offer.pending ? 'Opening…' : 'Add payment method';+ return offer.pending+ ? 'Charging…'+ : `Buy ${formatCreditBalance(offer.packCents)} in credits`;+ }+ if (offer.autoReload?.paymentFailed)+ return offer.pending ? 'Opening…' : 'Add payment method';+ return offer.pending ? 'Turning on…' : 'Turn on auto-reload';+ };+ const onPrimary = () => {+ const offer = props.offer;+ if (!offer) return props.onOpenSettings();+ if (offer.mode === 'credits')+ return fixCard() ? props.onAddPaymentMethod?.() : props.onBuyCredits?.();+ if (offer.autoReload?.paymentFailed) return props.onAddPaymentMethod?.();+ props.onTurnOnAutoReload?.();+ };+return (<Dialogopen={props.open}onOpenChange={(open) => !open && props.onClose()}position="center"- class="w-160"+ class="w-120"><Surface depth={2} class="rounded-xl">- <section class="flex flex-col gap-5 p-6 font-sans">- <div class="flex flex-col gap-1">- <Dialog.Title class="text-xl font-semibold text-ink">+ <section class="flex flex-col font-sans">+ <header class="flex flex-col gap-1.5 p-6 pb-5">+ <Dialog.Title class="text-lg font-semibold text-ink">{TITLES[props.code ?? 'ai_allowance_exhausted']}</Dialog.Title>- <Dialog.Description class="text-sm text-ink-extra-muted">- {props.freePlan- ? 'Subscribe to a paid plan to keep going.'- : props.usage- ? 'Add additional credits to keep going.'- : 'Check your plan and usage options to keep going.'}+ <Dialog.Description class="text-sm text-ink-muted">+ {description()}</Dialog.Description>- </div>-- <Show when={props.previewNotice}>- <p class="text-xs text-ink-muted" role="status">- {props.previewNotice}- </p>- </Show>+ <Show when={props.previewNotice}>+ <p class="text-xs text-ink-extra-muted" role="status">+ {props.previewNotice}+ </p>+ </Show>+ </header>- {/* The summary is a suspending query resource; keep its- suspension inside the dialog rather than the route boundary. */}- <Suspense fallback={null}>- <Show when={props.usage}>- {(snapshot) => (- <div class="flex flex-col gap-4 rounded-lg bg-active p-4">- <MonthlyLimit- percentage={snapshot().percentage}- periodEnd={snapshot().periodEnd}- unlimited={snapshot().unlimited}+ <Show when={props.offer}>+ {(offer) => (+ <div class="flex flex-col gap-3 px-6 pb-6">+ <Show when={offer().autoReload}>+ <Tabs+ aria-label="How to add credits"+ size="sm"+ fullWidth+ options={[+ { value: 'credits', label: 'One-time' },+ { value: 'auto-reload', label: 'Auto-reload' },+ ]}+ value={offer().mode}+ onChange={(mode) => props.onMode?.(mode)}/>- </div>- )}- </Show>- </Suspense>+ </Show>+ <dl class="divide-y divide-edge-muted rounded-lg border border-edge-muted">+ <Switch>+ <Match when={autoReloadMode()}>+ {(reload) => (+ <>+ <DetailRow label="Reload">+ {formatCreditBalance(reload().targetBalanceCents)}{' '}+ when below{' '}+ {formatCreditBalance(reload().minimumBalanceCents)}+ </DetailRow>+ <DetailRow label="Monthly limit">+ <TextField+ value={reload().monthlyLimit}+ onChange={(value) =>+ props.onMonthlyLimit?.(value)+ }+ >+ <TextField.Label class="sr-only">+ Monthly spend limit+ </TextField.Label>+ <InputGroup size="md" class="w-28">+ <TextField.Input+ as={InputGroup.Input}+ inputMode="decimal"+ class="text-right text-sm"+ placeholder="None"+ />+ <InputGroup.Addon aria-hidden="true">+ $+ </InputGroup.Addon>+ </InputGroup>+ </TextField>+ </DetailRow>+ <DetailRow label="Payment">Card on file</DetailRow>+ </>+ )}+ </Match>+ <Match when={offer().mode === 'credits'}>+ <DetailRow label="Amount">+ <Tabs+ aria-label="Credit amount"+ size="sm"+ options={offer().packsCents.map((cents) => ({+ value: String(cents),+ label: formatCreditBalance(cents),+ disabled:+ offer().limit !== undefined &&+ cents > (offer().limit?.remainingCents ?? 0),+ }))}+ value={String(offer().packCents)}+ onChange={(cents) => props.onPack?.(Number(cents))}+ />+ </DetailRow>+ <Show when={offer().limit}>+ {(limit) => (+ <DetailRow+ label={+ offer().teamCard+ ? 'Team monthly limit'+ : 'Monthly limit'+ }+ >+ {formatCreditBalance(limit().remainingCents)} of{' '}+ {formatCreditBalance(limit().limitCents)} left+ </DetailRow>+ )}+ </Show>+ <DetailRow label="Payment">+ {offer().teamCard+ ? "Team owner's card"+ : 'Card on file'}+ </DetailRow>+ </Match>+ </Switch>+ </dl>+ <p class="text-xs text-ink-extra-muted">+ {autoReloadMode()+ ? 'Leave the limit blank for no limit. Change or turn off auto-reload anytime in usage settings.'+ : offer().teamCard+ ? 'Credits are shared with your team and charged to its card right away.'+ : 'Charged to your card right away. Credits are added immediately.'}+ </p>+ <Show when={error()}>+ {(message) => (+ <p class="text-sm text-failure-ink" role="alert">+ {message()}+ </p>+ )}+ </Show>+ </div>+ )}+ </Show>- <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">- <Button- variant={props.freePlan ? 'primary' : 'ghost'}- class="px-3 py-1.5"- onClick={props.onOpenSettings}+ <footer class="flex flex-col-reverse gap-2 border-t border-edge-muted px-6 py-4 sm:flex-row sm:items-center sm:justify-between">+ <Show+ when={props.offer}+ fallback={<span class="hidden sm:block" />}>- {props.freePlan ? 'View plans' : 'Open usage settings'}- </Button>- <div class="flex gap-2 sm:justify-end"><Buttonvariant="ghost"- class="px-3 py-1.5"- onClick={props.onClose}+ class="sm:-ml-3"+ onClick={props.onOpenSettings}>+ Usage settings+ </Button>+ </Show>+ <div class="flex flex-col-reverse gap-2 sm:flex-row">+ <Button variant="ghost" onClick={props.onClose}>Dismiss</Button>+ <Button+ variant="primary"+ disabled={+ props.offer?.pending || (limitReached() && !fixCard())+ }+ onClick={onPrimary}+ >+ {primaryLabel()}+ </Button></div>- </div>+ </footer></section></Surface></Dialog>diff --git a/apps/web/src/features/usage/components/credit-purchase-dialog.tsx b/apps/web/src/features/usage/components/credit-purchase-dialog.tsxindex 51fa6842b8..098faa1e13 100644--- a/apps/web/src/features/usage/components/credit-purchase-dialog.tsx+++ b/apps/web/src/features/usage/components/credit-purchase-dialog.tsx@@ -5,6 +5,8 @@ import { formatCreditBalance } from '../core/usage';export function CreditPurchaseDialog(props: {sharedWithTeam?: boolean;+ /** A team member buying on the team owner's card. */+ teamCard?: boolean;selection: number | 'other';customAmount: string;amountCents: number | undefined;@@ -12,7 +14,7 @@ export function CreditPurchaseDialog(props: {onCustomAmount: (amount: string) => void;onClose: () => void;onRestoreFocus?: () => void;- onCheckout: () => void;+ onBuy: () => void;onViewPlans?: () => void;pending: boolean;disabled: boolean;@@ -97,8 +99,9 @@ export function CreditPurchaseDialog(props: {</div></div><p class="text-xs text-ink-muted">- Choose or add your payment method and review your purchase in Stripe- Checkout.+ {props.teamCard+ ? "Charged right away to your team owner's card on file."+ : 'Charged right away to your card on file.'}</p><Show when={props.notice}><p class="text-sm text-ink-muted" role="status">@@ -120,9 +123,11 @@ export function CreditPurchaseDialog(props: {<Buttonvariant="primary"disabled={props.disabled || props.pending}- onClick={props.onCheckout}+ onClick={props.onBuy}>- {props.pending ? 'Opening checkout…' : 'Continue to checkout'}+ {props.pending+ ? 'Charging…'+ : `Buy ${formatCreditBalance(props.amountCents ?? 0)} in credits`}</Button>}>diff --git a/apps/web/src/features/usage/context/usage-context.ts b/apps/web/src/features/usage/context/usage-context.tsindex 717ebfa5bb..cbcc0f1a1b 100644--- a/apps/web/src/features/usage/context/usage-context.ts+++ b/apps/web/src/features/usage/context/usage-context.ts@@ -13,10 +13,25 @@ export type UsageContext = {loading: Accessor<boolean>;failed: Accessor<boolean>;refresh: () => void;- checkout: {+ /** One-time credit purchases charged to the card on file (the team owner's+ * for a member). Resolves to how the charge ended; rejects when refused.+ * When the card can't be charged off-session (none on file, or it needs+ * 3-D Secure) nothing is charged and the payer can `checkout`. */+ creditPurchase: {pending: Accessor<boolean>;supportedAmounts: Accessor<readonly number[]>;- start: (amountCents: number) => Promise<string>;+ /** Resolves to how the charge ended and the amount it was for (a retry+ * of a declined purchase charges that purchase's amount). */+ buy: (amountCents: number) => Promise<{+ status:+ | 'paid'+ | 'declined'+ | 'payment_method_required'+ | 'authentication_required';+ amountCents: number;+ }>;+ /** Stripe Checkout for the same pack; resolves to its URL. Payer only. */+ checkout: (amountCents: number) => Promise<string>;};autoReload: {settings: Accessor<AutoReloadSettings>;diff --git a/apps/web/src/features/usage/core/usage.ts b/apps/web/src/features/usage/core/usage.tsindex 678b932b3c..53c5b2fa75 100644--- a/apps/web/src/features/usage/core/usage.ts+++ b/apps/web/src/features/usage/core/usage.ts@@ -11,6 +11,9 @@ export type UsageSummary = {suspended: boolean;budget?: AutoReloadBudget;};+ /** The monthly credit limit on one-time purchases and what is left of it;+ * absent when there is no limit. A team member always has one. */+ purchaseLimit?: { limitCents: number; remainingCents: number };};export type UsagePreviewPlan = 'free' | 'paid';@@ -24,8 +27,8 @@ export type AutoReloadSettings = {export const DEFAULT_AUTO_RELOAD: AutoReloadSettings = {enabled: false,- minimumBalanceCents: 1_000,- targetBalanceCents: 10_000,+ minimumBalanceCents: 500,+ targetBalanceCents: 2_500,monthlySpendLimitCents: null,};diff --git a/apps/web/src/features/usage/primitives/auto-reload-form.test.ts b/apps/web/src/features/usage/primitives/auto-reload-form.test.tsindex 29068ffdee..bd8851ee97 100644--- a/apps/web/src/features/usage/primitives/auto-reload-form.test.ts+++ b/apps/web/src/features/usage/primitives/auto-reload-form.test.ts@@ -3,7 +3,7 @@ import { DEFAULT_AUTO_RELOAD } from '../core/usage';import { createAutoReloadForm } from './auto-reload-form';describe('Auto-Reload form', () => {- it('defaults to $10/$100, accepts an optional cap and rejects an inverted balance range', () => {+ it('defaults to $5/$25, accepts an optional cap and rejects an inverted balance range', () => {const form = createAutoReloadForm(DEFAULT_AUTO_RELOAD);expect(form.error()).toBeUndefined();expect(form.settings()).toEqual({ ...DEFAULT_AUTO_RELOAD, enabled: true });diff --git a/apps/web/src/features/usage/queries/usage-summary.test.ts b/apps/web/src/features/usage/queries/usage-summary.test.tsindex 11e5de2a19..f5e3880d8e 100644--- a/apps/web/src/features/usage/queries/usage-summary.test.ts+++ b/apps/web/src/features/usage/queries/usage-summary.test.ts@@ -152,6 +152,66 @@ describe('automatic reload', () => {});});+ it('starts an off Auto-Reload from the catalog defaults and the plan limit, but keeps an opted-in payer’s settings', () => {+ const catalog = {+ plans: [+ {+ tier: 'premium' as const,+ monthly_price_cents: 4_000,+ included_ai_cents_per_seat: 2_000,+ purchasable: true,+ auto_reload_default_monthly_limit_cents: 20_000,+ },+ {+ tier: 'max' as const,+ monthly_price_cents: 20_000,+ included_ai_cents_per_seat: 10_000,+ purchasable: true,+ auto_reload_default_monthly_limit_cents: 100_000,+ },+ ],+ credit_packs_cents: [1_000],+ overage_limit_min_cents: 500,+ overage_limit_max_cents: 500_000,+ auto_reload_defaults: {+ minimum_balance_cents: 500,+ target_balance_cents: 2_500,+ },+ };+ const stored = {+ minimum_balance_cents: 1_000,+ target_balance_cents: 10_000,+ monthly_spend_limit_cents: null,+ suspended: false,+ active: false,+ };+ expect(+ toUsageSummary({ ...snapshot, tier: 'max', auto_reload: stored }, catalog)+ .autoReload.settings+ ).toEqual({+ enabled: false,+ minimumBalanceCents: 500,+ targetBalanceCents: 2_500,+ monthlySpendLimitCents: 100_000,+ });+ expect(+ toUsageSummary(+ {+ ...snapshot,+ tier: 'premium',+ overage_enabled: true,+ auto_reload: stored,+ },+ catalog+ ).autoReload.settings+ ).toEqual({+ enabled: true,+ minimumBalanceCents: 1_000,+ targetBalanceCents: 10_000,+ monthlySpendLimitCents: null,+ });+ });+it('falls back to the default thresholds when the snapshot has none', () => {expect(toUsageSummary(snapshot).autoReload).toEqual({settings: DEFAULT_AUTO_RELOAD,diff --git a/apps/web/src/features/usage/queries/usage-summary.ts b/apps/web/src/features/usage/queries/usage-summary.tsindex 86114d9c78..d5fe65cde4 100644--- a/apps/web/src/features/usage/queries/usage-summary.ts+++ b/apps/web/src/features/usage/queries/usage-summary.ts@@ -1,19 +1,51 @@-import type { AiUsageSnapshot } from '@service-auth/ai-billing-types';+import type {+ AiPlanCatalog,+ AiUsageSnapshot,+} from '@service-auth/ai-billing-types';import {+ type AutoReloadSettings,DEFAULT_AUTO_RELOAD,monthlyUsagePercent,type UsageSummary,} from '../core/usage';-function toAutoReload(snapshot: AiUsageSnapshot): UsageSummary['autoReload'] {+/**+ * The thresholds Auto-Reload starts from while it is off: the catalog's+ * defaults and the plan's monthly limit, rather than whatever an account row+ * stored before the payer opted in.+ */+function startingThresholds(+ snapshot: AiUsageSnapshot,+ catalog: AiPlanCatalog+): Omit<AutoReloadSettings, 'enabled'> {+ const defaults = catalog.auto_reload_defaults;+ const plan = catalog.plans.find((entry) => entry.tier === snapshot.tier);+ return {+ minimumBalanceCents:+ defaults?.minimum_balance_cents ??+ DEFAULT_AUTO_RELOAD.minimumBalanceCents,+ targetBalanceCents:+ defaults?.target_balance_cents ?? DEFAULT_AUTO_RELOAD.targetBalanceCents,+ monthlySpendLimitCents:+ plan?.auto_reload_default_monthly_limit_cents ?? null,+ };+}++function toAutoReload(+ snapshot: AiUsageSnapshot,+ catalog: AiPlanCatalog | undefined+): UsageSummary['autoReload'] {const reload = snapshot.auto_reload;- const thresholds = reload- ? {- minimumBalanceCents: reload.minimum_balance_cents,- targetBalanceCents: reload.target_balance_cents,- monthlySpendLimitCents: reload.monthly_spend_limit_cents,- }- : DEFAULT_AUTO_RELOAD;+ const thresholds =+ !snapshot.overage_enabled && catalog+ ? startingThresholds(snapshot, catalog)+ : reload+ ? {+ minimumBalanceCents: reload.minimum_balance_cents,+ targetBalanceCents: reload.target_balance_cents,+ monthlySpendLimitCents: reload.monthly_spend_limit_cents,+ }+ : DEFAULT_AUTO_RELOAD;return {settings: { ...thresholds, enabled: snapshot.overage_enabled },suspended: reload?.suspended ?? false,@@ -30,7 +62,10 @@ function toAutoReload(snapshot: AiUsageSnapshot): UsageSummary['autoReload'] {};}-export function toUsageSummary(snapshot: AiUsageSnapshot): UsageSummary {+export function toUsageSummary(+ snapshot: AiUsageSnapshot,+ catalog?: AiPlanCatalog+): UsageSummary {return {monthlyPercent: monthlyUsagePercent(snapshot.used_cents,@@ -51,7 +86,19 @@ export function toUsageSummary(snapshot: AiUsageSnapshot): UsageSummary {suspended: snapshot.overage_suspended,}: undefined,- autoReload: toAutoReload(snapshot),+ autoReload: toAutoReload(snapshot, catalog),+ ...(snapshot.credit_purchase?.monthly_limit_cents != null+ ? {+ purchaseLimit: {+ limitCents: snapshot.credit_purchase.monthly_limit_cents,+ remainingCents: Math.max(+ 0,+ snapshot.credit_purchase.monthly_limit_cents -+ snapshot.credit_purchase.committed_cents+ ),+ },+ }+ : {}),billingAccess:snapshot.tier === 'free'? 'free'diff --git a/apps/web/src/features/usage/usage.tsx b/apps/web/src/features/usage/usage.tsxindex 144c43b14c..7c58f0b009 100644--- a/apps/web/src/features/usage/usage.tsx+++ b/apps/web/src/features/usage/usage.tsx@@ -8,11 +8,13 @@ import {} from '@core/constant/featureFlags';import { useSettingsState } from '@core/constant/SettingsState';import { fireAndForget } from '@core/util/fireAndForget';+import { getWebOrigin } from '@core/util/webOrigin';import {useAiBillingPlansQuery,useAiBillingSummaryQuery,useCreateAiCreditCheckoutMutation,useCreateBillingPortalMutation,+ usePurchaseAiCreditsMutation,useUpdateAiAutoReloadMutation,useUpdateAiOverageMutation,} from '@queries/auth';@@ -31,6 +33,7 @@ export function Usage() {const summary = useAiBillingSummaryQuery();const plans = useAiBillingPlansQuery();const aiUsageBilling = useFeatureFlag(enableAiUsageBilling);+ const purchase = usePurchaseAiCreditsMutation();const checkout = useCreateAiCreditCheckoutMutation();const portal = useCreateBillingPortalMutation();const overage = useUpdateAiOverageMutation();@@ -45,13 +48,16 @@ export function Usage() {const available = () =>!usagePreview.beforeLaunch() &&isUsageAvailable(PROD_MODE_ENV && !LOCAL_ONLY, aiUsageBilling().enabled);- const returnUrl = `${window.location.origin}/app/settings/usage`;+ // Stripe can't return to the native app's own origin.+ const returnUrl = `${getWebOrigin()}/app/settings/usage`;const usageSummary = () => {const snapshot = usagePreview.withPreview(summary.isSuccess ? summary.data : undefined,plans.isSuccess ? plans.data.plans : undefined);- return snapshot ? toUsageSummary(snapshot) : undefined;+ return snapshot+ ? toUsageSummary(snapshot, plans.isSuccess ? plans.data : undefined)+ : undefined;};const canChangeAutoReload = () =>available() &&@@ -71,22 +77,33 @@ export function Usage() {refresh: () => {fireAndForget(summary.refetch(), 'usage');},- checkout: {- pending: () => checkout.isPending,+ creditPurchase: {+ pending: () => purchase.isPending || checkout.isPending,supportedAmounts: () =>plans.isSuccess? plans.data.credit_packs_cents: [1_000, 2_500, 5_000, 10_000],- start: async (amountCents) => {+ // Team members buy on the owner's card within the team's monthly limit.+ buy: async (amountCents) => {if (!available() ||previewing() ||!summary.isSuccess ||summary.data.unlimited ||- summary.data.tier === 'free' ||- !summary.data.can_manage_billing+ summary.data.tier === 'free')throw new Error('Credit purchase unavailable');+ const result = await purchase.mutateAsync({ amountCents });+ return { status: result.status, amountCents: result.amountCents };+ },+ checkout: async (amountCents) => {+ if (+ !available() ||+ previewing() ||+ !summary.isSuccess ||+ !summary.data.can_manage_billing+ )+ throw new Error('Credit checkout unavailable');return await checkout.mutateAsync({amountCents,successUrl: `${returnUrl}?aiCreditsSuccess=true`,diff --git a/apps/web/src/features/usage/views/credit-purchase.tsx b/apps/web/src/features/usage/views/credit-purchase.tsxindex 5c31b50d33..4e2a989d51 100644--- a/apps/web/src/features/usage/views/credit-purchase.tsx+++ b/apps/web/src/features/usage/views/credit-purchase.tsx@@ -1,9 +1,20 @@+import { toast } from '@core/component/Toast/Toast';import { fireAndForget } from '@core/util/fireAndForget';-import { thrownResultErrorHasCode } from '@core/util/result';+import { ThrownResultError, thrownResultErrorHasCode } from '@core/util/result';import { createSignal } from 'solid-js';import { CreditPurchaseDialog } from '../components/credit-purchase-dialog';import type { UsageContext } from '../context/usage-context';-import { parseDollarInput } from '../core/usage';+import { formatCreditBalance, parseDollarInput } from '../core/usage';++/** The server's reason for a refused purchase, as a sentence. */+function purchaseRejection(error: unknown) {+ const message =+ error instanceof ThrownResultError &&+ error.errors.find((e) => e.code === 'CREDIT_PURCHASE_REJECTED')?.message;+ return message+ ? `${message.charAt(0).toUpperCase()}${message.slice(1)}.`+ : "Couldn't buy credits. Please try again.";+}export function CreditPurchaseView(props: {context: UsageContext;@@ -22,43 +33,90 @@ export function CreditPurchaseView(props: {};const previewing = () =>props.context.developer?.active() || props.context.autoReload.preview();+ const teamCard = () =>+ props.context.summary()?.billingAccess === 'team-member';const notice = () => {if (previewing())return 'Credit purchases are disabled during the developer preview.';- if (props.context.summary()?.unlimited)+ const summary = props.context.summary();+ if (summary?.unlimited)return 'Your plan includes unlimited AI usage. No additional credits are needed.';- if (props.context.summary()?.billingAccess === 'free')+ if (summary?.billingAccess === 'free')return 'Subscribe to a paid plan to buy additional usage credits.';- if (props.context.summary()?.billingAccess !== 'payer')- return 'Your team owner manages usage credits. Ask them to add credits.';const amount = amountCents();if (amount === undefined)return 'Enter an amount greater than $0, using at most two decimal places.';- if (!props.context.checkout.supportedAmounts().includes(amount))+ if (!props.context.creditPurchase.supportedAmounts().includes(amount))return 'Custom credit amounts are not available yet. Choose $25, $50, or $100.';+ const limit = summary?.purchaseLimit;+ if (limit && amount > limit.remainingCents)+ return `${formatCreditBalance(limit.remainingCents)} of ${teamCard() ? "your team's" : 'your'} ${formatCreditBalance(limit.limitCents)} monthly credit limit is left. ${teamCard() ? 'Ask your team owner to raise it.' : 'Raise it in Automatic reload settings.'}`;+ };+ /** The card on file can't be charged off-session (none on file, or it+ * needs 3-D Secure): the payer pays this pack through Stripe Checkout. */+ const checkout = async (+ amount: number,+ reason: 'payment_method_required' | 'authentication_required'+ ) => {+ if (teamCard()) {+ setError(+ reason === 'payment_method_required'+ ? "Your team doesn't have a card on file. Ask your team owner to add one."+ : "Your team's card needs verification. Ask your team owner to buy credits or update the card."+ );+ return;+ }+ try {+ props.context.navigateToPayment(+ await props.context.creditPurchase.checkout(amount)+ );+ } catch {+ setError("Couldn't open checkout. Please try again.");+ }};- const checkout = async () => {+ const buy = async () => {const amount = amountCents();- if (notice() || amount === undefined || props.context.checkout.pending())+ if (+ notice() ||+ amount === undefined ||+ props.context.creditPurchase.pending()+ )return;setError(undefined);try {- const url = await props.context.checkout.start(amount);- props.context.navigateToPayment(url);+ const { status, amountCents: charged } =+ await props.context.creditPurchase.buy(amount);+ if (+ status === 'payment_method_required' ||+ status === 'authentication_required'+ ) {+ await checkout(amount, status);+ return;+ }+ if (status === 'declined') {+ setError(+ teamCard()+ ? "Your team's card was declined. Ask your team owner to update it."+ : 'Your card was declined. Update your payment method, then try again.'+ );+ return;+ }props.onClose();+ toast.success(`Added ${formatCreditBalance(charged)} in credits.`);} catch (error) {const needsPlan = thrownResultErrorHasCode(error, 'PAID_PLAN_REQUIRED');setSubscriptionRequired(needsPlan);setError(needsPlan? 'Subscribe to a paid plan to buy additional usage credits.'- : "Couldn't start checkout. Please try again."+ : purchaseRejection(error));}};return (<CreditPurchaseDialogsharedWithTeam={props.context.summary()?.creditScope === 'team'}+ teamCard={teamCard()}selection={selection()}customAmount={customAmount()}amountCents={amountCents()}@@ -69,7 +127,7 @@ export function CreditPurchaseView(props: {onCustomAmount={setCustomAmount}onClose={props.onClose}onRestoreFocus={props.onRestoreFocus}- onCheckout={() => fireAndForget(checkout(), 'usage')}+ onBuy={() => fireAndForget(buy(), 'usage')}onViewPlans={(props.context.summary()?.billingAccess === 'free' && !previewing()) ||subscriptionRequired()@@ -79,7 +137,7 @@ export function CreditPurchaseView(props: {}: undefined}- pending={props.context.checkout.pending()}+ pending={props.context.creditPurchase.pending()}disabled={!!notice()}notice={notice()}error={error()}diff --git a/apps/web/src/features/usage/views/usage-settings.test.tsx b/apps/web/src/features/usage/views/usage-settings.test.tsxindex f68b4e658e..1c02614e95 100644--- a/apps/web/src/features/usage/views/usage-settings.test.tsx+++ b/apps/web/src/features/usage/views/usage-settings.test.tsx@@ -11,6 +11,16 @@ import { fixtureSnapshot } from '../../billing-lab/queries/fixture-snapshot';import { toUsageSummary } from '../queries/usage-summary';import { UsageSettingsView } from './usage-settings';+const toastMocks = vi.hoisted(() => ({ success: vi.fn() }));+vi.mock('@core/component/Toast/Toast', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@core/component/Toast/Toast')>();+ return {+ ...actual,+ toast: { ...actual.toast, success: toastMocks.success },+ };+});+beforeEach(() => vi.spyOn(window, 'scrollTo').mockImplementation(() => {}));afterEach(() => {cleanup();@@ -125,19 +135,25 @@ it('removes the cap notice when the simulated calendar month resets', () => {expect(lab.usage.autoReload.settings().enabled).toBe(true);});-it('shows team-paid members only a team-managed notice for usage credits', () => {+it('lets team-paid members add credits within the team limit, without Auto-Reload', () => {const lab = createBillingLab('team-member');render(() => <UsageSettingsView context={lab.usage} />);+ expect(screen.getByText(/credits remaining/)).toBeTruthy();expect(- screen.getByText('Usage credits are managed by your team.')+ screen.getByText(+ /You can add \$[\d,.]+ more this month, within your team's/+ )).toBeTruthy();- expect(screen.queryByRole('button', { name: 'Add more' })).toBeNull();- expect(screen.queryByRole('button', { name: 'Add credits' })).toBeNull();- expect(screen.queryByText(/credits remaining/)).toBeNull();expect(screen.queryByText('Automatic reload')).toBeNull();expect(screen.queryByRole('button', { name: /Automatic reload/ })).toBeNull();- expect(screen.queryByRole('button', { name: 'Adjust limit' })).toBeNull();- expect(screen.queryByRole('dialog')).toBeNull();++ fireEvent.click(screen.getByRole('button', { name: 'Add more' }));+ expect(+ screen.getByText("Charged right away to your team owner's card on file.")+ ).toBeTruthy();+ expect(+ screen.getByRole('button', { name: 'Buy $25 in credits' })+ ).toBeTruthy();});it.each(['pro', 'team-owner'] as const)(@@ -208,3 +224,149 @@ it('keeps team credit labels and the personal allowance explanation for an ownerscreen.getByText('These credits are shared by your entire team.')).toBeTruthy();});++it('sends a payer with no card on file to checkout for the same pack', async () => {+ const lab = createBillingLab('pro');+ const checkout = vi.fn(async () => 'https://checkout.stripe.test/session');+ const navigateToPayment = vi.fn();+ render(() => (+ <UsageSettingsView+ context={{+ ...lab.usage,+ creditPurchase: {+ ...lab.usage.creditPurchase,+ buy: async () => ({+ status: 'payment_method_required',+ amountCents: 2_500,+ }),+ checkout,+ },+ navigateToPayment,+ }}+ />+ ));++ fireEvent.click(screen.getByRole('button', { name: 'Add more' }));+ fireEvent.click(screen.getByRole('button', { name: 'Buy $25 in credits' }));++ await waitFor(() =>+ expect(navigateToPayment).toHaveBeenCalledWith(+ 'https://checkout.stripe.test/session'+ )+ );+ expect(checkout).toHaveBeenCalledWith(2_500);+});++it('asks a team member to have the owner add a card when the team has none', async () => {+ const lab = createBillingLab('team-member');+ const checkout = vi.fn(async () => 'https://checkout.stripe.test/session');+ render(() => (+ <UsageSettingsView+ context={{+ ...lab.usage,+ creditPurchase: {+ ...lab.usage.creditPurchase,+ buy: async () => ({+ status: 'payment_method_required',+ amountCents: 2_500,+ }),+ checkout,+ },+ }}+ />+ ));++ fireEvent.click(screen.getByRole('button', { name: 'Add more' }));+ fireEvent.click(screen.getByRole('button', { name: 'Buy $25 in credits' }));++ expect(+ await screen.findByText(+ "Your team doesn't have a card on file. Ask your team owner to add one."+ )+ ).toBeTruthy();+ expect(checkout).not.toHaveBeenCalled();+});++it('sends a payer whose card needs authentication to checkout', async () => {+ const lab = createBillingLab('pro');+ const checkout = vi.fn(async () => 'https://checkout.stripe.test/session');+ const navigateToPayment = vi.fn();+ render(() => (+ <UsageSettingsView+ context={{+ ...lab.usage,+ creditPurchase: {+ ...lab.usage.creditPurchase,+ buy: async () => ({+ status: 'authentication_required',+ amountCents: 2_500,+ }),+ checkout,+ },+ navigateToPayment,+ }}+ />+ ));++ fireEvent.click(screen.getByRole('button', { name: 'Add more' }));+ fireEvent.click(screen.getByRole('button', { name: 'Buy $25 in credits' }));++ await waitFor(() =>+ expect(navigateToPayment).toHaveBeenCalledWith(+ 'https://checkout.stripe.test/session'+ )+ );+ expect(checkout).toHaveBeenCalledWith(2_500);+});++it('asks a team member to have the owner verify a card that needs authentication', async () => {+ const lab = createBillingLab('team-member');+ const checkout = vi.fn(async () => 'https://checkout.stripe.test/session');+ render(() => (+ <UsageSettingsView+ context={{+ ...lab.usage,+ creditPurchase: {+ ...lab.usage.creditPurchase,+ buy: async () => ({+ status: 'authentication_required',+ amountCents: 2_500,+ }),+ checkout,+ },+ }}+ />+ ));++ fireEvent.click(screen.getByRole('button', { name: 'Add more' }));+ fireEvent.click(screen.getByRole('button', { name: 'Buy $25 in credits' }));++ expect(+ await screen.findByText(+ "Your team's card needs verification. Ask your team owner to buy credits or update the card."+ )+ ).toBeTruthy();+ expect(checkout).not.toHaveBeenCalled();+});++it('reports the amount actually charged, not the pack that was picked', async () => {+ const lab = createBillingLab('pro');+ render(() => (+ <UsageSettingsView+ context={{+ ...lab.usage,+ creditPurchase: {+ ...lab.usage.creditPurchase,+ buy: async () => ({ status: 'paid', amountCents: 10_000 }),+ },+ }}+ />+ ));++ fireEvent.click(screen.getByRole('button', { name: 'Add more' }));+ fireEvent.click(screen.getByRole('button', { name: 'Buy $25 in credits' }));++ await waitFor(() =>+ expect(toastMocks.success).toHaveBeenCalledWith('Added $100 in credits.')+ );+});diff --git a/apps/web/src/features/usage/views/usage-settings.tsx b/apps/web/src/features/usage/views/usage-settings.tsxindex 2e176077ae..6266c1612f 100644--- a/apps/web/src/features/usage/views/usage-settings.tsx+++ b/apps/web/src/features/usage/views/usage-settings.tsx@@ -42,7 +42,7 @@ export function UsageSettingsView(props: { context: UsageContext }) {}pending={props.context.autoReload.pending() ||- props.context.checkout.pending()+ props.context.creditPurchase.pending()}onAdjust={(trigger) => {autoReloadTrigger = trigger;@@ -257,9 +257,44 @@ export function UsageSettingsView(props: { context: UsageContext }) {}><SettingsCard>- <p class="p-4 text-sm text-ink-muted">- Usage credits are managed by your team.- </p>+ <SettingsRow+ label={+ <span class="font-medium">+ {formatCreditBalance(summary().creditBalanceCents)}{' '}+ credits remaining+ </span>+ }+ description={+ <Show+ when={summary().purchaseLimit}+ fallback="Shared team balance"+ >+ {(limit) =>+ `Shared team balance. You can add ${formatCreditBalance(limit().remainingCents)} more this month, within your team's ${formatCreditBalance(limit().limitCents)} limit.`+ }+ </Show>+ }+ >+ <Button+ ref={(button) => {+ purchaseTrigger = button;+ }}+ variant="secondary"+ size="sm"+ class="rounded-full px-4"+ disabled={props.context.creditPurchase+ .supportedAmounts()+ .every(+ (cents) =>+ cents >+ (summary().purchaseLimit?.remainingCents ??+ Number.POSITIVE_INFINITY)+ )}+ onClick={() => setPurchaseOpen(true)}+ >+ Add more+ </Button>+ </SettingsRow></SettingsCard></Show></SettingsSection>diff --git a/apps/web/src/lib/queries/auth/ai-billing.ts b/apps/web/src/lib/queries/auth/ai-billing.tsindex caf676dd86..b753049840 100644--- a/apps/web/src/lib/queries/auth/ai-billing.ts+++ b/apps/web/src/lib/queries/auth/ai-billing.ts@@ -149,6 +149,27 @@ export function useUpdateAiAutoReloadMutation() {}));}+/** Buy a credit pack on the payer's card on file; updates the summary. */+export function usePurchaseAiCreditsMutation() {+ return useMutation(() => ({+ mutationFn: async (args: { amountCents: number }) =>+ await throwOnErr(+ async () => await authServiceClient.purchaseAiCredits(args)+ ),+ onSuccess: (result) => {+ if (result.snapshot) {+ queryClient.setQueryData(+ authKeys.aiBillingSummary.queryKey,+ result.snapshot+ );+ return;+ }+ // The purchase happened but its summary could not be read.+ fireAndForget(invalidateAiBillingSummary(), 'ai-billing');+ },+ }));+}+/** Start a Stripe Checkout for a credit pack; resolves to the hosted URL. */export function useCreateAiCreditCheckoutMutation() {return useMutation(() => ({diff --git a/apps/web/src/lib/queries/auth/index.ts b/apps/web/src/lib/queries/auth/index.tsindex e729c98911..92624c16ff 100644--- a/apps/web/src/lib/queries/auth/index.ts+++ b/apps/web/src/lib/queries/auth/index.ts@@ -12,6 +12,7 @@ export {useChangePlanMutation,useCreateAiCreditCheckoutMutation,useIncludedAiCentsByTier,+ usePurchaseAiCreditsMutation,useSubscriptionStatusQuery,useUpdateAiAutoReloadMutation,useUpdateAiOverageMutation,diff --git a/apps/web/src/lib/service-clients/service-auth/ai-billing-types.ts b/apps/web/src/lib/service-clients/service-auth/ai-billing-types.tsindex 172df6cb49..bbb5789f90 100644--- a/apps/web/src/lib/service-clients/service-auth/ai-billing-types.ts+++ b/apps/web/src/lib/service-clients/service-auth/ai-billing-types.ts@@ -1,3 +1,5 @@+import type { CreditPurchaseSnapshot } from './generated/schemas/creditPurchaseSnapshot';+import type { CreditPurchaseStatus } from './generated/schemas/creditPurchaseStatus';/*** Hand-written mirrors of the auth service's AI billing OpenAPI types* (`crates/ai_billing`). Replace with the orval-generated schemas on the next@@ -66,6 +68,17 @@ export interface AiUsageSnapshot {uncovered_cents: number;remaining_cents: number;blocked_reason?: AiDenyReason;+ /** The monthly credit limit on this user's one-time purchases; present for+ * paid, metered users. */+ credit_purchase?: CreditPurchaseSnapshot;+}++/** Outcome of `POST /ai-billing/credits/purchase`. */+export interface AiCreditPurchaseResult {+ status: CreditPurchaseStatus;+ amountCents: number;+ /** Absent when the server could not read it after the purchase. */+ snapshot?: AiUsageSnapshot;}export interface AiPlanCatalogEntry {@@ -73,6 +86,9 @@ export interface AiPlanCatalogEntry {monthly_price_cents: number;included_ai_cents_per_seat: number;purchasable: boolean;+ /** Monthly Auto-Reload limit a payer on this plan starts from; absent for+ * plans that cannot reload. */+ auto_reload_default_monthly_limit_cents?: number | null;}/** Thresholds automatic reload starts from before the payer sets their own. */diff --git a/apps/web/src/lib/service-clients/service-auth/client.test.ts b/apps/web/src/lib/service-clients/service-auth/client.test.tsindex 94755a6130..2fa6b4938d 100644--- a/apps/web/src/lib/service-clients/service-auth/client.test.ts+++ b/apps/web/src/lib/service-clients/service-auth/client.test.ts@@ -51,53 +51,68 @@ describe('passwordless code check', () => {});});-describe('credit checkout', () => {- const args = {- amountCents: 2_500,- successUrl:- 'https://localhost:3000/app/settings/usage?aiCreditsSuccess=true',- cancelUrl: 'https://localhost:3000/app/settings/usage?aiCreditsCancel=true',- };-- test('sends the selected pack and return URLs and resolves to the hosted checkout URL', async () => {- fetchCheckout.mockResolvedValueOnce(- ok({ url: 'https://checkout.stripe.com/test' })- );- const result = await authServiceClient.createAiCreditCheckout(args);- expect(result._unsafeUnwrap()).toBe('https://checkout.stripe.com/test');+describe('credit purchase', () => {+ test('sends the selected pack and resolves to the outcome and new position', async () => {+ const outcome = {+ status: 'paid',+ amountCents: 2_500,+ snapshot: { remaining_cents: 100 },+ };+ fetchCheckout.mockResolvedValueOnce(ok(outcome));+ const result = await authServiceClient.purchaseAiCredits({+ amountCents: 2_500,+ });+ expect(result._unsafeUnwrap()).toEqual(outcome);expect(fetchCheckout).toHaveBeenCalledWith(- expect.stringMatching(/\/ai-billing\/credits\/checkout$/),+ expect.stringMatching(/\/ai-billing\/credits\/purchase$/),expect.objectContaining({method: 'POST',- body: JSON.stringify(args),+ body: JSON.stringify({ amountCents: 2_500 }),}));});test.each([- [402, 'PAID_PLAN_REQUIRED'],- [401, 'UNAUTHORIZED'],- [403, 'FORBIDDEN'],- [500, 'SERVER_ERROR'],+ [+ 402,+ '{"error":"a paid plan is required"}',+ 'PAID_PLAN_REQUIRED',+ 'A paid plan is required',+ ],+ [+ 409,+ '{"error":"this purchase would exceed the monthly credit limit"}',+ 'CREDIT_PURCHASE_REJECTED',+ 'this purchase would exceed the monthly credit limit',+ ],+ [409, 'not json', 'CREDIT_PURCHASE_REJECTED', 'Credit purchase rejected'],+ [+ 500,+ '{"error":"internal error"}',+ 'SERVER_ERROR',+ 'Internal server error',+ ],])(- 'preserves a %i response as %s for the checkout view',- async (status, code) => {+ 'reports a %i response for the purchase views',+ async (status, body, code, message) => {fetchCheckout.mockImplementationOnce(async (_input: RequestInfo,- init: FetchWithTokenInit<'PAID_PLAN_REQUIRED'>+ init: FetchWithTokenInit<+ 'PAID_PLAN_REQUIRED' | 'CREDIT_PURCHASE_REJECTED'+ >) => {const error = await init.errorResponseHandler?.(- new Response(JSON.stringify({ error: 'a paid plan is required' }), {- status,- })+ new Response(body, { status }));- if (!error) throw new Error('Expected a checkout error handler');+ if (!error) throw new Error('Expected a purchase error handler');return err([error]);});- const result = await authServiceClient.createAiCreditCheckout(args);- expect(result._unsafeUnwrapErr()[0].code).toBe(code);+ const result = await authServiceClient.purchaseAiCredits({+ amountCents: 2_500,+ });+ expect(result._unsafeUnwrapErr()[0]).toEqual({ code, message });});});diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.tsindex 842d0deeb6..13afbefc80 100644--- a/apps/web/src/lib/service-clients/service-auth/client.ts+++ b/apps/web/src/lib/service-clients/service-auth/client.ts@@ -15,6 +15,7 @@ import { makePersisted } from '@solid-primitives/storage';import { ok } from 'neverthrow';import { createSignal } from 'solid-js';import type {+ AiCreditPurchaseResult,AiPlanCatalog,AiUsageSnapshot,PaidPlan,@@ -933,6 +934,42 @@ export const authServiceClient = {);},+ /** Buy a credit pack now on the payer's card on file. */+ async purchaseAiCredits(args: { amountCents: number }) {+ return await fetchWithAuth<+ AiCreditPurchaseResult,+ 'PAID_PLAN_REQUIRED' | 'CREDIT_PURCHASE_REJECTED'+ >(`${authHost}/ai-billing/credits/purchase`, {+ method: 'POST',+ body: JSON.stringify({ amountCents: args.amountCents }),+ errorResponseHandler: async (response) => {+ if (response.status === 402) {+ return {+ code: 'PAID_PLAN_REQUIRED',+ message: 'A paid plan is required',+ };+ }+ // Over the monthly credit limit, or an earlier purchase is still+ // processing; the body says which.+ if (response.status === 409) {+ const body: unknown = await response.json().catch(() => undefined);+ return {+ code: 'CREDIT_PURCHASE_REJECTED',+ message:+ typeof body === 'object' &&+ body !== null &&+ 'error' in body &&+ typeof body.error === 'string'+ ? body.error+ : 'Credit purchase rejected',+ };+ }+ return statusError(response.status);+ },+ });+ },++ /** Stripe Checkout for a credit pack, for a payer with no card on file. */async createAiCreditCheckout(args: {amountCents: number;successUrl: string;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/client.ts b/apps/web/src/lib/service-clients/service-auth/generated/client.tsindex d219031122..9fb4d0dcb3 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/client.ts@@ -25,6 +25,8 @@ import type {CreateTeamRequest,CreditCheckoutRequestBody,CreditCheckoutResponse,+ CreditPurchaseRequestBody,+ CreditPurchaseResponse,CurrentSystemStatus,CursorApiKeyStatus,CursorModelsResponse,@@ -474,6 +476,82 @@ export const createAiCreditCheckout = async (} as createAiCreditCheckoutResponse;};+/**+ * @summary Buy a credit pack now, charged to the payer's card on file. Any paid team+member may buy, within the team's monthly credit limit.+ */+export type purchaseAiCreditsResponse200 = {+ data: CreditPurchaseResponse;+ status: 200;+};++export type purchaseAiCreditsResponse400 = {+ data: AiBillingErrorBody;+ status: 400;+};++export type purchaseAiCreditsResponse401 = {+ data: void;+ status: 401;+};++export type purchaseAiCreditsResponse402 = {+ data: AiBillingErrorBody;+ status: 402;+};++export type purchaseAiCreditsResponse409 = {+ data: AiBillingErrorBody;+ status: 409;+};++export type purchaseAiCreditsResponse500 = {+ data: AiBillingErrorBody;+ status: 500;+};++export type purchaseAiCreditsResponseSuccess = purchaseAiCreditsResponse200 & {+ headers: Headers;+};+export type purchaseAiCreditsResponseError = (+ | purchaseAiCreditsResponse400+ | purchaseAiCreditsResponse401+ | purchaseAiCreditsResponse402+ | purchaseAiCreditsResponse409+ | purchaseAiCreditsResponse500+) & {+ headers: Headers;+};++export type purchaseAiCreditsResponse =+ | purchaseAiCreditsResponseSuccess+ | purchaseAiCreditsResponseError;++export const getPurchaseAiCreditsUrl = () => {+ return `/ai-billing/credits/purchase`;+};++export const purchaseAiCredits = async (+ creditPurchaseRequestBody: CreditPurchaseRequestBody,+ options?: RequestInit+): Promise<purchaseAiCreditsResponse> => {+ const res = await fetch(getPurchaseAiCreditsUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(creditPurchaseRequestBody),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: purchaseAiCreditsResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as purchaseAiCreditsResponse;+};+/*** @summary Retired direct-usage opt-in. Enabling is rejected; disabling remains supported.*/diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/autoReloadMonthlyBudget.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/autoReloadMonthlyBudget.tsindex 74d0a6e001..d3875f415c 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/autoReloadMonthlyBudget.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/autoReloadMonthlyBudget.ts@@ -9,8 +9,9 @@* Calendar-month commitments that consume the payer's automatic reload cap.*/export interface AutoReloadMonthlyBudget {- /** Reloads paid, pending, or failed with an invoice that can still collect.-Customer cents; manual credit purchases do not count. */+ /** Reloads and one-time card purchases paid, pending, or failed with an+invoice that can still collect. Customer cents; Checkout purchases do+not count. */committed_cents: number;/** Remaining cap cannot fund the minimum automatic reload charge. */limit_reached: boolean;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditPurchaseRequestBody.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditPurchaseRequestBody.tsnew file mode 100644index 0000000000..6e8fd44194--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditPurchaseRequestBody.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Request body for [`purchase_credits_handler`].+ */+export interface CreditPurchaseRequestBody {+ /** One of the catalog's credit packs, cents. */+ amountCents: number;+}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditPurchaseResponse.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditPurchaseResponse.tsnew file mode 100644index 0000000000..93ce642fa1--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditPurchaseResponse.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { CreditPurchaseResponseSnapshot } from './creditPurchaseResponseSnapshot';+import type { CreditPurchaseStatus } from './creditPurchaseStatus';++/**+ * Response for [`purchase_credits_handler`].+ */+export interface CreditPurchaseResponse {+ /** Amount charged, cents: the requested pack, unless an earlier declined+purchase that Stripe collected in the meantime was booked instead. */+ amountCents: number;+ snapshot?: CreditPurchaseResponseSnapshot;+ /** Whether the card on file paid. */+ status: CreditPurchaseStatus;+}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditPurchaseResponseSnapshot.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditPurchaseResponseSnapshot.tsnew file mode 100644index 0000000000..dccf474055--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditPurchaseResponseSnapshot.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { UsageSnapshot } from './usageSnapshot';++export type CreditPurchaseResponseSnapshot = null | UsageSnapshot;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditPurchaseSnapshot.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditPurchaseSnapshot.tsnew file mode 100644index 0000000000..3c7957ee4d--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditPurchaseSnapshot.ts@@ -0,0 +1,21 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { CreditPurchaseSnapshotMonthlyLimitCents } from './creditPurchaseSnapshotMonthlyLimitCents';++/**+ * The monthly credit limit that applies to this user's one-time purchases.+ */+export interface CreditPurchaseSnapshot {+ /** Charged this month so far, including charges that may still collect. */+ committed_cents: number;+ /** Most credits charged to the card on file per UTC calendar month, from+automatic reloads and one-time purchases together, in customer cents.+`null` when the payer set no limit; team members always have one. */+ monthly_limit_cents?: CreditPurchaseSnapshotMonthlyLimitCents;+ /** Start of the next UTC calendar month. */+ resets_at: string;+}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditPurchaseSnapshotMonthlyLimitCents.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditPurchaseSnapshotMonthlyLimitCents.tsnew file mode 100644index 0000000000..fee709639e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditPurchaseSnapshotMonthlyLimitCents.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Most credits charged to the card on file per UTC calendar month, from+automatic reloads and one-time purchases together, in customer cents.+`null` when the payer set no limit; team members always have one.+ */+export type CreditPurchaseSnapshotMonthlyLimitCents = number | null;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditPurchaseStatus.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditPurchaseStatus.tsnew file mode 100644index 0000000000..110a001204--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/creditPurchaseStatus.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * How a one-time credit purchase charged to the card on file ended.+ */+export type CreditPurchaseStatus =+ (typeof CreditPurchaseStatus)[keyof typeof CreditPurchaseStatus];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const CreditPurchaseStatus = {+ paid: 'paid',+ declined: 'declined',+ payment_method_required: 'payment_method_required',+ authentication_required: 'authentication_required',+} as const;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.tsindex 0107412f7b..2a9b1535f3 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts@@ -48,6 +48,12 @@ export * from './createPortalSessionRequest';export * from './createTeamRequest';export * from './creditCheckoutRequestBody';export * from './creditCheckoutResponse';+export * from './creditPurchaseRequestBody';+export * from './creditPurchaseResponse';+export * from './creditPurchaseResponseSnapshot';+export * from './creditPurchaseSnapshot';+export * from './creditPurchaseSnapshotMonthlyLimitCents';+export * from './creditPurchaseStatus';export * from './currentSystemStatus';export * from './currentSystemStatusAllOf';export * from './currentSystemStatusAllOfUpdatedAt';@@ -178,6 +184,7 @@ export * from './patchUserOnboardingRequest';export * from './patchUserTutorialRequest';export * from './permission';export * from './planCatalogEntry';+export * from './planCatalogEntryAutoReloadDefaultMonthlyLimitCents';export * from './planCatalogResponse';export * from './planTier';export * from './postGetNamesRequestBody';@@ -251,6 +258,7 @@ export * from './upstreamErrorCode';export * from './upstreamErrorResponse';export * from './usageSnapshot';export * from './usageSnapshotBlockedReason';+export * from './usageSnapshotCreditPurchase';export * from './userLanguage';export * from './userLanguageLanguage';export * from './userLinkResponse';diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogEntry.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogEntry.tsindex 4db5a90952..894eee3b88 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogEntry.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogEntry.ts@@ -4,12 +4,16 @@* authentication_service* OpenAPI spec version: 0.1.0*/+import type { PlanCatalogEntryAutoReloadDefaultMonthlyLimitCents } from './planCatalogEntryAutoReloadDefaultMonthlyLimitCents';import type { PlanTier } from './planTier';/*** One plan in the catalog.*/export interface PlanCatalogEntry {+ /** Monthly automatic reload limit a payer on this plan starts from,+cents. Absent for plans that cannot reload. */+ auto_reload_default_monthly_limit_cents?: PlanCatalogEntryAutoReloadDefaultMonthlyLimitCents;/** Included AI per seat per period, in cents at provider cost. For thefree plan this is its monthly hard cap. */included_ai_cents_per_seat: number;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogEntryAutoReloadDefaultMonthlyLimitCents.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogEntryAutoReloadDefaultMonthlyLimitCents.tsnew file mode 100644index 0000000000..825ff224a3--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogEntryAutoReloadDefaultMonthlyLimitCents.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Monthly automatic reload limit a payer on this plan starts from,+cents. Absent for plans that cannot reload.+ */+export type PlanCatalogEntryAutoReloadDefaultMonthlyLimitCents = number | null;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshot.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshot.tsindex 57f926ceed..15bc7007f6 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshot.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshot.ts@@ -7,6 +7,7 @@import type { AutoReloadSnapshot } from './autoReloadSnapshot';import type { PlanTier } from './planTier';import type { UsageSnapshotBlockedReason } from './usageSnapshotBlockedReason';+import type { UsageSnapshotCreditPurchase } from './usageSnapshotCreditPurchase';/*** The payer's current-period position, as shown in Billing settings and used@@ -21,6 +22,7 @@ reloads are not suspended. */can_manage_billing: boolean;/** Shared prepaid credit balance, in customer cents. */credit_balance_cents: number;+ credit_purchase?: UsageSnapshotCreditPurchase;/** Shared payer credits already applied to this period, in customer cents. */credits_consumed_cents: number;/** Whether prepaid credits belong to the team, including a team with one seat. */diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshotCreditPurchase.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshotCreditPurchase.tsnew file mode 100644index 0000000000..c87a0dcada--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshotCreditPurchase.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { CreditPurchaseSnapshot } from './creditPurchaseSnapshot';++export type UsageSnapshotCreditPurchase = null | CreditPurchaseSnapshot;diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.jsonindex 125a6f72f1..77d4bd111d 100644--- a/apps/web/src/lib/service-clients/service-auth/openapi.json+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json@@ -347,6 +347,78 @@}}},+ "/ai-billing/credits/purchase": {+ "post": {+ "tags": ["ai_billing"],+ "summary": "Buy a credit pack now, charged to the payer's card on file. Any paid team\nmember may buy, within the team's monthly credit limit.",+ "operationId": "purchase_ai_credits",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreditPurchaseRequestBody"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Purchase outcome and updated position",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreditPurchaseResponse"+ }+ }+ }+ },+ "400": {+ "description": "Invalid pack or no payment account",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AiBillingErrorBody"+ }+ }+ }+ },+ "401": {+ "description": "Unauthorized"+ },+ "402": {+ "description": "A paid plan is required",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AiBillingErrorBody"+ }+ }+ }+ },+ "409": {+ "description": "Over the monthly credit limit, or an earlier purchase is still processing",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AiBillingErrorBody"+ }+ }+ }+ },+ "500": {+ "description": "Internal server error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AiBillingErrorBody"+ }+ }+ }+ }+ }+ }+ },"/ai-billing/overage": {"patch": {"tags": ["ai_billing"],@@ -6217,7 +6289,7 @@"committed_cents": {"type": "integer","format": "int64",- "description": "Reloads paid, pending, or failed with an invoice that can still collect.\nCustomer cents; manual credit purchases do not count."+ "description": "Reloads and one-time card purchases paid, pending, or failed with an\ninvoice that can still collect. Customer cents; Checkout purchases do\nnot count."},"limit_reached": {"type": "boolean",@@ -6603,6 +6675,77 @@}}},+ "CreditPurchaseRequestBody": {+ "type": "object",+ "description": "Request body for [`purchase_credits_handler`].",+ "required": ["amountCents"],+ "properties": {+ "amountCents": {+ "type": "integer",+ "format": "int64",+ "description": "One of the catalog's credit packs, cents."+ }+ }+ },+ "CreditPurchaseResponse": {+ "type": "object",+ "description": "Response for [`purchase_credits_handler`].",+ "required": ["status", "amountCents"],+ "properties": {+ "amountCents": {+ "type": "integer",+ "format": "int64",+ "description": "Amount charged, cents: the requested pack, unless an earlier declined\npurchase that Stripe collected in the meantime was booked instead."+ },+ "snapshot": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/UsageSnapshot",+ "description": "The caller's position after the purchase. Absent when it could not be\nread; the purchase still happened, so refetch the summary instead."+ }+ ]+ },+ "status": {+ "$ref": "#/components/schemas/CreditPurchaseStatus",+ "description": "Whether the card on file paid."+ }+ }+ },+ "CreditPurchaseSnapshot": {+ "type": "object",+ "description": "The monthly credit limit that applies to this user's one-time purchases.",+ "required": ["committed_cents", "resets_at"],+ "properties": {+ "committed_cents": {+ "type": "integer",+ "format": "int64",+ "description": "Charged this month so far, including charges that may still collect."+ },+ "monthly_limit_cents": {+ "type": ["integer", "null"],+ "format": "int64",+ "description": "Most credits charged to the card on file per UTC calendar month, from\nautomatic reloads and one-time purchases together, in customer cents.\n`null` when the payer set no limit; team members always have one."+ },+ "resets_at": {+ "type": "string",+ "format": "date-time",+ "description": "Start of the next UTC calendar month."+ }+ }+ },+ "CreditPurchaseStatus": {+ "type": "string",+ "description": "How a one-time credit purchase charged to the card on file ended.",+ "enum": [+ "paid",+ "declined",+ "payment_method_required",+ "authentication_required"+ ]+ },"CurrentSystemStatus": {"allOf": [{@@ -7932,6 +8075,11 @@"purchasable"],"properties": {+ "auto_reload_default_monthly_limit_cents": {+ "type": ["integer", "null"],+ "format": "int64",+ "description": "Monthly automatic reload limit a payer on this plan starts from,\ncents. Absent for plans that cannot reload."+ },"included_ai_cents_per_seat": {"type": "integer","format": "int64",@@ -8807,6 +8955,17 @@"format": "int64","description": "Shared prepaid credit balance, in customer cents."},+ "credit_purchase": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/CreditPurchaseSnapshot",+ "description": "The monthly credit limit for one-time purchases charged to the card on\nfile. Present for paid, metered users, payer and team members alike."+ }+ ]+ },"credits_consumed_cents": {"type": "integer","format": "int64",diff --git a/crates/agent_code_mode/src/domain/operations.json b/crates/agent_code_mode/src/domain/operations.jsonindex b635cbf1a8..cce3ab58f5 100644--- a/crates/agent_code_mode/src/domain/operations.json+++ b/crates/agent_code_mode/src/domain/operations.json@@ -50,6 +50,7 @@"auth.putAgentApiKey": "Put Agent Api Key","auth.updateAiBillingAutoReload": "Update Ai Billing Auto Reload","auth.createAiCreditCheckout": "Create Ai Credit Checkout",+ "auth.purchaseAiCredits": "Purchase Ai Credits","auth.updateAiBillingOverage": "Update Ai Billing Overage","auth.getAiBillingPlans": "Get Ai Billing Plans","auth.getAiBillingSummary": "Get Ai Billing Summary",diff --git a/crates/agent_inmem/src/testing.rs b/crates/agent_inmem/src/testing.rsindex 85007cc844..3fb7b29f94 100644--- a/crates/agent_inmem/src/testing.rs+++ b/crates/agent_inmem/src/testing.rs@@ -91,6 +91,14 @@ impl ai_billing::domain::BillingService for UnavailableBilling {panic!("admission must not change settings")}+ async fn purchase_credits(+ &self,+ _: &MacroUserIdStr<'_>,+ _: i64,+ ) -> ai_billing::domain::Result<ai_billing::domain::CreditPurchase> {+ panic!("admission must not purchase credits")+ }+async fn create_credit_checkout(&self,_: &MacroUserIdStr<'_>,@@ -124,7 +132,12 @@ impl ai_billing::domain::BillingService for UnavailableBilling {panic!("admission must not handle invoices")}- async fn mark_credit_reload_invoice(&self, _: &str, _: bool) -> ai_billing::domain::Result<()> {+ async fn mark_credit_reload_invoice(+ &self,+ _: &str,+ _: Option<macro_uuid::Uuid>,+ _: bool,+ ) -> ai_billing::domain::Result<()> {panic!("admission must not handle invoices")}}diff --git a/crates/ai_billing/AGENTS.md b/crates/ai_billing/AGENTS.mdindex ea7c3aa6c2..7811674aac 100644--- a/crates/ai_billing/AGENTS.md+++ b/crates/ai_billing/AGENTS.md@@ -51,6 +51,13 @@ provider cost (plus markup for overage).- Usage is cost cents; credits/charges/caps/packs are customer cents — only`AiPricing`'s conversions cross that boundary; never multiply/compare thetwo directly.+- `ai_credit_reload` holds both card-on-file charges: `kind = 'automatic'`+ reloads and `kind = 'purchase'` one-time buys (with `purchased_by`). Both+ count against the payer's monthly limit; automatic retries, orphan sweeps,+ and auto-reload suspension must stay scoped to `automatic`.+- A voided purchase is `failed` with `stripe_invoice_id` cleared, so limit,+ retry, and sweep queries (which count failed rows only with an invoice)+ ignore it without a separate status.## Relateddiff --git a/crates/ai_billing/src/domain.rs b/crates/ai_billing/src/domain.rsindex 24e8c5d128..162b5cce7b 100644--- a/crates/ai_billing/src/domain.rs+++ b/crates/ai_billing/src/domain.rs@@ -26,7 +26,8 @@ pub use models::{AUTO_RELOAD_DEFAULT_MINIMUM_CENTS, AUTO_RELOAD_DEFAULT_TARGET_CENTS,AUTO_RELOAD_TARGET_MAX_CENTS, AiUsageBilling, AllowanceDecision, AllowanceStore,AutoReloadSnapshot, AutoReloadThresholds, BillingError, BillingPeriod, BillingSettings,- CREDIT_PACKS_CENTS, CreditReloadStatus, DenyReason, Entitlement, MIN_STRIPE_CHARGE_CENTS,+ CREDIT_PACKS_CENTS, CreditPurchase, CreditPurchaseSnapshot, CreditPurchaseStatus,+ CreditReloadKind, CreditReloadStatus, DenyReason, Entitlement, MIN_STRIPE_CHARGE_CENTS,OVERAGE_CHARGE_THRESHOLD_CENTS, OVERAGE_LIMIT_MAX_CENTS, OVERAGE_LIMIT_MIN_CENTS,OpenPeriodStart, OverageChargeStatus, PayerScope, PeriodAllowance, PeriodLedger, PlanTier,Result, SeatAllowance, SeatGeneration, SeatUsage, SubscriptionScope, UsagePolicy,@@ -34,8 +35,9 @@ pub use models::{};pub use ports::{BillingRepo, BillingService, CreditCheckoutRequest, CreditReloadRequest, EntitlementSource,- OverageChargeRequest, PaymentGateway, PendingCharge, PendingReload, ResolvedReload,- SettlementCandidates, SettlementOutcome, SettlementTrigger, UsageReader,+ InvoicePayment, InvoiceVoid, OverageChargeRequest, PaymentGateway, PendingCharge,+ PendingReload, PurchaseReservation, ResolvedReload, SettlementCandidates, SettlementOutcome,+ SettlementTrigger, UsageReader,};pub use pricing::{AiPricing, IncludedAllowanceCents, OverageMarkupPercent, PlanAllowances, PricingError,diff --git a/crates/ai_billing/src/domain/admission/test.rs b/crates/ai_billing/src/domain/admission/test.rsindex cd56a72f61..29206abc6b 100644--- a/crates/ai_billing/src/domain/admission/test.rs+++ b/crates/ai_billing/src/domain/admission/test.rs@@ -62,6 +62,13 @@ impl BillingService for FakeBilling {) -> BillingResult<UsageSnapshot> {panic!("admission must not change settings")}+ async fn purchase_credits(+ &self,+ _: &MacroUserIdStr<'_>,+ _: i64,+ ) -> BillingResult<crate::domain::CreditPurchase> {+ panic!("admission must not purchase credits")+ }async fn create_credit_checkout(&self,_: &MacroUserIdStr<'_>,@@ -91,7 +98,12 @@ impl BillingService for FakeBilling {async fn mark_overage_invoice(&self, _: &str, _: bool) -> BillingResult<()> {panic!("admission must not handle invoices")}- async fn mark_credit_reload_invoice(&self, _: &str, _: bool) -> BillingResult<()> {+ async fn mark_credit_reload_invoice(+ &self,+ _: &str,+ _: Option<macro_uuid::Uuid>,+ _: bool,+ ) -> BillingResult<()> {panic!("admission must not handle invoices")}}diff --git a/crates/ai_billing/src/domain/ledger.rs b/crates/ai_billing/src/domain/ledger.rsindex 2f933bea43..0e5db87469 100644--- a/crates/ai_billing/src/domain/ledger.rs+++ b/crates/ai_billing/src/domain/ledger.rs@@ -213,6 +213,7 @@ pub fn build_snapshot(uncovered_cents,remaining_cents,blocked_reason: None,+ credit_purchase: None,};snapshot.blocked_reason = match decide(&snapshot) {AllowanceDecision::Allow => None,diff --git a/crates/ai_billing/src/domain/ledger/test.rs b/crates/ai_billing/src/domain/ledger/test.rsindex 8d154e8b70..27ea9ab8fd 100644--- a/crates/ai_billing/src/domain/ledger/test.rs+++ b/crates/ai_billing/src/domain/ledger/test.rs@@ -232,7 +232,7 @@ fn reload_below_the_stripe_minimum_is_skipped() {#[test]fn default_thresholds_are_valid() {let defaults = AutoReloadThresholds::default();- assert_eq!(defaults, thresholds(1_000, 10_000, None));+ assert_eq!(defaults, thresholds(500, 2_500, None));assert!(defaults.validate().is_ok());}@@ -435,8 +435,8 @@ fn snapshot_reports_auto_reload_settings_and_activity() {PeriodLedger::default(),0,);- assert_eq!(s.auto_reload.minimum_balance_cents, 1_000);- assert_eq!(s.auto_reload.target_balance_cents, 10_000);+ assert_eq!(s.auto_reload.minimum_balance_cents, 500);+ assert_eq!(s.auto_reload.target_balance_cents, 2_500);assert_eq!(s.auto_reload.monthly_spend_limit_cents, None);assert!(!s.auto_reload.suspended);assert!(!s.auto_reload.active, "overage off: reloads never fire");diff --git a/crates/ai_billing/src/domain/models.rs b/crates/ai_billing/src/domain/models.rsindex 306d91e6f5..599f7b939c 100644--- a/crates/ai_billing/src/domain/models.rs+++ b/crates/ai_billing/src/domain/models.rs@@ -54,10 +54,10 @@ pub const OVERAGE_LIMIT_MIN_CENTS: i64 = 500;pub const OVERAGE_LIMIT_MAX_CENTS: i64 = 500_000;/// Credit balance below which an automatic reload fires, unless the payer/// has set their own minimum.-pub const AUTO_RELOAD_DEFAULT_MINIMUM_CENTS: i64 = 1_000;+pub const AUTO_RELOAD_DEFAULT_MINIMUM_CENTS: i64 = 500;/// Credit balance an automatic reload tops up to, unless the payer has set/// their own target.-pub const AUTO_RELOAD_DEFAULT_TARGET_CENTS: i64 = 10_000;+pub const AUTO_RELOAD_DEFAULT_TARGET_CENTS: i64 = 2_500;/// Largest automatic reload target a payer may set.pub const AUTO_RELOAD_TARGET_MAX_CENTS: i64 = 500_000;/// Accrued overage is charged once it reaches this much (or when the period@@ -106,6 +106,16 @@ impl PlanTier {}}+ /// Monthly automatic reload limit a payer on this tier starts from, in+ /// customer cents. `None` for tiers that cannot reload.+ pub const fn default_auto_reload_monthly_limit_cents(self) -> Option<i64> {+ match self {+ PlanTier::Free => None,+ PlanTier::Premium => Some(20_000),+ PlanTier::Max => Some(100_000),+ }+ }+/// AI usage included per seat per period, in cents at provider cost: this/// tier's configured allowance ([`AiPricing::included_allowance_cents_for`])./// For Free this is the whole monthly cap.@@ -551,6 +561,58 @@ pub enum OverageChargeStatus {Failed,}+/// What a card-on-file credit charge is for. Both kinds count against the+/// payer's monthly credit limit.+#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display, strum::EnumString)]+#[strum(serialize_all = "snake_case")]+pub enum CreditReloadKind {+ /// Bought by Auto-Reload when the balance fell under the minimum.+ Automatic,+ /// Bought once by the payer or a team member.+ Purchase,+}++/// How a one-time credit purchase charged to the card on file ended.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum CreditPurchaseStatus {+ /// Collected and booked as credits.+ Paid,+ /// The card was declined. The invoice stays open for the provider's+ /// retries; buying again retries it instead of charging twice.+ Declined,+ /// The payer has no card on file. Nothing was reserved or charged; the+ /// payer can buy the same pack through checkout instead.+ PaymentMethodRequired,+ /// The card needs the cardholder to authenticate (3-D Secure), which an+ /// off-session charge can't do. The invoice was voided, so nothing was+ /// charged; the payer can buy the same pack through checkout instead.+ AuthenticationRequired,+}++/// A one-time credit purchase charged to the payer's card on file.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct CreditPurchase {+ /// Amount charged, customer cents. A retry of an earlier declined+ /// purchase charges that purchase's amount.+ pub amount_cents: i64,+ /// How the charge ended.+ pub status: CreditPurchaseStatus,+}++/// The monthly credit limit that applies to this user's one-time purchases.+#[derive(Debug, Clone, Serialize, ToSchema)]+pub struct CreditPurchaseSnapshot {+ /// Most credits charged to the card on file per UTC calendar month, from+ /// automatic reloads and one-time purchases together, in customer cents.+ /// `null` when the payer set no limit; team members always have one.+ pub monthly_limit_cents: Option<i64>,+ /// Charged this month so far, including charges that may still collect.+ pub committed_cents: i64,+ /// Start of the next UTC calendar month.+ pub resets_at: DateTime<Utc>,+}+/// Lifecycle of an automatic credit reload pushed to Stripe.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,@@ -624,8 +686,9 @@ pub enum AllowanceDecision {/// Calendar-month commitments that consume the payer's automatic reload cap.#[derive(Debug, Clone, Serialize, ToSchema)]pub struct AutoReloadMonthlyBudget {- /// Reloads paid, pending, or failed with an invoice that can still collect.- /// Customer cents; manual credit purchases do not count.+ /// Reloads and one-time card purchases paid, pending, or failed with an+ /// invoice that can still collect. Customer cents; Checkout purchases do+ /// not count.pub committed_cents: i64,/// Start of the next UTC calendar month, independently of subscription renewal.pub resets_at: DateTime<Utc>,@@ -702,6 +765,10 @@ pub struct UsageSnapshot {/// Why requests are refused right now, if they are.#[serde(skip_serializing_if = "Option::is_none")]pub blocked_reason: Option<DenyReason>,+ /// The monthly credit limit for one-time purchases charged to the card on+ /// file. Present for paid, metered users, payer and team members alike.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub credit_purchase: Option<CreditPurchaseSnapshot>,}/// Errors raised by the billing domain.@@ -726,6 +793,16 @@ pub enum BillingError {/// offered range ([`AutoReloadThresholds::validate`]).#[error("invalid automatic reload settings: {0}")]InvalidAutoReload(&'static str),+ /// The purchase would take this month's card charges past the monthly+ /// credit limit.+ #[error("this purchase would exceed the monthly credit limit")]+ CreditLimitExceeded {+ /// What can still be charged this month, customer cents.+ remaining_cents: i64,+ },+ /// An earlier purchase is still with the payment provider.+ #[error("an earlier credit purchase is still being processed")]+ PurchaseInProgress,/// The payer has no Stripe customer to bill.#[error("no payment account on file")]NoStripeCustomer,diff --git a/crates/ai_billing/src/domain/ports.rs b/crates/ai_billing/src/domain/ports.rsindex d03a7fad99..e78f965073 100644--- a/crates/ai_billing/src/domain/ports.rs+++ b/crates/ai_billing/src/domain/ports.rs@@ -5,9 +5,9 @@ use super::financial::FundingPeriod;use super::ledger::SettlementPolicy;use super::models::{AllowanceDecision, AllowanceStore, AutoReloadThresholds, BillingPeriod, BillingSettings,- CreditReloadStatus, Entitlement, OpenPeriodStart, OverageChargeStatus, PeriodAllowance,- PeriodLedger, Result, SeatAllowance, SeatGeneration, SeatUsage, SubscriptionScope,- UsageSnapshot,+ CreditPurchase, CreditReloadKind, CreditReloadStatus, Entitlement, OpenPeriodStart,+ OverageChargeStatus, PeriodAllowance, PeriodLedger, Result, SeatAllowance, SeatGeneration,+ SeatUsage, SubscriptionScope, UsageSnapshot,};use super::policy::UsageAllocation;use ai_usage::domain::financial::{@@ -114,6 +114,30 @@ pub struct PendingReload {pub stripe_invoice_id: Option<String>,}+/// How an attempt to collect an invoice ended.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum InvoicePayment {+ /// Collected.+ Paid,+ /// The card was declined; the invoice stays open for the provider's+ /// retries.+ Declined,+ /// The card needs the cardholder to authenticate (3-D Secure), which an+ /// off-session charge can't do; the invoice stays open.+ AuthenticationRequired,+ /// The invoice is void or uncollectible and can never be paid.+ Uncollectible,+}++/// The state of an invoice after asking the provider to void it.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum InvoiceVoid {+ /// Void (or otherwise uncollectible): it can no longer charge the card.+ Voided,+ /// The provider collected it before it could be voided.+ Paid,+}+/// A credit reload whose Stripe invoice outcome just changed.#[derive(Debug, Clone, PartialEq, Eq)]pub struct ResolvedReload {@@ -121,6 +145,25 @@ pub struct ResolvedReload {pub payer: MacroUserIdStr<'static>,/// Amount collected (or not), customer cents.pub amount_cents: i64,+ /// Whether Auto-Reload or a one-time purchase charged it.+ pub kind: CreditReloadKind,+}++/// What reserving a one-time card-on-file purchase found.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum PurchaseReservation {+ /// A new purchase to collect.+ New(PendingReload),+ /// An earlier declined purchase whose invoice is still open, handed back+ /// (as pending) so buying again pays that invoice instead of charging twice.+ Retry(PendingReload),+ /// The purchase would take this month's card charges past the limit.+ OverLimit {+ /// What can still be charged this month, customer cents.+ remaining_cents: i64,+ },+ /// An earlier purchase is still with the payment provider.+ InProgress,}/// What a settlement booked.@@ -157,8 +200,9 @@ pub trait BillingRepo: Send + Sync + 'static {payer: &MacroUserIdStr<'_>,) -> impl Future<Output = Result<BillingSettings>> + Send;- /// Reload commitments charged against a UTC calendar-month cap. Includes- /// pending reloads and failed invoices that may still collect; excludes manual purchases.+ /// Card charges counted against the UTC calendar-month credit limit:+ /// automatic reloads and one-time purchases, including pending ones and+ /// failed invoices that may still collect. Checkout purchases are excluded.fn credit_reload_committed_cents(&self,payer: &MacroUserIdStr<'_>,@@ -357,6 +401,33 @@ pub trait BillingRepo: Send + Sync + 'static {now: DateTime<Utc>,) -> impl Future<Output = Result<Option<PendingReload>>> + Send;+ /// Under the payer's row lock, reserve a one-time purchase of+ /// `amount_cents` asked for by `purchased_by`. Purchases and automatic+ /// reloads in the UTC calendar month containing `now` that Stripe may+ /// still collect count against `monthly_limit_cents` (`None` is no limit).+ /// An earlier purchase that never reached Stripe is marked failed; one+ /// declined with its invoice still open is retried instead of reserving a+ /// new one; one still pending with Stripe blocks the purchase.+ fn reserve_credit_purchase(+ &self,+ payer: &MacroUserIdStr<'_>,+ purchased_by: &MacroUserIdStr<'_>,+ amount_cents: i64,+ monthly_limit_cents: Option<i64>,+ now: DateTime<Utc>,+ ) -> impl Future<Output = Result<PurchaseReservation>> + Send;++ /// One-time purchases by `payer` that were declined with their invoice+ /// still open (status `failed`), oldest first.+ fn declined_credit_purchases(+ &self,+ payer: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Vec<PendingReload>>> + Send;++ /// Mark a purchase whose invoice was voided: `failed` with no invoice, so+ /// it is neither retried nor counted against the monthly limit.+ fn void_credit_purchase(&self, reload_id: Uuid) -> impl Future<Output = Result<()>> + Send;+/// Record the result of collecting a reserved reload.fn finish_credit_reload(&self,@@ -373,6 +444,7 @@ pub trait BillingRepo: Send + Sync + 'static {payer: &MacroUserIdStr<'_>,amount_cents: i64,stripe_invoice_id: &str,+ kind: CreditReloadKind,) -> impl Future<Output = Result<bool>> + Send;/// Update a reload by its Stripe invoice (webhook). Returns the payer and@@ -381,9 +453,13 @@ pub trait BillingRepo: Send + Sync + 'static {/// reload, and re-reporting the current status is a no-op./// A transition to `Paid` atomically books the purchased credits, deduplicated/// by invoice, so a failed credit write leaves the status retryable.+ /// A `Paid` invoice no row records yet is matched by `reload_id` (the id+ /// stamped on the invoice) when that row has no invoice, so a charge whose+ /// collector died before recording it is still booked.fn resolve_credit_reload_invoice(&self,stripe_invoice_id: &str,+ reload_id: Option<Uuid>,status: CreditReloadStatus,) -> impl Future<Output = Result<Option<ResolvedReload>>> + Send;@@ -479,15 +555,34 @@ pub trait PaymentGateway: Send + Sync + 'static {/// If no active or trialing subscription matches, an invoice-stored/// payment method may still collect the existing debt.///- /// `Ok(true)` when it is paid, `Ok(false)` when the card was declined and- /// the invoice stays open for the provider's own retries (the webhook- /// reports the outcome), `Err` when the provider could not be reached or- /// rejected the request.+ /// [`InvoicePayment::Paid`] when it is paid; `Declined` or+ /// `AuthenticationRequired` when it was not and the invoice stays open+ /// for the provider's own retries (the webhook reports the outcome);+ /// `Err` when the provider could not be reached or rejected the request.fn pay_overage_invoice(&self,charge_id: Uuid,invoice_id: &str,scope: SubscriptionScope,+ ) -> impl Future<Output = Result<InvoicePayment>> + Send;++ /// Void an open credit reload invoice so it can never charge the card,+ /// for example before the payer pays the same pack through checkout.+ /// Reports [`InvoiceVoid::Paid`] when it was collected first.+ fn void_credit_invoice(+ &self,+ invoice_id: &str,+ ) -> impl Future<Output = Result<InvoiceVoid>> + Send;++ /// Whether a charge in `scope` has a card to collect from: the+ /// subscription's or the customer's default payment method, or a legacy+ /// default source. `Ok(false)` when there is none (for example after the+ /// payer removed their card in the billing portal) or no active or+ /// trialing subscription matches `scope`.+ fn has_payment_method(+ &self,+ customer_id: &str,+ scope: SubscriptionScope,) -> impl Future<Output = Result<bool>> + Send;/// The current period of the customer's subscription in `scope`. Active or@@ -610,6 +705,16 @@ pub trait BillingService: Send + Sync + 'static {cancel_url: String,) -> impl Future<Output = Result<String>> + Send;+ /// Buy a credit pack now, charged to the payer's card on file. Any paid,+ /// metered member of the payer's team may buy, within the monthly credit+ /// limit: the payer's configured limit, or for a member when none is set,+ /// the plan's default. Credits are booked and usage settled once paid.+ fn purchase_credits(+ &self,+ user: &MacroUserIdStr<'_>,+ amount_cents: i64,+ ) -> impl Future<Output = Result<CreditPurchase>> + Send;+/// Book a completed credit purchase (webhook). Idempotent on/// `stripe_reference`.fn apply_credit_purchase(@@ -639,11 +744,14 @@ pub trait BillingService: Send + Sync + 'static {/// Record the outcome of a credit reload invoice (webhook). Unknown/// invoices are ignored. A paid invoice books its credits once, even when- /// the collector already did, and settles; a failed one pauses automatic- /// reloads.+ /// the collector already did, and settles; a failed automatic reload+ /// pauses automatic reloads, while a failed purchase changes nothing else.+ /// `reload_id` is the reload id stamped on the invoice, used to find a+ /// paid invoice that never reached its row.fn mark_credit_reload_invoice(&self,stripe_invoice_id: &str,+ reload_id: Option<Uuid>,paid: bool,) -> impl Future<Output = Result<()>> + Send;}diff --git a/crates/ai_billing/src/domain/service.rs b/crates/ai_billing/src/domain/service.rsindex fd42b278bc..166072d008 100644--- a/crates/ai_billing/src/domain/service.rs+++ b/crates/ai_billing/src/domain/service.rs@@ -8,6 +8,7 @@ use super::ledger::{SettlementPolicy, build_snapshot, decide};use super::models::{AiUsageBilling, AllowanceDecision, AllowanceStore, AutoReloadMonthlyBudget,AutoReloadThresholds, BillingError, BillingPeriod, BillingSettings, CREDIT_PACKS_CENTS,+ CreditPurchase, CreditPurchaseSnapshot, CreditPurchaseStatus, CreditReloadKind,CreditReloadStatus, Entitlement, MIN_STRIPE_CHARGE_CENTS, OVERAGE_CHARGE_THRESHOLD_CENTS,OverageChargeStatus, PayerScope, PeriodAllowance, PeriodLedger, Result, SeatAllowance,SeatUsage, SubscriptionScope, UsageSnapshot,@@ -15,7 +16,7 @@ use super::models::{use super::period::{PeriodSync, SubscriptionPeriod};use super::ports::{BillingRepo, BillingService, CreditCheckoutRequest, CreditReloadRequest, EntitlementSource,- PaymentGateway, PendingReload, UsageReader,+ InvoicePayment, InvoiceVoid, PaymentGateway, PendingReload, PurchaseReservation, UsageReader,};use super::pricing::AiPricing;use ai_usage::AiUsageEnforcement;@@ -32,6 +33,9 @@ use teams::domain::open_seat_release::OpenSeatRelease;/// would read the provider again. One minute bounds that to one read per/// payer per process while Stripe rolls a period or a provider recovers.const PERIOD_MISS_BACKOFF: chrono::Duration = chrono::Duration::minutes(1);+/// Reservations one purchase may make while retiring stale invoices (a void+/// one, or a declined pack the buyer did not pick) before giving up.+const MAX_PURCHASE_ATTEMPTS: usize = 3;/// How many closed periods behind the open one a settlement reconciles.///@@ -583,8 +587,11 @@ whereelse {return Ok(());};- match self.collect_reload(entitlement, reload).await {- Ok(()) => Ok(()),+ match self+ .collect_credit_charge(entitlement, reload, CreditReloadKind::Automatic)+ .await+ {+ Ok(_) => Ok(()),Err(e @ (BillingError::Payment(_) | BillingError::NoStripeCustomer)) => {tracing::warn!(error = ?e,@@ -596,24 +603,32 @@ where}}- /// Collect a reserved credit reload: open its invoice (or pick up the one- /// an earlier attempt opened), try to pay it, and book the credits once- /// paid. A provider failure marks the reload failed and pauses automatic- /// reloads until the payer saves their settings again. A recorded invoice- /// stays on the row because Stripe may still collect it, in which case- /// the webhook books the credits.- async fn collect_reload(&self, entitlement: &Entitlement, reload: PendingReload) -> Result<()> {+ /// Collect a reserved card charge for credits: open its invoice (or pick+ /// up the one an earlier attempt opened), try to pay it, and book the+ /// credits once paid. Reports how the payment ended. A purchase whose card+ /// needs authentication has its invoice voided, since the payer pays+ /// through checkout instead; an automatic reload keeps it open like a+ /// decline. A failure marks the charge failed; for an automatic reload it also pauses+ /// automatic reloads until the payer saves their settings again. A+ /// recorded invoice stays on the row because Stripe may still collect it,+ /// in which case the webhook books the credits.+ async fn collect_credit_charge(+ &self,+ entitlement: &Entitlement,+ reload: PendingReload,+ kind: CreditReloadKind,+ ) -> Result<InvoicePayment> {let payer = &entitlement.payer;let scope = SubscriptionScope::from(&entitlement.scope);let customer_id = match self.entitlements.stripe_customer_id(payer).await {Ok(Some(customer_id)) => customer_id,Ok(None) => {tracing::warn!("credit reload reserved but payer has no stripe customer");- self.fail_reload(payer, reload.id).await?;+ self.fail_credit_charge(payer, reload.id, kind).await?;return Err(BillingError::NoStripeCustomer);}Err(e) => {- self.fail_reload(payer, reload.id).await?;+ self.fail_credit_charge(payer, reload.id, kind).await?;return Err(e);}};@@ -621,10 +636,15 @@ wherelet invoice_id = match reload.stripe_invoice_id.clone() {Some(invoice_id) => invoice_id,None => {- let description = format!(- "Macro AI credits, automatic reload of {}",- dollars(reload.amount_cents)- );+ let description = match kind {+ CreditReloadKind::Automatic => format!(+ "Macro AI credits, automatic reload of {}",+ dollars(reload.amount_cents)+ ),+ CreditReloadKind::Purchase => {+ format!("Macro AI credits, {}", dollars(reload.amount_cents))+ }+ };match self.payments.open_credit_reload_invoice(CreditReloadRequest {@@ -644,7 +664,7 @@ wherecents = reload.amount_cents,"ai credit reload invoice could not be opened");- self.fail_reload(payer, reload.id).await?;+ self.fail_credit_charge(payer, reload.id, kind).await?;return Err(e);}}@@ -661,9 +681,9 @@ where.pay_overage_invoice(reload.id, &invoice_id, scope).await{- Ok(true) => {+ Ok(InvoicePayment::Paid) => {self.repo- .record_credit_reload(payer, reload.amount_cents, &invoice_id)+ .record_credit_reload(payer, reload.amount_cents, &invoice_id, kind).await?;self.repo.finish_credit_reload(reload.id, Some(&invoice_id), CreditReloadStatus::Paid)@@ -671,19 +691,72 @@ wheretracing::info!(cents = reload.amount_cents,invoice = %invoice_id,- "collected automatic ai credit reload"+ %kind,+ "collected ai credit charge");- Ok(())+ Ok(InvoicePayment::Paid)+ }+ Ok(InvoicePayment::AuthenticationRequired) if kind == CreditReloadKind::Purchase => {+ tracing::info!(+ cents = reload.amount_cents,+ invoice = %invoice_id,+ "ai credit purchase needs card authentication; voiding for checkout"+ );+ // Failed with its invoice first: if voiding fails, buying+ // again retries this invoice instead of waiting on it.+ self.repo+ .finish_credit_reload(reload.id, Some(&invoice_id), CreditReloadStatus::Failed)+ .await?;+ if self+ .abandon_credit_purchase(payer, reload.id, reload.amount_cents, &invoice_id)+ .await?+ {+ return Ok(InvoicePayment::Paid);+ }+ Ok(InvoicePayment::AuthenticationRequired)}- Ok(false) => {+ Ok(InvoicePayment::Declined | InvoicePayment::AuthenticationRequired) => {// Declined: the invoice stays open for Stripe's retries and- // the webhook books the credits if one succeeds.+ // the webhook books the credits if one succeeds. A declined+ // purchase is marked failed so buying again retries this+ // invoice rather than waiting on it.+ if kind == CreditReloadKind::Purchase {+ self.repo+ .finish_credit_reload(+ reload.id,+ Some(&invoice_id),+ CreditReloadStatus::Failed,+ )+ .await?;+ }tracing::info!(cents = reload.amount_cents,invoice = %invoice_id,- "ai credit reload invoice awaiting payment"+ %kind,+ "ai credit charge declined; invoice awaiting payment");- Ok(())+ Ok(InvoicePayment::Declined)+ }+ Ok(InvoicePayment::Uncollectible) => {+ tracing::warn!(+ cents = reload.amount_cents,+ invoice = %invoice_id,+ %kind,+ "ai credit charge invoice is void or uncollectible"+ );+ match kind {+ // Nothing can be charged; buying again starts over.+ CreditReloadKind::Purchase => {+ self.repo.void_credit_purchase(reload.id).await?;+ Ok(InvoicePayment::Uncollectible)+ }+ CreditReloadKind::Automatic => {+ self.fail_credit_charge(payer, reload.id, kind).await?;+ Err(BillingError::Payment(anyhow::anyhow!(+ "credit reload invoice {invoice_id} is void or uncollectible"+ )))+ }+ }}Err(e) => {tracing::error!(@@ -692,19 +765,85 @@ whereinvoice = %invoice_id,"ai credit reload failed");- self.fail_reload(payer, reload.id).await?;+ self.fail_credit_charge(payer, reload.id, kind).await?;Err(e)}}}- /// A reload that could not be collected: automatic reloads pause until- /// the payer saves their settings again.- async fn fail_reload(&self, payer: &MacroUserIdStr<'_>, reload_id: Uuid) -> Result<()> {+ /// Void a purchase's open invoice so it can never charge the card, before+ /// the payer pays through checkout instead. If Stripe collected it first,+ /// book the credits and return `true`.+ async fn abandon_credit_purchase(+ &self,+ payer: &MacroUserIdStr<'_>,+ reload_id: Uuid,+ amount_cents: i64,+ invoice_id: &str,+ ) -> Result<bool> {+ match self.payments.void_credit_invoice(invoice_id).await? {+ InvoiceVoid::Voided => {+ self.repo.void_credit_purchase(reload_id).await?;+ Ok(false)+ }+ InvoiceVoid::Paid => {+ self.repo+ .record_credit_reload(+ payer,+ amount_cents,+ invoice_id,+ CreditReloadKind::Purchase,+ )+ .await?;+ self.repo+ .finish_credit_reload(reload_id, Some(invoice_id), CreditReloadStatus::Paid)+ .await?;+ Ok(true)+ }+ }+ }++ /// Apply freshly booked purchase credits to usage waiting on them.+ async fn settle_after_purchase(&self, user: &MacroUserIdStr<'_>) {+ if let Err(e) = self.settle(user).await {+ // The credits are booked; the next settlement applies them.+ tracing::warn!(error = ?e, "settlement after credit purchase failed");+ }+ }++ /// A charge that could not be collected. A failed automatic reload pauses+ /// automatic reloads until the payer saves their settings again; a failed+ /// purchase does not.+ async fn fail_credit_charge(+ &self,+ payer: &MacroUserIdStr<'_>,+ reload_id: Uuid,+ kind: CreditReloadKind,+ ) -> Result<()> {self.repo.finish_credit_reload(reload_id, None, CreditReloadStatus::Failed).await?;- self.repo.suspend_auto_reload(payer).await+ match kind {+ CreditReloadKind::Automatic => self.repo.suspend_auto_reload(payer).await,+ CreditReloadKind::Purchase => Ok(()),+ }+ }++ /// The monthly credit limit on `user`'s one-time purchases: the payer's+ /// configured limit, or for a team member when none is set, their plan's+ /// default, so a member can never charge the team card without a limit.+ fn purchase_limit_cents(+ entitlement: &Entitlement,+ settings: &BillingSettings,+ user: &MacroUserIdStr<'_>,+ ) -> Option<i64> {+ settings.auto_reload.monthly_limit_cents.or_else(|| {+ if entitlement.is_payer(user) {+ None+ } else {+ entitlement.tier.default_auto_reload_monthly_limit_cents()+ }+ })}fn require_payer(entitlement: &Entitlement, user: &MacroUserIdStr<'_>) -> Result<()> {@@ -819,19 +958,29 @@ wherelet now = Utc::now();let position = self.position(user, now).await?;let mut snapshot = self.snapshot_at(user, &position).await?;- // Summary-only read; allowance enforcement does not need monthly reload facts.- if position.entitlement.is_metered()- && let Some(limit) = position.settings.auto_reload.monthly_limit_cents- {+ // Summary-only read; allowance enforcement does not need monthly+ // credit-limit facts.+ if position.entitlement.is_metered() {let month = BillingPeriod::calendar_month(now);let committed_cents = self.repo.credit_reload_committed_cents(&position.entitlement.payer, month).await?;- snapshot.auto_reload.monthly_budget = Some(AutoReloadMonthlyBudget {+ if let Some(limit) = position.settings.auto_reload.monthly_limit_cents {+ snapshot.auto_reload.monthly_budget = Some(AutoReloadMonthlyBudget {+ committed_cents,+ resets_at: month.end,+ limit_reached: limit.saturating_sub(committed_cents) < MIN_STRIPE_CHARGE_CENTS,+ });+ }+ snapshot.credit_purchase = Some(CreditPurchaseSnapshot {+ monthly_limit_cents: Self::purchase_limit_cents(+ &position.entitlement,+ &position.settings,+ user,+ ),committed_cents,resets_at: month.end,- limit_reached: limit.saturating_sub(committed_cents) < MIN_STRIPE_CHARGE_CENTS,});}// Keep the summary consistent with the configured allowance gate.@@ -918,6 +1067,145 @@ whereself.snapshot(user).await}+ #[tracing::instrument(skip(self), err)]+ async fn purchase_credits(+ &self,+ user: &MacroUserIdStr<'_>,+ amount_cents: i64,+ ) -> Result<CreditPurchase> {+ if !CREDIT_PACKS_CENTS.contains(&amount_cents) {+ return Err(BillingError::InvalidCreditAmount);+ }+ let now = Utc::now();+ let Position {+ entitlement,+ settings,+ ..+ } = self.position(user, now).await?;+ // Every billed seat may buy for the team; Free has nothing to fund and+ // Enterprise is never metered.+ if !entitlement.is_metered() {+ return Err(BillingError::FreePlan);+ }+ // A payer who removed their card can't be charged off-session; send+ // them to checkout instead of opening an invoice nobody can pay.+ let customer_id = self+ .entitlements+ .stripe_customer_id(&entitlement.payer)+ .await?+ .ok_or(BillingError::NoStripeCustomer)?;+ let scope = SubscriptionScope::from(&entitlement.scope);+ if !self+ .payments+ .has_payment_method(&customer_id, scope)+ .await?+ {+ // A purchase declined before the card was removed keeps an open+ // invoice; void it so a card added later can't collect it on top+ // of the checkout payment. One Stripe collected first is booked.+ let mut booked_cents = 0;+ for declined in self+ .repo+ .declined_credit_purchases(&entitlement.payer)+ .await?+ {+ if let Some(invoice_id) = declined.stripe_invoice_id.as_deref()+ && self+ .abandon_credit_purchase(+ &entitlement.payer,+ declined.id,+ declined.amount_cents,+ invoice_id,+ )+ .await?+ {+ booked_cents += declined.amount_cents;+ }+ }+ if booked_cents > 0 {+ self.settle_after_purchase(user).await;+ return Ok(CreditPurchase {+ amount_cents: booked_cents,+ status: CreditPurchaseStatus::Paid,+ });+ }+ return Ok(CreditPurchase {+ amount_cents,+ status: CreditPurchaseStatus::PaymentMethodRequired,+ });+ }+ let limit = Self::purchase_limit_cents(&entitlement, &settings, user);+ // Each pass that does not end the purchase retires one stale invoice+ // (a void one, or a declined pack the buyer did not pick), so this is+ // bounded by the purchases that can be open at once.+ for _ in 0..MAX_PURCHASE_ATTEMPTS {+ let reload = match self+ .repo+ .reserve_credit_purchase(&entitlement.payer, user, amount_cents, limit, now)+ .await?+ {+ PurchaseReservation::New(reload) => reload,+ PurchaseReservation::Retry(reload) if reload.amount_cents == amount_cents => reload,+ PurchaseReservation::Retry(declined) => {+ // The buyer picked a different pack than the declined one:+ // void it rather than charge an amount they did not choose.+ let collected = match declined.stripe_invoice_id.as_deref() {+ Some(invoice_id) => {+ self.abandon_credit_purchase(+ &entitlement.payer,+ declined.id,+ declined.amount_cents,+ invoice_id,+ )+ .await?+ }+ None => {+ self.repo.void_credit_purchase(declined.id).await?;+ false+ }+ };+ if collected {+ self.settle_after_purchase(user).await;+ return Ok(CreditPurchase {+ amount_cents: declined.amount_cents,+ status: CreditPurchaseStatus::Paid,+ });+ }+ continue;+ }+ PurchaseReservation::OverLimit { remaining_cents } => {+ return Err(BillingError::CreditLimitExceeded { remaining_cents });+ }+ PurchaseReservation::InProgress => return Err(BillingError::PurchaseInProgress),+ };+ let charged_cents = reload.amount_cents;+ // Provider and storage errors surface as errors, never as a+ // decline that would send the buyer to update a working card.+ let status = match self+ .collect_credit_charge(&entitlement, reload, CreditReloadKind::Purchase)+ .await?+ {+ InvoicePayment::Paid => CreditPurchaseStatus::Paid,+ InvoicePayment::Declined => CreditPurchaseStatus::Declined,+ InvoicePayment::AuthenticationRequired => {+ CreditPurchaseStatus::AuthenticationRequired+ }+ // A retried invoice that was voided in Stripe: reserve afresh.+ InvoicePayment::Uncollectible => continue,+ };+ if status == CreditPurchaseStatus::Paid {+ self.settle_after_purchase(user).await;+ }+ return Ok(CreditPurchase {+ amount_cents: charged_cents,+ status,+ });+ }+ Err(BillingError::Payment(anyhow::anyhow!(+ "credit purchase found no collectable invoice after {MAX_PURCHASE_ATTEMPTS} attempts"+ )))+ }+#[tracing::instrument(skip(self, success_url, cancel_url), err)]async fn create_credit_checkout(&self,@@ -1025,7 +1313,12 @@ where}#[tracing::instrument(skip(self), err)]- async fn mark_credit_reload_invoice(&self, stripe_invoice_id: &str, paid: bool) -> Result<()> {+ async fn mark_credit_reload_invoice(+ &self,+ stripe_invoice_id: &str,+ reload_id: Option<Uuid>,+ paid: bool,+ ) -> Result<()> {let status = if paid {CreditReloadStatus::Paid} else {@@ -1033,14 +1326,17 @@ where};let Some(resolved) = self.repo- .resolve_credit_reload_invoice(stripe_invoice_id, status)+ .resolve_credit_reload_invoice(stripe_invoice_id, reload_id, status).await?else {// Not ours, already paid, or already in this state.return Ok(());};if !paid {- return self.repo.suspend_auto_reload(&resolved.payer).await;+ return match resolved.kind {+ CreditReloadKind::Automatic => self.repo.suspend_auto_reload(&resolved.payer).await,+ CreditReloadKind::Purchase => Ok(()),+ };}// Resolving a paid reload atomically books its credits with the status.// The reloaded credits cover any usage that was waiting on them.diff --git a/crates/ai_billing/src/domain/service/test.rs b/crates/ai_billing/src/domain/service/test.rsindex e066e20b2b..20b2a82c64 100644--- a/crates/ai_billing/src/domain/service/test.rs+++ b/crates/ai_billing/src/domain/service/test.rs@@ -1,12 +1,13 @@use super::*;use crate::domain::ledger::{ReloadState, plan_reload, plan_settlement};use crate::domain::models::{- AllowanceStore, AutoReloadThresholds, CreditReloadStatus, DenyReason, OVERAGE_LIMIT_MIN_CENTS,- OpenPeriodStart, PayerScope, PeriodAllowance, PeriodLedger, PlanTier, SeatGeneration,+ AllowanceStore, AutoReloadThresholds, CreditPurchaseStatus, CreditReloadKind,+ CreditReloadStatus, DenyReason, OVERAGE_LIMIT_MIN_CENTS, OpenPeriodStart, PayerScope,+ PeriodAllowance, PeriodLedger, PlanTier, SeatGeneration,};use crate::domain::ports::{- CreditReloadRequest, OverageChargeRequest, PendingCharge, PendingReload, ResolvedReload,- SettlementOutcome,+ CreditReloadRequest, OverageChargeRequest, PendingCharge, PendingReload, PurchaseReservation,+ ResolvedReload, SettlementOutcome,};use chrono::TimeZone;use macro_user_id::cowlike::CowLike;@@ -164,6 +165,8 @@ struct FakeReload {status: CreditReloadStatus,invoice: Option<String>,created_at: DateTime<Utc>,+ kind: CreditReloadKind,+ purchased_by: Option<String>,}#[derive(Default)]@@ -589,6 +592,7 @@ impl BillingRepo for FakeRepo {.reloads.iter().filter(|r| r.status == CreditReloadStatus::Pending)+ .filter(|r| r.kind == CreditReloadKind::Automatic).collect();if let Some(orphan) = pending.iter()@@ -626,6 +630,8 @@ impl BillingRepo for FakeRepo {status: CreditReloadStatus::Pending,invoice: None,created_at: now,+ kind: CreditReloadKind::Automatic,+ purchased_by: None,});Ok(Some(PendingReload {id,@@ -633,6 +639,94 @@ impl BillingRepo for FakeRepo {stripe_invoice_id: None,}))}+ async fn reserve_credit_purchase(+ &self,+ _payer: &MacroUserIdStr<'_>,+ purchased_by: &MacroUserIdStr<'_>,+ amount_cents: i64,+ monthly_limit_cents: Option<i64>,+ now: DateTime<Utc>,+ ) -> Result<PurchaseReservation> {+ let mut s = self.state.lock().unwrap();+ let stale_before = now - chrono::Duration::minutes(10);+ for r in s.reloads.iter_mut().filter(|r| {+ r.kind == CreditReloadKind::Purchase+ && r.status == CreditReloadStatus::Pending+ && r.invoice.is_none()+ && r.created_at < stale_before+ }) {+ r.status = CreditReloadStatus::Failed;+ }+ if let Some(r) = s.reloads.iter_mut().find(|r| {+ r.kind == CreditReloadKind::Purchase+ && r.status == CreditReloadStatus::Failed+ && r.invoice.is_some()+ }) {+ r.status = CreditReloadStatus::Pending;+ return Ok(PurchaseReservation::Retry(PendingReload {+ id: r.id,+ amount_cents: r.amount_cents,+ stripe_invoice_id: r.invoice.clone(),+ }));+ }+ if s.reloads.iter().any(|r| {+ r.kind == CreditReloadKind::Purchase && r.status == CreditReloadStatus::Pending+ }) {+ return Ok(PurchaseReservation::InProgress);+ }+ if let Some(limit) = monthly_limit_cents {+ let committed = s.reload_committed_cents(BillingPeriod::calendar_month(now));+ let remaining_cents = (limit - committed).max(0);+ if amount_cents > remaining_cents {+ return Ok(PurchaseReservation::OverLimit { remaining_cents });+ }+ }+ let id = macro_uuid::generate_uuid_v7();+ s.reloads.push(FakeReload {+ id,+ amount_cents,+ status: CreditReloadStatus::Pending,+ invoice: None,+ created_at: now,+ kind: CreditReloadKind::Purchase,+ purchased_by: Some(purchased_by.as_ref().to_string()),+ });+ Ok(PurchaseReservation::New(PendingReload {+ id,+ amount_cents,+ stripe_invoice_id: None,+ }))+ }+ async fn declined_credit_purchases(+ &self,+ _payer: &MacroUserIdStr<'_>,+ ) -> Result<Vec<PendingReload>> {+ Ok(self+ .state+ .lock()+ .unwrap()+ .reloads+ .iter()+ .filter(|r| {+ r.kind == CreditReloadKind::Purchase+ && r.status == CreditReloadStatus::Failed+ && r.invoice.is_some()+ })+ .map(|r| PendingReload {+ id: r.id,+ amount_cents: r.amount_cents,+ stripe_invoice_id: r.invoice.clone(),+ })+ .collect())+ }+ async fn void_credit_purchase(&self, reload_id: Uuid) -> Result<()> {+ let mut s = self.state.lock().unwrap();+ for r in s.reloads.iter_mut().filter(|r| r.id == reload_id) {+ r.status = CreditReloadStatus::Failed;+ r.invoice = None;+ }+ Ok(())+ }async fn finish_credit_reload(&self,reload_id: Uuid,@@ -653,6 +747,7 @@ impl BillingRepo for FakeRepo {payer: &MacroUserIdStr<'_>,amount_cents: i64,stripe_invoice_id: &str,+ _kind: CreditReloadKind,) -> Result<bool> {self.record_credit_purchase(payer, amount_cents, stripe_invoice_id).await@@ -660,19 +755,24 @@ impl BillingRepo for FakeRepo {async fn resolve_credit_reload_invoice(&self,stripe_invoice_id: &str,+ reload_id: Option<Uuid>,status: CreditReloadStatus,) -> Result<Option<ResolvedReload>> {let mut s = self.state.lock().unwrap();+ let adopt = status == CreditReloadStatus::Paid;let found = s.reloads.iter_mut().find(|r| {- r.invoice.as_deref() == Some(stripe_invoice_id)+ (r.invoice.as_deref() == Some(stripe_invoice_id)+ || (adopt && Some(r.id) == reload_id && r.invoice.is_none()))&& r.status != CreditReloadStatus::Paid&& r.status != status});let resolved = found.map(|r| {r.status = status;+ r.invoice = Some(stripe_invoice_id.to_string());ResolvedReload {payer: user("[email protected]"),amount_cents: r.amount_cents,+ kind: r.kind,}});if let Some(resolved) = &resolved@@ -697,6 +797,10 @@ enum PayOutcome {Paid,/// Card declined: the invoice stays open for Stripe's retries.Declined,+ /// The card needs 3-D Secure: the invoice stays open.+ AuthenticationRequired,+ /// The invoice was voided in Stripe.+ Uncollectible,/// The provider could not be reached.Error,}@@ -719,9 +823,40 @@ struct FakePayments {payments: Arc<Mutex<Vec<(Uuid, String)>>>,period_reply: Arc<Mutex<PeriodReply>>,period_requests: Arc<Mutex<Vec<(String, SubscriptionScope)>>>,+ no_card: Arc<Mutex<bool>>,+ voided: Arc<Mutex<Vec<String>>>,+ /// Outcomes for the next payment attempts, before `pay_outcome` applies.+ pay_queue: Arc<Mutex<std::collections::VecDeque<PayOutcome>>>,+ void_outcome: Arc<Mutex<VoidOutcome>>,+}++/// How the fake provider answers a request to void an invoice.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+enum VoidOutcome {+ #[default]+ Voided,+ /// Stripe collected the invoice before it could be voided.+ AlreadyPaid,+ /// The provider could not be reached.+ Error,}impl FakePayments {+ fn queue_pay(&self, outcomes: &[PayOutcome]) {+ self.pay_queue.lock().unwrap().extend(outcomes);+ }+ fn set_void(&self, outcome: VoidOutcome) {+ *self.void_outcome.lock().unwrap() = outcome;+ }+ fn restore_card(&self) {+ *self.no_card.lock().unwrap() = false;+ }+ fn voided(&self) -> Vec<String> {+ self.voided.lock().unwrap().clone()+ }+ fn remove_card(&self) {+ *self.no_card.lock().unwrap() = true;+ }fn set_pay(&self, outcome: PayOutcome) {*self.pay_outcome.lock().unwrap() = outcome;}@@ -768,17 +903,37 @@ impl PaymentGateway for FakePayments {charge_id: Uuid,invoice_id: &str,_scope: SubscriptionScope,- ) -> Result<bool> {+ ) -> Result<InvoicePayment> {self.payments.lock().unwrap().push((charge_id, invoice_id.to_string()));- match *self.pay_outcome.lock().unwrap() {- PayOutcome::Paid => Ok(true),- PayOutcome::Declined => Ok(false),+ let queued = self.pay_queue.lock().unwrap().pop_front();+ match queued.unwrap_or(*self.pay_outcome.lock().unwrap()) {+ PayOutcome::Paid => Ok(InvoicePayment::Paid),+ PayOutcome::Declined => Ok(InvoicePayment::Declined),+ PayOutcome::AuthenticationRequired => Ok(InvoicePayment::AuthenticationRequired),+ PayOutcome::Uncollectible => Ok(InvoicePayment::Uncollectible),PayOutcome::Error => Err(BillingError::Payment(anyhow::anyhow!("card declined"))),}}+ async fn void_credit_invoice(&self, invoice_id: &str) -> Result<InvoiceVoid> {+ match *self.void_outcome.lock().unwrap() {+ VoidOutcome::Voided => {+ self.voided.lock().unwrap().push(invoice_id.to_string());+ Ok(InvoiceVoid::Voided)+ }+ VoidOutcome::AlreadyPaid => Ok(InvoiceVoid::Paid),+ VoidOutcome::Error => Err(BillingError::Payment(anyhow::anyhow!("stripe unavailable"))),+ }+ }+ async fn has_payment_method(+ &self,+ _customer_id: &str,+ _scope: SubscriptionScope,+ ) -> Result<bool> {+ Ok(!*self.no_card.lock().unwrap())+ }async fn subscription_period(&self,customer_id: &str,@@ -1420,6 +1575,8 @@ async fn summary_reports_calendar_month_commitments_and_minimum_reload_cap_statustatus,invoice: invoice.map(str::to_string),created_at,+ kind: CreditReloadKind::Automatic,+ purchased_by: None,});}}@@ -1439,6 +1596,8 @@ async fn summary_reports_calendar_month_commitments_and_minimum_reload_cap_statustatus: CreditReloadStatus::Paid,invoice: Some("in_last_cent".to_string()),created_at: now,+ kind: CreditReloadKind::Automatic,+ purchased_by: None,});let budget = service.snapshot(&payer)@@ -1675,7 +1834,7 @@ async fn a_low_balance_reloads_credits_before_overage_is_reserved() {// 600 cost over is 630 owed: the balance would end at -130, so the// reload brings it back to the $100 target after this usage is paid.let snap = svc- .update_auto_reload(&payer, true, AutoReloadThresholds::default())+ .update_auto_reload(&payer, true, thresholds(1_000, 10_000, None)).await.unwrap();let opened = payments.opened_reloads();@@ -1937,12 +2096,12 @@ async fn reload_invoice_webhooks_book_credits_once() {let (svc, repo, _, _) = premium_service(0);let payer = user("[email protected]");repo.set_balance(500);- svc.update_auto_reload(&payer, true, AutoReloadThresholds::default())+ svc.update_auto_reload(&payer, true, thresholds(1_000, 10_000, None)).await.unwrap();let invoice = repo.reloads()[0].invoice.clone().unwrap();assert_eq!(repo.state.lock().unwrap().balance, 10_000);- svc.mark_credit_reload_invoice(&invoice, true)+ svc.mark_credit_reload_invoice(&invoice, None, true).await.unwrap();assert_eq!(repo.state.lock().unwrap().balance, 10_000);@@ -1951,22 +2110,22 @@ async fn reload_invoice_webhooks_book_credits_once() {let (svc, repo, payments, _) = premium_service(0);repo.set_balance(500);payments.set_pay(PayOutcome::Declined);- svc.update_auto_reload(&payer, true, AutoReloadThresholds::default())+ svc.update_auto_reload(&payer, true, thresholds(1_000, 10_000, None)).await.unwrap();let invoice = repo.reloads()[0].invoice.clone().unwrap();assert_eq!(repo.state.lock().unwrap().balance, 500);- svc.mark_credit_reload_invoice(&invoice, true)+ svc.mark_credit_reload_invoice(&invoice, None, true).await.unwrap();assert_eq!(repo.reloads()[0].status, CreditReloadStatus::Paid);assert_eq!(repo.state.lock().unwrap().balance, 10_000);// Paid is terminal: a duplicate or a late failure changes nothing.- svc.mark_credit_reload_invoice(&invoice, true)+ svc.mark_credit_reload_invoice(&invoice, None, true).await.unwrap();- svc.mark_credit_reload_invoice(&invoice, false)+ svc.mark_credit_reload_invoice(&invoice, None, false).await.unwrap();assert_eq!(repo.state.lock().unwrap().balance, 10_000);@@ -1974,7 +2133,7 @@ async fn reload_invoice_webhooks_book_credits_once() {assert!(!svc.snapshot(&payer).await.unwrap().auto_reload.suspended);// Unknown invoices are ignored.- svc.mark_credit_reload_invoice("in_unknown", false)+ svc.mark_credit_reload_invoice("in_unknown", None, false).await.unwrap();assert!(!svc.snapshot(&payer).await.unwrap().auto_reload.suspended);@@ -1986,12 +2145,12 @@ async fn a_failed_reload_invoice_webhook_pauses_reloads_only() {let payer = user("[email protected]");repo.set_balance(500);payments.set_pay(PayOutcome::Declined);- svc.update_auto_reload(&payer, true, AutoReloadThresholds::default())+ svc.update_auto_reload(&payer, true, thresholds(1_000, 10_000, None)).await.unwrap();let invoice = repo.reloads()[0].invoice.clone().unwrap();- svc.mark_credit_reload_invoice(&invoice, false)+ svc.mark_credit_reload_invoice(&invoice, None, false).await.unwrap();assert_eq!(repo.reloads()[0].status, CreditReloadStatus::Failed);@@ -2228,7 +2387,7 @@ async fn previous_period_usage_never_triggers_a_reload() {// credits on hand.usage.add(&payer, previous.start + chrono::Duration::days(2), 4_000);- svc.update_auto_reload(&payer, true, AutoReloadThresholds::default())+ svc.update_auto_reload(&payer, true, thresholds(1_000, 10_000, None)).await.unwrap();@@ -3501,3 +3660,444 @@ async fn assert_upgrade_resets_snapshot_and_gate(pool: sqlx::PgPool, from: PlanT.unwrap();assert_eq!(svc.snapshot(&payer).await.unwrap().used_cents, 200);}++fn purchase_team(monthly_limit: Option<i64>) -> (Service, FakeRepo, FakePayments) {+ let owner = user("[email protected]");+ let member = user("[email protected]");+ let repo = FakeRepo::default();+ repo.state+ .lock()+ .unwrap()+ .settings+ .auto_reload+ .monthly_limit_cents = monthly_limit;+ let payments = FakePayments::default();+ let svc = BillingServiceImpl::new(+ FakeEntitlements::default()+ .with(premium_team(&owner, &member, Uuid::from_u128(9)))+ .with_customer(&owner, "cus_owner"),+ FakeUsage::default(),+ repo.clone(),+ payments.clone(),+ AiPricing::testing(),+ )+ .with_billing(AiUsageBilling::Enabled);+ (svc, repo, payments)+}++#[tokio::test]+async fn a_payer_buys_credits_on_the_card_on_file() {+ let (svc, repo, payments, _) = premium_service(0);+ let payer = user("[email protected]");++ let purchase = svc.purchase_credits(&payer, 2_500).await.unwrap();++ assert_eq!(+ purchase,+ CreditPurchase {+ amount_cents: 2_500,+ status: CreditPurchaseStatus::Paid,+ }+ );+ assert_eq!(repo.state.lock().unwrap().balance, 2_500);+ let opened = payments.opened_reloads();+ assert_eq!(opened.len(), 1);+ assert_eq!(opened[0].customer_id, "cus_123");+ assert_eq!(opened[0].description, "Macro AI credits, $25.00");+ let reloads = repo.reloads();+ assert_eq!(reloads[0].kind, CreditReloadKind::Purchase);+ assert_eq!(reloads[0].status, CreditReloadStatus::Paid);+ assert_eq!(reloads[0].purchased_by.as_deref(), Some(payer.as_ref()));+}++#[tokio::test]+async fn a_purchase_without_a_card_on_file_asks_for_checkout_and_charges_nothing() {+ let (svc, repo, payments, _) = premium_service(0);+ payments.remove_card();+ let payer = user("[email protected]");++ let purchase = svc.purchase_credits(&payer, 2_500).await.unwrap();++ assert_eq!(+ purchase,+ CreditPurchase {+ amount_cents: 2_500,+ status: CreditPurchaseStatus::PaymentMethodRequired,+ }+ );+ assert!(payments.opened_reloads().is_empty());+ assert!(payments.payments().is_empty());+ assert!(repo.reloads().is_empty());+ assert_eq!(repo.state.lock().unwrap().balance, 0);+}++#[tokio::test]+async fn a_card_that_needs_authentication_voids_the_invoice_for_checkout() {+ let (svc, repo, payments, _) = premium_service(0);+ payments.set_pay(PayOutcome::AuthenticationRequired);+ let payer = user("[email protected]");++ let purchase = svc.purchase_credits(&payer, 2_500).await.unwrap();++ assert_eq!(+ purchase.status,+ CreditPurchaseStatus::AuthenticationRequired+ );+ let reloads = repo.reloads();+ assert_eq!(payments.voided(), vec![format!("in_{}", reloads[0].id)]);+ // Voided: neither retried nor counted against the monthly limit.+ assert_eq!(reloads[0].status, CreditReloadStatus::Failed);+ assert_eq!(reloads[0].invoice, None);+ assert_eq!(repo.state.lock().unwrap().balance, 0);+ assert!(!repo.state.lock().unwrap().auto_reload_suspended);+}++#[tokio::test]+async fn removing_the_card_after_a_decline_voids_the_open_invoice_before_checkout() {+ let (svc, repo, payments, _) = premium_service(0);+ let payer = user("[email protected]");+ payments.set_pay(PayOutcome::Declined);+ let declined = svc.purchase_credits(&payer, 2_500).await.unwrap();+ assert_eq!(declined.status, CreditPurchaseStatus::Declined);+ let invoice = repo.reloads()[0].invoice.clone().unwrap();++ payments.remove_card();+ let purchase = svc.purchase_credits(&payer, 5_000).await.unwrap();++ assert_eq!(purchase.status, CreditPurchaseStatus::PaymentMethodRequired);+ assert_eq!(payments.voided(), vec![invoice]);+ let reloads = repo.reloads();+ assert_eq!(reloads.len(), 1);+ assert_eq!(reloads[0].invoice, None);+}++#[tokio::test]+async fn a_different_pack_voids_the_declined_invoice_instead_of_charging_it() {+ let (svc, repo, payments, _) = premium_service(0);+ let payer = user("[email protected]");+ payments.set_pay(PayOutcome::Declined);+ svc.purchase_credits(&payer, 2_500).await.unwrap();+ let declined_invoice = repo.reloads()[0].invoice.clone().unwrap();++ payments.set_pay(PayOutcome::Paid);+ let purchase = svc.purchase_credits(&payer, 5_000).await.unwrap();++ assert_eq!(+ purchase,+ CreditPurchase {+ amount_cents: 5_000,+ status: CreditPurchaseStatus::Paid,+ }+ );+ assert_eq!(payments.voided(), vec![declined_invoice]);+ assert_eq!(repo.state.lock().unwrap().balance, 5_000);+ let reloads = repo.reloads();+ assert_eq!(reloads.len(), 2);+ assert_eq!(reloads[0].invoice, None);+ assert_eq!(reloads[1].status, CreditReloadStatus::Paid);+}++#[tokio::test]+async fn the_same_pack_retries_the_declined_invoice() {+ let (svc, repo, payments, _) = premium_service(0);+ let payer = user("[email protected]");+ payments.set_pay(PayOutcome::Declined);+ svc.purchase_credits(&payer, 2_500).await.unwrap();++ payments.set_pay(PayOutcome::Paid);+ let purchase = svc.purchase_credits(&payer, 2_500).await.unwrap();++ assert_eq!(purchase.status, CreditPurchaseStatus::Paid);+ assert!(payments.voided().is_empty());+ assert_eq!(repo.reloads().len(), 1);+ assert_eq!(payments.opened_reloads().len(), 1);+ assert_eq!(repo.state.lock().unwrap().balance, 2_500);+}++#[tokio::test]+async fn a_declined_invoice_voided_in_stripe_is_replaced_by_a_fresh_purchase() {+ let (svc, repo, payments, _) = premium_service(0);+ let payer = user("[email protected]");+ payments.set_pay(PayOutcome::Declined);+ svc.purchase_credits(&payer, 2_500).await.unwrap();++ // The retried invoice is void; the next reservation is new and paid.+ payments.set_pay(PayOutcome::Paid);+ payments.queue_pay(&[PayOutcome::Uncollectible]);+ let purchase = svc.purchase_credits(&payer, 2_500).await.unwrap();++ assert_eq!(purchase.status, CreditPurchaseStatus::Paid);+ let reloads = repo.reloads();+ assert_eq!(reloads.len(), 2);+ assert_eq!(reloads[0].status, CreditReloadStatus::Failed);+ assert_eq!(reloads[0].invoice, None);+ assert_eq!(reloads[1].status, CreditReloadStatus::Paid);+ assert_eq!(repo.state.lock().unwrap().balance, 2_500);+}++#[tokio::test]+async fn a_provider_error_is_an_error_not_a_decline() {+ let (svc, repo, payments, _) = premium_service(0);+ let payer = user("[email protected]");+ payments.set_pay(PayOutcome::Error);++ assert!(matches!(+ svc.purchase_credits(&payer, 2_500).await,+ Err(BillingError::Payment(_))+ ));+ // The invoice stays on the row, so buying again retries it.+ let reloads = repo.reloads();+ assert_eq!(reloads[0].status, CreditReloadStatus::Failed);+ assert!(reloads[0].invoice.is_some());++ payments.set_pay(PayOutcome::Paid);+ let purchase = svc.purchase_credits(&payer, 2_500).await.unwrap();+ assert_eq!(purchase.status, CreditPurchaseStatus::Paid);+ assert_eq!(repo.reloads().len(), 1);+}++#[tokio::test]+async fn a_failed_void_after_3d_secure_leaves_the_invoice_retryable() {+ let (svc, repo, payments, _) = premium_service(0);+ let payer = user("[email protected]");+ payments.set_pay(PayOutcome::AuthenticationRequired);+ payments.set_void(VoidOutcome::Error);++ assert!(svc.purchase_credits(&payer, 2_500).await.is_err());+ let reloads = repo.reloads();+ assert_eq!(reloads[0].status, CreditReloadStatus::Failed);+ assert!(reloads[0].invoice.is_some());++ // The next attempt retries the same invoice and voids it this time.+ payments.set_void(VoidOutcome::Voided);+ let purchase = svc.purchase_credits(&payer, 2_500).await.unwrap();+ assert_eq!(+ purchase.status,+ CreditPurchaseStatus::AuthenticationRequired+ );+ assert_eq!(repo.reloads().len(), 1);+ assert_eq!(repo.reloads()[0].invoice, None);+}++#[tokio::test]+async fn no_card_but_stripe_already_collected_the_declined_invoice_reports_paid() {+ let (svc, repo, payments, _) = premium_service(0);+ let payer = user("[email protected]");+ payments.set_pay(PayOutcome::Declined);+ svc.purchase_credits(&payer, 2_500).await.unwrap();++ payments.remove_card();+ payments.set_void(VoidOutcome::AlreadyPaid);+ let purchase = svc.purchase_credits(&payer, 5_000).await.unwrap();++ assert_eq!(+ purchase,+ CreditPurchase {+ amount_cents: 2_500,+ status: CreditPurchaseStatus::Paid,+ }+ );+ assert_eq!(repo.state.lock().unwrap().balance, 2_500);+ assert_eq!(repo.reloads()[0].status, CreditReloadStatus::Paid);+ payments.restore_card();+}++#[tokio::test]+async fn a_paid_invoice_that_never_reached_its_row_is_booked_by_reload_id() {+ let (svc, repo, _, _) = premium_service(0);+ let payer = user("[email protected]");+ // The collector died after Stripe finalized the invoice but before the+ // row recorded it.+ let PurchaseReservation::New(orphan) = repo+ .reserve_credit_purchase(&payer, &payer, 2_500, None, Utc::now())+ .await+ .unwrap()+ else {+ panic!("purchase reserved");+ };++ // A failure event never adopts the orphan.+ svc.mark_credit_reload_invoice("in_lost", Some(orphan.id), false)+ .await+ .unwrap();+ assert_eq!(repo.reloads()[0].invoice, None);++ svc.mark_credit_reload_invoice("in_lost", Some(orphan.id), true)+ .await+ .unwrap();+ let reloads = repo.reloads();+ assert_eq!(reloads[0].status, CreditReloadStatus::Paid);+ assert_eq!(reloads[0].invoice.as_deref(), Some("in_lost"));+ assert_eq!(repo.state.lock().unwrap().balance, 2_500);++ // A duplicate event books nothing twice.+ svc.mark_credit_reload_invoice("in_lost", Some(orphan.id), true)+ .await+ .unwrap();+ assert_eq!(repo.state.lock().unwrap().balance, 2_500);+}++#[tokio::test]+async fn a_team_member_without_a_team_card_on_file_reserves_nothing() {+ let (svc, repo, payments) = purchase_team(Some(5_000));+ payments.remove_card();++ let purchase = svc+ .purchase_credits(&user("[email protected]"), 2_500)+ .await+ .unwrap();++ assert_eq!(purchase.status, CreditPurchaseStatus::PaymentMethodRequired);+ assert!(repo.reloads().is_empty());+ assert!(payments.opened_reloads().is_empty());+}++#[tokio::test]+async fn purchases_need_a_paid_plan_and_an_offered_pack() {+ let (svc, _, _, _) = premium_service(0);+ let payer = user("[email protected]");+ assert!(matches!(+ svc.purchase_credits(&payer, 1_234).await,+ Err(BillingError::InvalidCreditAmount)+ ));++ let free = user("[email protected]");+ let svc = BillingServiceImpl::new(+ FakeEntitlements::default().with(Entitlement::personal(free.clone(), PlanTier::Free)),+ FakeUsage::default(),+ FakeRepo::default(),+ FakePayments::default(),+ AiPricing::testing(),+ );+ assert!(matches!(+ svc.purchase_credits(&free, 2_500).await,+ Err(BillingError::FreePlan)+ ));+}++#[tokio::test]+async fn a_team_member_buys_on_the_team_card_within_the_plan_default_limit() {+ let (svc, repo, payments) = purchase_team(None);+ let member = user("[email protected]");++ // Premium's $200 default applies to members while the owner set no limit.+ svc.purchase_credits(&member, 10_000).await.unwrap();+ svc.purchase_credits(&member, 10_000).await.unwrap();+ assert!(matches!(+ svc.purchase_credits(&member, 2_500).await,+ Err(BillingError::CreditLimitExceeded { remaining_cents: 0 })+ ));++ assert_eq!(repo.state.lock().unwrap().balance, 20_000);+ assert!(+ payments+ .opened_reloads()+ .iter()+ .all(|request| request.customer_id == "cus_owner"+ && request.payer.as_ref() == user("[email protected]").as_ref())+ );+ assert!(+ repo.reloads()+ .iter()+ .all(|reload| reload.purchased_by.as_deref() == Some(member.as_ref()))+ );++ // The owner set no limit, so their own purchases are not capped.+ svc.purchase_credits(&user("[email protected]"), 10_000)+ .await+ .unwrap();+}++#[tokio::test]+async fn automatic_reloads_and_purchases_share_the_owners_monthly_limit() {+ let (svc, repo, _) = purchase_team(Some(5_000));+ let member = user("[email protected]");+ repo.state.lock().unwrap().reloads.push(FakeReload {+ id: macro_uuid::generate_uuid_v7(),+ amount_cents: 2_500,+ status: CreditReloadStatus::Paid,+ invoice: Some("in_auto".into()),+ created_at: Utc::now(),+ kind: CreditReloadKind::Automatic,+ purchased_by: None,+ });++ assert!(matches!(+ svc.purchase_credits(&member, 5_000).await,+ Err(BillingError::CreditLimitExceeded {+ remaining_cents: 2_500+ })+ ));+ svc.purchase_credits(&member, 2_500).await.unwrap();++ let snapshot = svc.snapshot(&member).await.unwrap();+ let limit = snapshot.credit_purchase.unwrap();+ assert_eq!(limit.monthly_limit_cents, Some(5_000));+ assert_eq!(limit.committed_cents, 5_000);+}++#[tokio::test]+async fn members_see_the_plan_default_limit_and_payers_their_own() {+ let (svc, _, _) = purchase_team(None);+ let member = svc.snapshot(&user("[email protected]")).await.unwrap();+ assert_eq!(+ member.credit_purchase.unwrap().monthly_limit_cents,+ Some(20_000)+ );+ let owner = svc.snapshot(&user("[email protected]")).await.unwrap();+ assert_eq!(owner.credit_purchase.unwrap().monthly_limit_cents, None);+}++#[tokio::test]+async fn a_declined_purchase_retries_its_invoice_and_never_pauses_auto_reload() {+ let (svc, repo, payments, _) = premium_service(0);+ let payer = user("[email protected]");+ payments.set_pay(PayOutcome::Declined);++ let declined = svc.purchase_credits(&payer, 2_500).await.unwrap();+ assert_eq!(declined.status, CreditPurchaseStatus::Declined);+ assert!(!repo.state.lock().unwrap().auto_reload_suspended);+ let invoice = repo.reloads()[0].invoice.clone().unwrap();++ // Stripe reports the failure too: still no effect on Auto-Reload.+ svc.mark_credit_reload_invoice(&invoice, None, false)+ .await+ .unwrap();+ assert!(!repo.state.lock().unwrap().auto_reload_suspended);++ // Buying the same pack again pays the open invoice instead of charging a+ // second time.+ payments.set_pay(PayOutcome::Paid);+ let retried = svc.purchase_credits(&payer, 2_500).await.unwrap();+ assert_eq!(+ retried,+ CreditPurchase {+ amount_cents: 2_500,+ status: CreditPurchaseStatus::Paid,+ }+ );+ assert_eq!(payments.opened_reloads().len(), 1);+ assert_eq!(repo.state.lock().unwrap().balance, 2_500);+}++#[tokio::test]+async fn automatic_reloads_never_pick_up_a_purchase() {+ let (svc, repo, payments, _) = premium_service(0);+ let payer = user("[email protected]");+ payments.set_pay(PayOutcome::Declined);+ svc.purchase_credits(&payer, 2_500).await.unwrap();++ // Turning Auto-Reload on reserves its own reload rather than retrying+ // the declined purchase.+ payments.set_pay(PayOutcome::Paid);+ repo.set_balance(0);+ svc.update_auto_reload(&payer, true, thresholds(1_000, 10_000, None))+ .await+ .unwrap();+ let reloads = repo.reloads();+ assert_eq!(reloads.len(), 2);+ assert_eq!(reloads[0].kind, CreditReloadKind::Purchase);+ assert_eq!(reloads[0].status, CreditReloadStatus::Failed);+ assert_eq!(reloads[1].kind, CreditReloadKind::Automatic);+ assert_eq!(reloads[1].status, CreditReloadStatus::Paid);+}diff --git a/crates/ai_billing/src/domain/sweep/test.rs b/crates/ai_billing/src/domain/sweep/test.rsindex 7228502cfe..754948d79a 100644--- a/crates/ai_billing/src/domain/sweep/test.rs+++ b/crates/ai_billing/src/domain/sweep/test.rs@@ -111,6 +111,13 @@ impl BillingService for FakeBilling {) -> Result<UsageSnapshot> {unreachable!()}+ async fn purchase_credits(+ &self,+ _user: &MacroUserIdStr<'_>,+ _amount_cents: i64,+ ) -> Result<crate::domain::CreditPurchase> {+ unreachable!()+ }async fn create_credit_checkout(&self,_user: &MacroUserIdStr<'_>,@@ -143,6 +150,7 @@ impl BillingService for FakeBilling {async fn mark_credit_reload_invoice(&self,_stripe_invoice_id: &str,+ _reload_id: Option<macro_uuid::Uuid>,_paid: bool,) -> Result<()> {unreachable!()diff --git a/crates/ai_billing/src/inbound/axum_router.rs b/crates/ai_billing/src/inbound/axum_router.rsindex 3f5b263972..3664867850 100644--- a/crates/ai_billing/src/inbound/axum_router.rs+++ b/crates/ai_billing/src/inbound/axum_router.rs@@ -5,8 +5,8 @@use crate::domain::{AUTO_RELOAD_DEFAULT_MINIMUM_CENTS, AUTO_RELOAD_DEFAULT_TARGET_CENTS,AUTO_RELOAD_TARGET_MAX_CENTS, AiPricing, AutoReloadThresholds, BillingError, BillingService,- CREDIT_PACKS_CENTS, OVERAGE_LIMIT_MAX_CENTS, OVERAGE_LIMIT_MIN_CENTS, PaymentGateway, PlanTier,- SubscriptionScope, UsageSnapshot,+ CREDIT_PACKS_CENTS, CreditPurchaseStatus, OVERAGE_LIMIT_MAX_CENTS, OVERAGE_LIMIT_MIN_CENTS,+ PaymentGateway, PlanTier, SubscriptionScope, UsageSnapshot,};use axum::{Json, Router,@@ -46,6 +46,9 @@ pub struct PlanCatalogEntry {pub included_ai_cents_per_seat: i64,/// Whether a new purchase or plan move may pick this plan today.pub purchasable: bool,+ /// Monthly automatic reload limit a payer on this plan starts from,+ /// cents. Absent for plans that cannot reload.+ pub auto_reload_default_monthly_limit_cents: Option<i64>,}/// The plan catalog and the knobs the billing UI offers.@@ -307,6 +310,10 @@ where"/ai-billing/credits/checkout",post(create_credit_checkout_handler::<B, Auth>),)+ .route(+ "/ai-billing/credits/purchase",+ post(purchase_credits_handler::<B, Auth>),+ ).route("/internal/ai-billing/settle",post(settle_handler::<B, Auth>),@@ -327,6 +334,9 @@ fn error_response(e: BillingError) -> Response {| BillingError::DirectUsageBillingDisabled| BillingError::InvalidAutoReload(_)| BillingError::NoStripeCustomer => StatusCode::BAD_REQUEST,+ BillingError::CreditLimitExceeded { .. } | BillingError::PurchaseInProgress => {+ StatusCode::CONFLICT+ }BillingError::Payment(_) | BillingError::Storage(_) | BillingError::Entitlement(_) => {tracing::error!(error = ?e, "ai billing request failed");StatusCode::INTERNAL_SERVER_ERROR@@ -393,6 +403,8 @@ pub async fn get_plans_handler(State(pricing): State<AiPricing>) -> Json<PlanCatpurchasable: SeatPlan::PURCHASABLE.into_iter().any(|plan| PlanTier::from(plan) == tier),+ auto_reload_default_monthly_limit_cents: tier+ .default_auto_reload_monthly_limit_cents(),}).collect(),credit_packs_cents: CREDIT_PACKS_CENTS.to_vec(),@@ -478,6 +490,72 @@ pub async fn update_auto_reload_handler<B: BillingService, Auth: MacroAuthorizat}}+/// Request body for [`purchase_credits_handler`].+#[derive(Debug, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct CreditPurchaseRequestBody {+ /// One of the catalog's credit packs, cents.+ pub amount_cents: i64,+}++/// Response for [`purchase_credits_handler`].+#[derive(Debug, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct CreditPurchaseResponse {+ /// Whether the card on file paid.+ pub status: CreditPurchaseStatus,+ /// Amount charged, cents: the requested pack, unless an earlier declined+ /// purchase that Stripe collected in the meantime was booked instead.+ pub amount_cents: i64,+ /// The caller's position after the purchase. Absent when it could not be+ /// read; the purchase still happened, so refetch the summary instead.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub snapshot: Option<UsageSnapshot>,+}++/// Buy a credit pack now, charged to the payer's card on file. Any paid team+/// member may buy, within the team's monthly credit limit.+#[utoipa::path(+ post,+ path = "/ai-billing/credits/purchase",+ operation_id = "purchase_ai_credits",+ request_body = CreditPurchaseRequestBody,+ responses(+ (status = 200, description = "Purchase outcome and updated position", body = CreditPurchaseResponse),+ (status = 400, description = "Invalid pack or no payment account", body = AiBillingErrorBody),+ (status = 401, description = "Unauthorized"),+ (status = 402, description = "A paid plan is required", body = AiBillingErrorBody),+ (status = 409, description = "Over the monthly credit limit, or an earlier purchase is still processing", body = AiBillingErrorBody),+ (status = 500, description = "Internal server error", body = AiBillingErrorBody),+ ),+ tag = "ai_billing"+)]+#[tracing::instrument(skip(service, user), fields(user_id = %user.authorization.user.macro_user_id, cents = req.amount_cents))]+pub async fn purchase_credits_handler<B: BillingService, Auth: MacroAuthorizationService>(+ State(service): State<Arc<B>>,+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ Json(req): Json<CreditPurchaseRequestBody>,+) -> Response {+ let user_id = &user.authorization.user.macro_user_id;+ let purchase = match service.purchase_credits(user_id, req.amount_cents).await {+ Ok(purchase) => purchase,+ Err(e) => return error_response(e),+ };+ // A failed read must not hide a completed purchase: reporting an error+ // here would invite the buyer to pay again.+ let snapshot = service+ .snapshot(user_id)+ .await+ .inspect_err(|e| tracing::warn!(error = ?e, "snapshot after credit purchase failed"))+ .ok();+ Json(CreditPurchaseResponse {+ status: purchase.status,+ amount_cents: purchase.amount_cents,+ snapshot,+ })+ .into_response()+}+/// Start a Stripe Checkout for a credit pack. Payer only.#[utoipa::path(post,diff --git a/crates/ai_billing/src/inbound/axum_router/test.rs b/crates/ai_billing/src/inbound/axum_router/test.rsindex 3737a15c91..b0333a5481 100644--- a/crates/ai_billing/src/inbound/axum_router/test.rs+++ b/crates/ai_billing/src/inbound/axum_router/test.rs@@ -104,6 +104,16 @@ async fn plan_catalog_lists_every_tier_and_marks_the_purchasable_ones() {catalog.auto_reload_defaults.target_balance_cents,AUTO_RELOAD_DEFAULT_TARGET_CENTS);++ // Paid plans start Auto-Reload with a monthly limit sized to the plan.+ assert_eq!(+ catalog+ .plans+ .iter()+ .map(|plan| plan.auto_reload_default_monthly_limit_cents)+ .collect::<Vec<_>>(),+ vec![None, Some(20_000), Some(100_000)]+ );}#[test]diff --git a/crates/ai_billing/src/lib.rs b/crates/ai_billing/src/lib.rsindex db98cef6d0..8d62de5260 100644--- a/crates/ai_billing/src/lib.rs+++ b/crates/ai_billing/src/lib.rs@@ -58,7 +58,8 @@ pub use ai_usage::{AiFeature, AiUsageEnforcement};pub use domain::{AdmissionFuture, AiAdmissionError, AiAdmissionService, AiPricing, AiUsageBilling,AllowanceDecision, AutoReloadSnapshot, AutoReloadThresholds, BillingAdmissionService,- BillingError, BillingPeriod, BillingService, BillingSettings, CREDIT_PACKS_CENTS, DenyReason,- DisabledAiAdmissionService, Entitlement, IncludedAllowanceCents, OverageMarkupPercent,- PayerScope, PlanAllowances, PlanTier, PricingError, UsageSnapshot, cost_cents,+ BillingError, BillingPeriod, BillingService, BillingSettings, CREDIT_PACKS_CENTS,+ CreditPurchaseSnapshot, CreditPurchaseStatus, DenyReason, DisabledAiAdmissionService,+ Entitlement, IncludedAllowanceCents, OverageMarkupPercent, PayerScope, PlanAllowances,+ PlanTier, PricingError, UsageSnapshot, cost_cents,};diff --git a/crates/ai_billing/src/outbound/http_payment_gateway.rs b/crates/ai_billing/src/outbound/http_payment_gateway.rsindex 81a5f8a17d..49b3abc534 100644--- a/crates/ai_billing/src/outbound/http_payment_gateway.rs+++ b/crates/ai_billing/src/outbound/http_payment_gateway.rs@@ -6,8 +6,8 @@ mod test;use super::NoOpPaymentGateway;use crate::domain::{- BillingError, BillingPeriod, CreditCheckoutRequest, CreditReloadRequest, OverageChargeRequest,- PaymentGateway, Result, SubscriptionScope,+ BillingError, BillingPeriod, CreditCheckoutRequest, CreditReloadRequest, InvoicePayment,+ InvoiceVoid, OverageChargeRequest, PaymentGateway, Result, SubscriptionScope,};use authentication_service_client::AuthServiceClient;use macro_uuid::Uuid;@@ -53,12 +53,26 @@ impl PaymentGateway for HttpPaymentGateway {charge_id: Uuid,invoice_id: &str,scope: SubscriptionScope,- ) -> Result<bool> {+ ) -> Result<InvoicePayment> {NoOpPaymentGateway.pay_overage_invoice(charge_id, invoice_id, scope).await}+ async fn void_credit_invoice(&self, invoice_id: &str) -> Result<InvoiceVoid> {+ NoOpPaymentGateway.void_credit_invoice(invoice_id).await+ }++ async fn has_payment_method(+ &self,+ customer_id: &str,+ scope: SubscriptionScope,+ ) -> Result<bool> {+ NoOpPaymentGateway+ .has_payment_method(customer_id, scope)+ .await+ }+async fn subscription_period(&self,customer_id: &str,diff --git a/crates/ai_billing/src/outbound/pg_billing_repo.rs b/crates/ai_billing/src/outbound/pg_billing_repo.rsindex 28f4581b47..a7a2cd45fe 100644--- a/crates/ai_billing/src/outbound/pg_billing_repo.rs+++ b/crates/ai_billing/src/outbound/pg_billing_repo.rs@@ -16,10 +16,10 @@ use super::pg_funding_repo::{credit_commitments, lock_payer, postpaid_commitmentuse crate::domain::financial::legacy_cap_remaining;use crate::domain::{AiPricing, AllowanceStore, AutoReloadThresholds, BillingError, BillingPeriod, BillingRepo,- BillingSettings, CreditReloadStatus, OpenPeriodStart, OverageChargeStatus, PendingCharge,- PendingReload, PeriodAllowance, PeriodLedger, ReloadState, ResolvedReload, Result,- SeatAllowance, SeatGeneration, SettlementOutcome, SettlementPolicy, SettlementState,- plan_reload, plan_settlement,+ BillingSettings, CreditReloadKind, CreditReloadStatus, OpenPeriodStart, OverageChargeStatus,+ PendingCharge, PendingReload, PeriodAllowance, PeriodLedger, PurchaseReservation, ReloadState,+ ResolvedReload, Result, SeatAllowance, SeatGeneration, SettlementOutcome, SettlementPolicy,+ SettlementState, plan_reload, plan_settlement,};use chrono::{DateTime, Utc};use macro_user_id::user_id::MacroUserIdStr;@@ -65,6 +65,12 @@ async fn reload_committed_cents(FROM ai_credit_reloadWHERE user_id = $1AND (status <> 'failed' OR stripe_invoice_id IS NOT NULL)+ -- A purchase whose collector died before Stripe saw it charged+ -- nothing; a paid webhook still books it by reload id.+ AND NOT (kind = 'purchase'+ AND status = 'pending'+ AND stripe_invoice_id IS NULL+ AND updated_at < NOW() - INTERVAL '10 minutes')AND created_at >= $2AND created_at < $3"#,@@ -82,18 +88,24 @@ async fn book_credit_reload(payer: &MacroUserIdStr<'_>,amount_cents: i64,stripe_invoice_id: &str,+ kind: CreditReloadKind,) -> Result<bool> {let id = macro_uuid::generate_uuid_v7();+ let note = match kind {+ CreditReloadKind::Automatic => "Automatic reload",+ CreditReloadKind::Purchase => "Credit purchase",+ };let result = sqlx::query!(r#"INSERT INTO ai_credit_ledger (id, user_id, kind, delta_cents, stripe_reference, note)- VALUES ($1, $2, 'purchase', $3, $4, 'Automatic reload')+ VALUES ($1, $2, 'purchase', $3, $4, $5)ON CONFLICT (stripe_reference) WHERE stripe_reference IS NOT NULL DO NOTHING"#,id,payer.as_ref(),amount_cents,stripe_invoice_id,+ note,).execute(conn).await@@ -930,6 +942,7 @@ impl BillingRepo for PgBillingRepo {AND updated_at < NOW() - INTERVAL '10 minutes') AS "orphaned!"FROM ai_credit_reloadWHERE user_id = $1+ AND kind = 'automatic'AND (status = 'pending'OR (status = 'failed' AND stripe_invoice_id IS NOT NULL))ORDER BY created_at@@ -1032,6 +1045,152 @@ impl BillingRepo for PgBillingRepo {}))}+ #[tracing::instrument(skip(self), err)]+ async fn reserve_credit_purchase(+ &self,+ payer: &MacroUserIdStr<'_>,+ purchased_by: &MacroUserIdStr<'_>,+ amount_cents: i64,+ monthly_limit_cents: Option<i64>,+ now: DateTime<Utc>,+ ) -> Result<PurchaseReservation> {+ let payer = payer.as_ref();+ let mut tx = self.pool.begin().await.map_err(storage)?;+ // Serialize purchases with reloads and settlements on the account row.+ lock_payer(&mut tx, payer).await.map_err(funding_storage)?;+ let open = sqlx::query!(+ r#"+ SELECT id, amount_cents, stripe_invoice_id, status::text AS "status!",+ (status = 'pending'+ AND stripe_invoice_id IS NULL+ AND updated_at < NOW() - INTERVAL '10 minutes') AS "orphaned!"+ FROM ai_credit_reload+ WHERE user_id = $1+ AND kind = 'purchase'+ AND (status = 'pending'+ OR (status = 'failed' AND stripe_invoice_id IS NOT NULL))+ ORDER BY created_at+ FOR UPDATE+ "#,+ payer,+ )+ .fetch_all(&mut *tx)+ .await+ .map_err(storage)?;+ // A purchase whose collector died before Stripe saw it charged nothing.+ for row in open.iter().filter(|row| row.orphaned) {+ sqlx::query!(+ r#"+ UPDATE ai_credit_reload+ SET status = 'failed', updated_at = NOW()+ WHERE id = $1+ "#,+ row.id,+ )+ .execute(&mut *tx)+ .await+ .map_err(storage)?;+ }+ if let Some(row) = open.iter().find(|row| row.status == "failed") {+ sqlx::query!(+ r#"+ UPDATE ai_credit_reload+ SET status = 'pending', updated_at = NOW()+ WHERE id = $1+ "#,+ row.id,+ )+ .execute(&mut *tx)+ .await+ .map_err(storage)?;+ tx.commit().await.map_err(storage)?;+ return Ok(PurchaseReservation::Retry(PendingReload {+ id: row.id,+ amount_cents: row.amount_cents,+ stripe_invoice_id: row.stripe_invoice_id.clone(),+ }));+ }+ if open.iter().any(|row| !row.orphaned) {+ tx.commit().await.map_err(storage)?;+ return Ok(PurchaseReservation::InProgress);+ }++ if let Some(limit) = monthly_limit_cents {+ let month = BillingPeriod::calendar_month(now);+ let committed = reload_committed_cents(&mut tx, payer, month).await?;+ let remaining_cents = (limit - committed).max(0);+ if amount_cents > remaining_cents {+ tx.commit().await.map_err(storage)?;+ return Ok(PurchaseReservation::OverLimit { remaining_cents });+ }+ }++ let id = macro_uuid::generate_uuid_v7();+ sqlx::query!(+ r#"+ INSERT INTO ai_credit_reload (id, user_id, amount_cents, status, kind, purchased_by)+ VALUES ($1, $2, $3, 'pending', 'purchase', $4)+ "#,+ id,+ payer,+ amount_cents,+ purchased_by.as_ref(),+ )+ .execute(&mut *tx)+ .await+ .map_err(storage)?;+ tx.commit().await.map_err(storage)?;+ Ok(PurchaseReservation::New(PendingReload {+ id,+ amount_cents,+ stripe_invoice_id: None,+ }))+ }++ async fn declined_credit_purchases(+ &self,+ payer: &MacroUserIdStr<'_>,+ ) -> Result<Vec<PendingReload>> {+ let rows = sqlx::query!(+ r#"+ SELECT id, amount_cents, stripe_invoice_id+ FROM ai_credit_reload+ WHERE user_id = $1+ AND kind = 'purchase'+ AND status = 'failed'+ AND stripe_invoice_id IS NOT NULL+ ORDER BY created_at+ "#,+ payer.as_ref(),+ )+ .fetch_all(&self.pool)+ .await+ .map_err(storage)?;+ Ok(rows+ .into_iter()+ .map(|row| PendingReload {+ id: row.id,+ amount_cents: row.amount_cents,+ stripe_invoice_id: row.stripe_invoice_id,+ })+ .collect())+ }++ async fn void_credit_purchase(&self, reload_id: Uuid) -> Result<()> {+ sqlx::query!(+ r#"+ UPDATE ai_credit_reload+ SET status = 'failed', stripe_invoice_id = NULL, updated_at = NOW()+ WHERE id = $1 AND kind = 'purchase' AND status <> 'paid'+ "#,+ reload_id,+ )+ .execute(&self.pool)+ .await+ .map_err(storage)?;+ Ok(())+ }+async fn finish_credit_reload(&self,reload_id: Uuid,@@ -1061,12 +1220,14 @@ impl BillingRepo for PgBillingRepo {payer: &MacroUserIdStr<'_>,amount_cents: i64,stripe_invoice_id: &str,+ kind: CreditReloadKind,) -> Result<bool> {let mut tx = self.pool.begin().await.map_err(storage)?;lock_payer(&mut tx, payer.as_ref()).await.map_err(funding_storage)?;- let booked = book_credit_reload(&mut tx, payer, amount_cents, stripe_invoice_id).await?;+ let booked =+ book_credit_reload(&mut tx, payer, amount_cents, stripe_invoice_id, kind).await?;tx.commit().await.map_err(storage)?;Ok(booked)}@@ -1074,12 +1235,25 @@ impl BillingRepo for PgBillingRepo {async fn resolve_credit_reload_invoice(&self,stripe_invoice_id: &str,+ reload_id: Option<Uuid>,status: CreditReloadStatus,) -> Result<Option<ResolvedReload>> {+ // A paid invoice whose id never reached its row (the collector died+ // between Stripe finalizing it and recording it) is matched by the+ // reload id stamped on the invoice, so the charge is still booked.+ let adopt = status == CreditReloadStatus::Paid;let mut tx = self.pool.begin().await.map_err(storage)?;let Some(payer) = sqlx::query_scalar!(- "SELECT user_id FROM ai_credit_reload WHERE stripe_invoice_id = $1",+ r#"+ SELECT user_id FROM ai_credit_reload+ WHERE stripe_invoice_id = $1+ OR ($3 AND id = $2 AND stripe_invoice_id IS NULL)+ ORDER BY (stripe_invoice_id = $1) DESC NULLS LAST+ LIMIT 1+ "#,stripe_invoice_id,+ reload_id,+ adopt,).fetch_optional(&mut *tx).await@@ -1098,14 +1272,19 @@ impl BillingRepo for PgBillingRepo {let Some(row) = sqlx::query!(r#"UPDATE ai_credit_reload- SET status = ($2::text)::ai_credit_reload_status, updated_at = NOW()- WHERE stripe_invoice_id = $1+ SET status = ($2::text)::ai_credit_reload_status,+ stripe_invoice_id = $1,+ updated_at = NOW()+ WHERE (stripe_invoice_id = $1+ OR ($4 AND id = $3 AND stripe_invoice_id IS NULL))AND status <> 'paid'AND status <> ($2::text)::ai_credit_reload_status- RETURNING user_id, amount_cents+ RETURNING user_id, amount_cents, kind::text AS "kind!""#,stripe_invoice_id,status.to_string(),+ reload_id,+ adopt,).fetch_optional(&mut *tx).await@@ -1116,6 +1295,12 @@ impl BillingRepo for PgBillingRepo {let resolved = ResolvedReload {payer: MacroUserIdStr::try_from(row.user_id).map_err(invalid_payer)?,amount_cents: row.amount_cents,+ kind: CreditReloadKind::from_str(&row.kind).map_err(|e| {+ BillingError::Storage(anyhow::anyhow!(+ "unknown credit reload kind {}: {e}",+ row.kind+ ))+ })?,};if status == CreditReloadStatus::Paid {book_credit_reload(@@ -1123,6 +1308,7 @@ impl BillingRepo for PgBillingRepo {&resolved.payer,resolved.amount_cents,stripe_invoice_id,+ resolved.kind,).await?;}diff --git a/crates/ai_billing/src/outbound/pg_billing_repo/test.rs b/crates/ai_billing/src/outbound/pg_billing_repo/test.rsindex 4b9ae73690..0e3dc5c88a 100644--- a/crates/ai_billing/src/outbound/pg_billing_repo/test.rs+++ b/crates/ai_billing/src/outbound/pg_billing_repo/test.rs@@ -672,8 +672,8 @@ async fn auto_reload_defaults_when_no_account_row_exists(pool: PgPool) {assert_eq!(settings.auto_reload,AutoReloadThresholds {- minimum_cents: 1_000,- target_cents: 10_000,+ minimum_cents: 500,+ target_cents: 2_500,monthly_limit_cents: None,});@@ -811,7 +811,7 @@ async fn reserve_credit_reload_subtracts_usage_the_settlement_will_consume(pool:.await.unwrap();assert_eq!(repo.credit_balance_cents(&payer()).await.unwrap(), 500);- repo.record_credit_reload(&payer(), 9_500, "in_1")+ repo.record_credit_reload(&payer(), 9_500, "in_1", CreditReloadKind::Automatic).await.unwrap();assert!(@@ -1042,7 +1042,7 @@ async fn reserve_credit_reload_retries_a_failed_reload_on_its_open_invoice(pool:async fn credit_reloads_are_idempotent_on_the_invoice(pool: PgPool) {let repo = PgBillingRepo::new(pool, AiPricing::testing());assert!(- repo.record_credit_reload(&payer(), 9_500, "in_1")+ repo.record_credit_reload(&payer(), 9_500, "in_1", CreditReloadKind::Automatic).await.unwrap());@@ -1050,7 +1050,7 @@ async fn credit_reloads_are_idempotent_on_the_invoice(pool: PgPool) {// The collector and the webhook may both report the same invoice.assert!(!repo- .record_credit_reload(&payer(), 9_500, "in_1")+ .record_credit_reload(&payer(), 9_500, "in_1", CreditReloadKind::Automatic).await.unwrap());@@ -1081,28 +1081,28 @@ async fn reload_invoice_webhooks_resolve_once_and_never_unpay(pool: PgPool) {.unwrap();assert!(- repo.resolve_credit_reload_invoice("in_unknown", CreditReloadStatus::Paid)+ repo.resolve_credit_reload_invoice("in_unknown", None, CreditReloadStatus::Paid).await.unwrap().is_none());// Declined first; re-reporting it is a no-op.let failed = repo- .resolve_credit_reload_invoice("in_1", CreditReloadStatus::Failed)+ .resolve_credit_reload_invoice("in_1", None, CreditReloadStatus::Failed).await.unwrap().expect("status changed");assert_eq!(failed.payer.as_ref(), payer().as_ref());assert_eq!(failed.amount_cents, 10_000);assert!(- repo.resolve_credit_reload_invoice("in_1", CreditReloadStatus::Failed)+ repo.resolve_credit_reload_invoice("in_1", None, CreditReloadStatus::Failed).await.unwrap().is_none());// Stripe's retry collected it: reported exactly once.let paid = repo- .resolve_credit_reload_invoice("in_1", CreditReloadStatus::Paid)+ .resolve_credit_reload_invoice("in_1", None, CreditReloadStatus::Paid).await.unwrap().expect("status changed");@@ -1110,14 +1110,14 @@ async fn reload_invoice_webhooks_resolve_once_and_never_unpay(pool: PgPool) {assert_eq!(paid.amount_cents, 10_000);assert_eq!(repo.credit_balance_cents(&payer()).await.unwrap(), 10_000);assert!(- repo.resolve_credit_reload_invoice("in_1", CreditReloadStatus::Paid)+ repo.resolve_credit_reload_invoice("in_1", None, CreditReloadStatus::Paid).await.unwrap().is_none());// A late or duplicate failure cannot un-pay it.assert!(- repo.resolve_credit_reload_invoice("in_1", CreditReloadStatus::Failed)+ repo.resolve_credit_reload_invoice("in_1", None, CreditReloadStatus::Failed).await.unwrap().is_none()@@ -1148,7 +1148,7 @@ async fn reload_invoice_credit_write_failure_leaves_paid_webhook_retryable(pool:.await.unwrap();assert!(- repo.resolve_credit_reload_invoice("in_retry", CreditReloadStatus::Paid)+ repo.resolve_credit_reload_invoice("in_retry", None, CreditReloadStatus::Paid).await.is_err());@@ -1167,7 +1167,7 @@ async fn reload_invoice_credit_write_failure_leaves_paid_webhook_retryable(pool:.await.unwrap();assert!(- repo.resolve_credit_reload_invoice("in_retry", CreditReloadStatus::Paid)+ repo.resolve_credit_reload_invoice("in_retry", None, CreditReloadStatus::Paid).await.unwrap().is_some()@@ -1175,7 +1175,7 @@ async fn reload_invoice_credit_write_failure_leaves_paid_webhook_retryable(pool:assert_eq!(repo.credit_balance_cents(&payer()).await.unwrap(), 10_000);// Re-delivery cannot issue the purchased credits twice.assert!(- repo.resolve_credit_reload_invoice("in_retry", CreditReloadStatus::Paid)+ repo.resolve_credit_reload_invoice("in_retry", None, CreditReloadStatus::Paid).await.unwrap().is_none()@@ -1200,12 +1200,17 @@ async fn reload_invoice_webhook_deduplicates_credits_booked_by_collector(pool: P).await.unwrap();- repo.record_credit_reload(&payer(), reserved.amount_cents, "in_collector")- .await- .unwrap();+ repo.record_credit_reload(+ &payer(),+ reserved.amount_cents,+ "in_collector",+ CreditReloadKind::Automatic,+ )+ .await+ .unwrap();assert!(- repo.resolve_credit_reload_invoice("in_collector", CreditReloadStatus::Paid)+ repo.resolve_credit_reload_invoice("in_collector", None, CreditReloadStatus::Paid).await.unwrap().is_some()@@ -1648,3 +1653,293 @@ async fn credit_only_settlement_never_reserves_or_retries_direct_charges(pool: Passert_eq!(charge_rows(&pool).await, 1);}}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn credit_purchases_respect_the_monthly_limit_and_retry_declined_invoices(pool: PgPool) {+ let repo = PgBillingRepo::new(pool.clone(), AiPricing::testing());+ let now = Utc::now();+ let member = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();++ let PurchaseReservation::New(first) = repo+ .reserve_credit_purchase(&payer(), &member, 2_500, Some(5_000), now)+ .await+ .unwrap()+ else {+ panic!("first purchase reserved");+ };+ // Still with Stripe: a second purchase waits.+ assert_eq!(+ repo.reserve_credit_purchase(&payer(), &member, 2_500, Some(5_000), now)+ .await+ .unwrap(),+ PurchaseReservation::InProgress+ );+ // Declined with its invoice open: buying again retries that invoice.+ repo.finish_credit_reload(first.id, Some("in_first"), CreditReloadStatus::Failed)+ .await+ .unwrap();+ assert_eq!(+ repo.reserve_credit_purchase(&payer(), &member, 5_000, Some(5_000), now)+ .await+ .unwrap(),+ PurchaseReservation::Retry(PendingReload {+ id: first.id,+ amount_cents: 2_500,+ stripe_invoice_id: Some("in_first".into()),+ })+ );+ repo.finish_credit_reload(first.id, Some("in_first"), CreditReloadStatus::Paid)+ .await+ .unwrap();++ // The paid purchase counts against the limit.+ assert_eq!(+ repo.reserve_credit_purchase(&payer(), &member, 5_000, Some(5_000), now)+ .await+ .unwrap(),+ PurchaseReservation::OverLimit {+ remaining_cents: 2_500+ }+ );+ assert!(matches!(+ repo.reserve_credit_purchase(&payer(), &member, 2_500, Some(5_000), now)+ .await+ .unwrap(),+ PurchaseReservation::New(_)+ ));+ let committed = repo+ .credit_reload_committed_cents(&payer(), BillingPeriod::calendar_month(now))+ .await+ .unwrap();+ assert_eq!(committed, 5_000);+ let buyer = sqlx::query_scalar!(+ "SELECT purchased_by FROM ai_credit_reload WHERE kind = 'purchase' LIMIT 1"+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(buyer.as_deref(), Some(member.as_ref()));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn automatic_reloads_ignore_open_purchases(pool: PgPool) {+ let repo = PgBillingRepo::new(pool.clone(), AiPricing::testing());+ let now = Utc::now();+ let period_start = now - chrono::Duration::days(10);+ let PurchaseReservation::New(purchase) = repo+ .reserve_credit_purchase(&payer(), &payer(), 2_500, None, now)+ .await+ .unwrap()+ else {+ panic!("purchase reserved");+ };+ repo.finish_credit_reload(purchase.id, Some("in_purchase"), CreditReloadStatus::Failed)+ .await+ .unwrap();+ enable_auto_reload(&repo, &thresholds(None)).await;++ let reload = repo+ .reserve_credit_reload(&payer(), period_start, 0, now)+ .await+ .unwrap()+ .expect("automatic reload reserved");+ assert_ne!(reload.id, purchase.id);+ assert!(reload.stripe_invoice_id.is_none());++ // A failed purchase invoice resolves as a purchase.+ let resolved = repo+ .resolve_credit_reload_invoice("in_purchase", None, CreditReloadStatus::Paid)+ .await+ .unwrap()+ .unwrap();+ assert_eq!(resolved.kind, CreditReloadKind::Purchase);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn voided_purchases_are_neither_retried_nor_counted(pool: PgPool) {+ let repo = PgBillingRepo::new(pool.clone(), AiPricing::testing());+ let now = Utc::now();+ let member = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();++ let PurchaseReservation::New(declined) = repo+ .reserve_credit_purchase(&payer(), &member, 2_500, Some(5_000), now)+ .await+ .unwrap()+ else {+ panic!("purchase reserved");+ };+ repo.finish_credit_reload(declined.id, Some("in_declined"), CreditReloadStatus::Failed)+ .await+ .unwrap();+ // An automatic reload's open invoice is never treated as a purchase.+ enable_auto_reload(&repo, &thresholds(None)).await;+ let auto = repo+ .reserve_credit_reload(&payer(), now - chrono::Duration::days(10), 0, now)+ .await+ .unwrap()+ .expect("automatic reload reserved");+ repo.finish_credit_reload(auto.id, Some("in_auto"), CreditReloadStatus::Failed)+ .await+ .unwrap();++ assert_eq!(+ repo.declined_credit_purchases(&payer()).await.unwrap(),+ vec![PendingReload {+ id: declined.id,+ amount_cents: 2_500,+ stripe_invoice_id: Some("in_declined".into()),+ }]+ );+ let period = BillingPeriod::calendar_month(now);+ let before = repo+ .credit_reload_committed_cents(&payer(), period)+ .await+ .unwrap();++ repo.void_credit_purchase(declined.id).await.unwrap();+ // Voiding never touches an automatic reload.+ repo.void_credit_purchase(auto.id).await.unwrap();++ assert!(+ repo.declined_credit_purchases(&payer())+ .await+ .unwrap()+ .is_empty()+ );+ assert_eq!(+ repo.credit_reload_committed_cents(&payer(), period)+ .await+ .unwrap(),+ before - 2_500+ );+ // Buying again reserves a fresh purchase instead of retrying the void.+ assert!(matches!(+ repo.reserve_credit_purchase(&payer(), &member, 2_500, None, now)+ .await+ .unwrap(),+ PurchaseReservation::New(_)+ ));+ let auto_invoice = sqlx::query_scalar!(+ "SELECT stripe_invoice_id FROM ai_credit_reload WHERE id = $1",+ auto.id+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(auto_invoice.as_deref(), Some("in_auto"));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_paid_purchase_cannot_be_voided(pool: PgPool) {+ let repo = PgBillingRepo::new(pool.clone(), AiPricing::testing());+ let now = Utc::now();+ let PurchaseReservation::New(paid) = repo+ .reserve_credit_purchase(&payer(), &payer(), 2_500, None, now)+ .await+ .unwrap()+ else {+ panic!("purchase reserved");+ };+ repo.finish_credit_reload(paid.id, Some("in_paid"), CreditReloadStatus::Paid)+ .await+ .unwrap();++ repo.void_credit_purchase(paid.id).await.unwrap();++ let row = sqlx::query!(+ r#"SELECT status::text AS "status!", stripe_invoice_id FROM ai_credit_reload WHERE id = $1"#,+ paid.id+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(row.status, "paid");+ assert_eq!(row.stripe_invoice_id.as_deref(), Some("in_paid"));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_paid_invoice_is_matched_to_its_orphaned_row_by_reload_id(pool: PgPool) {+ let repo = PgBillingRepo::new(pool.clone(), AiPricing::testing());+ let now = Utc::now();+ let PurchaseReservation::New(orphan) = repo+ .reserve_credit_purchase(&payer(), &payer(), 2_500, None, now)+ .await+ .unwrap()+ else {+ panic!("purchase reserved");+ };++ // A failure never adopts the row.+ assert_eq!(+ repo.resolve_credit_reload_invoice("in_lost", Some(orphan.id), CreditReloadStatus::Failed)+ .await+ .unwrap(),+ None+ );+ let resolved = repo+ .resolve_credit_reload_invoice("in_lost", Some(orphan.id), CreditReloadStatus::Paid)+ .await+ .unwrap()+ .expect("orphan adopted");+ assert_eq!(resolved.kind, CreditReloadKind::Purchase);+ assert_eq!(resolved.amount_cents, 2_500);++ let row = sqlx::query!(+ r#"SELECT status::text AS "status!", stripe_invoice_id FROM ai_credit_reload WHERE id = $1"#,+ orphan.id+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(row.status, "paid");+ assert_eq!(row.stripe_invoice_id.as_deref(), Some("in_lost"));+ let note =+ sqlx::query_scalar!("SELECT note FROM ai_credit_ledger WHERE stripe_reference = 'in_lost'")+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(note.as_deref(), Some("Credit purchase"));++ // A row that already has another invoice is never adopted.+ assert_eq!(+ repo.resolve_credit_reload_invoice("in_other", Some(orphan.id), CreditReloadStatus::Paid)+ .await+ .unwrap(),+ None+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_stale_orphaned_purchase_stops_counting_against_the_limit(pool: PgPool) {+ let repo = PgBillingRepo::new(pool.clone(), AiPricing::testing());+ let now = Utc::now();+ let PurchaseReservation::New(orphan) = repo+ .reserve_credit_purchase(&payer(), &payer(), 2_500, None, now)+ .await+ .unwrap()+ else {+ panic!("purchase reserved");+ };+ let period = BillingPeriod::calendar_month(now);+ assert_eq!(+ repo.credit_reload_committed_cents(&payer(), period)+ .await+ .unwrap(),+ 2_500+ );++ sqlx::query!(+ "UPDATE ai_credit_reload SET updated_at = NOW() - INTERVAL '11 minutes' WHERE id = $1",+ orphan.id+ )+ .execute(&pool)+ .await+ .unwrap();++ assert_eq!(+ repo.credit_reload_committed_cents(&payer(), period)+ .await+ .unwrap(),+ 0+ );+}diff --git a/crates/ai_billing/src/outbound/pg_settlement_candidates.rs b/crates/ai_billing/src/outbound/pg_settlement_candidates.rsindex 23341c00c8..b70cb87b28 100644--- a/crates/ai_billing/src/outbound/pg_settlement_candidates.rs+++ b/crates/ai_billing/src/outbound/pg_settlement_candidates.rs@@ -46,7 +46,8 @@ impl SettlementCandidates for PgSettlementCandidates {UNION ALLSELECT user_idFROM ai_credit_reload- WHERE status = 'pending'+ WHERE kind = 'automatic'+ AND status = 'pending'AND stripe_invoice_id IS NULLAND updated_at < $2::timestamptz - INTERVAL '10 minutes'UNION ALLdiff --git a/crates/ai_billing/src/outbound/settling_recorder/test.rs b/crates/ai_billing/src/outbound/settling_recorder/test.rsindex 9bd2caf0b0..0025f2835c 100644--- a/crates/ai_billing/src/outbound/settling_recorder/test.rs+++ b/crates/ai_billing/src/outbound/settling_recorder/test.rs@@ -92,6 +92,14 @@ impl BillingService for FakeBilling {unreachable!()}+ async fn purchase_credits(+ &self,+ _user: &MacroUserIdStr<'_>,+ _amount_cents: i64,+ ) -> Result<crate::domain::CreditPurchase> {+ unreachable!()+ }+async fn create_credit_checkout(&self,_user: &MacroUserIdStr<'_>,@@ -128,6 +136,7 @@ impl BillingService for FakeBilling {async fn mark_credit_reload_invoice(&self,_stripe_invoice_id: &str,+ _reload_id: Option<macro_uuid::Uuid>,_paid: bool,) -> Result<()> {unreachable!()diff --git a/crates/ai_billing/src/outbound/stripe_gateway.rs b/crates/ai_billing/src/outbound/stripe_gateway.rsindex 8d42eef5c5..fdad91b602 100644--- a/crates/ai_billing/src/outbound/stripe_gateway.rs+++ b/crates/ai_billing/src/outbound/stripe_gateway.rs@@ -6,8 +6,8 @@mod test;use crate::domain::{- BillingError, BillingPeriod, CreditCheckoutRequest, CreditReloadRequest, OverageChargeRequest,- PaymentGateway, Result, SubscriptionScope,+ BillingError, BillingPeriod, CreditCheckoutRequest, CreditReloadRequest, InvoicePayment,+ InvoiceVoid, OverageChargeRequest, PaymentGateway, Result, SubscriptionScope,};use chrono::{DateTime, Utc};use macro_user_id::user_id::MacroUserIdStr;@@ -16,13 +16,13 @@ use serde::Serialize;use std::collections::HashMap;use std::sync::Arc;use stripe::{- CheckoutSession, CheckoutSessionMode, CollectionMethod, CreateCheckoutSession,+ ApiErrorsCode, CheckoutSession, CheckoutSessionMode, CollectionMethod, CreateCheckoutSession,CreateCheckoutSessionLineItems, CreateCheckoutSessionLineItemsPriceData,CreateCheckoutSessionLineItemsPriceDataProductData, CreateCheckoutSessionPaymentIntentData,CreateInvoice, CreateInvoiceItem, Currency, Customer, CustomerId, Expandable,FinalizeInvoiceParams, Invoice, InvoiceId, InvoiceItem, InvoicePendingInvoiceItemsBehavior,- InvoiceStatus, ListSubscriptions, PaymentMethodId, RequestStrategy, Subscription,- SubscriptionStatus,+ InvoiceStatus, ListSubscriptions, PaymentIntentStatus, PaymentMethodId, RequestStrategy,+ Subscription, SubscriptionStatus,};/// Metadata key stamped on every Stripe object this crate creates.@@ -263,6 +263,19 @@ impl ChargeMethod {}}+/// Whether the invoice's last payment attempt stopped for card+/// authentication (3-D Secure), which an off-session charge can't complete.+fn needs_authentication(invoice: &Invoice) -> bool {+ let Some(Expandable::Object(intent)) = invoice.payment_intent.as_ref() else {+ return false;+ };+ intent.status == PaymentIntentStatus::RequiresAction+ || intent.last_payment_error.as_ref().is_some_and(|error| {+ error.code == Some(ApiErrorsCode::AuthenticationRequired)+ || error.decline_code.as_deref() == Some("authentication_required")+ })+}+fn customer_fallback(customer: &Customer) -> Option<PaymentMethodId> {customer.invoice_settings@@ -482,7 +495,7 @@ impl PaymentGateway for StripePaymentGateway {charge_id: Uuid,invoice_id: &str,scope: SubscriptionScope,- ) -> Result<bool> {+ ) -> Result<InvoicePayment> {let invoice_id: InvoiceId = invoice_id.parse().map_err(|e| {BillingError::Payment(anyhow::anyhow!("invalid stripe invoice id: {e}"))})?;@@ -498,8 +511,12 @@ impl PaymentGateway for StripePaymentGateway {{return Err(BillingError::DirectUsageBillingDisabled);}- if invoice.status == Some(InvoiceStatus::Paid) {- return Ok(true);+ match invoice.status {+ Some(InvoiceStatus::Paid) => return Ok(InvoicePayment::Paid),+ Some(InvoiceStatus::Void | InvoiceStatus::Uncollectible) => {+ return Ok(InvoicePayment::Uncollectible);+ }+ _ => {}}let invoice_scope = stamped_scope(&invoice)?;let scope = invoice_scope.unwrap_or(scope);@@ -541,12 +558,13 @@ impl PaymentGateway for StripePaymentGateway {.post_form::<Invoice, _>(&format!("/invoices/{invoice_id}/pay"), &pay).await{- Ok(invoice) => Ok(invoice.status == Some(InvoiceStatus::Paid)),+ Ok(invoice) if invoice.status == Some(InvoiceStatus::Paid) => Ok(InvoicePayment::Paid),+ Ok(_) => Ok(InvoicePayment::Declined),Err(e) => {// A decline is a failed collection, not a failed request: the// invoice stays open and Stripe retries it. The invoice's own// status also tells a retry that Stripe already collected it.- let invoice = Invoice::retrieve(&self.client, &invoice_id, &[])+ let invoice = Invoice::retrieve(&self.client, &invoice_id, &["payment_intent"]).await.map_err(|retrieve_err| {tracing::warn!(@@ -556,13 +574,23 @@ impl PaymentGateway for StripePaymentGateway {payment(retrieve_err)})?;match invoice.status {- Some(InvoiceStatus::Paid) => Ok(true),+ Some(InvoiceStatus::Paid) => Ok(InvoicePayment::Paid),+ Some(InvoiceStatus::Open) if needs_authentication(&invoice) => {+ tracing::warn!(+ error = ?e,+ "invoice payment needs card authentication; left open"+ );+ Ok(InvoicePayment::AuthenticationRequired)+ }Some(InvoiceStatus::Open) => {tracing::warn!(error = ?e,"overage invoice payment did not succeed; left open for stripe retries");- Ok(false)+ Ok(InvoicePayment::Declined)+ }+ Some(InvoiceStatus::Void | InvoiceStatus::Uncollectible) => {+ Ok(InvoicePayment::Uncollectible)}other => Err(BillingError::Payment(anyhow::anyhow!("overage invoice is {other:?} after a failed payment attempt: {e}"@@ -572,6 +600,59 @@ impl PaymentGateway for StripePaymentGateway {}}+ #[tracing::instrument(skip(self), err)]+ async fn void_credit_invoice(&self, invoice_id: &str) -> Result<InvoiceVoid> {+ let invoice_id: InvoiceId = invoice_id.parse().map_err(|e| {+ BillingError::Payment(anyhow::anyhow!("invalid stripe invoice id: {e}"))+ })?;+ let invoice = Invoice::retrieve(&self.client, &invoice_id, &[])+ .await+ .map_err(payment)?;+ match invoice.status {+ Some(InvoiceStatus::Paid) => Ok(InvoiceVoid::Paid),+ Some(InvoiceStatus::Open) => {+ match Invoice::void(&self.client, &invoice_id).await {+ Ok(_) => Ok(InvoiceVoid::Voided),+ // Stripe may have collected it between the read and the+ // void; the invoice's own status says which.+ Err(e) => {+ let invoice = Invoice::retrieve(&self.client, &invoice_id, &[])+ .await+ .map_err(payment)?;+ match invoice.status {+ Some(InvoiceStatus::Paid) => Ok(InvoiceVoid::Paid),+ Some(InvoiceStatus::Void | InvoiceStatus::Uncollectible) => {+ Ok(InvoiceVoid::Voided)+ }+ _ => Err(payment(e)),+ }+ }+ }+ }+ _ => Ok(InvoiceVoid::Voided),+ }+ }++ #[tracing::instrument(skip(self), err)]+ async fn has_payment_method(+ &self,+ customer_id: &str,+ scope: SubscriptionScope,+ ) -> Result<bool> {+ let customer_id = parse_customer(customer_id)?;+ let customer = Customer::retrieve(&self.client, &customer_id, &[])+ .await+ .map_err(payment)?;+ let subscriptions = self.non_canceled_subscriptions(&customer_id).await?;+ Ok(+ match charge_method(customer_fallback(&customer), &subscriptions, scope)? {+ ChargeMethod::PaymentMethod(_) => true,+ ChargeMethod::StripeFallback => customer.default_source.is_some(),+ ChargeMethod::NoMatchingSubscription => false,+ },+ )+ }+#[tracing::instrument(skip(self), err)]async fn subscription_period(&self,@@ -613,6 +694,22 @@ impl PaymentGateway for NoOpPaymentGateway {_charge_id: Uuid,_invoice_id: &str,_scope: SubscriptionScope,+ ) -> Result<InvoicePayment> {+ Err(BillingError::Payment(anyhow::anyhow!(+ "payments are not configured in this service"+ )))+ }++ async fn void_credit_invoice(&self, _invoice_id: &str) -> Result<InvoiceVoid> {+ Err(BillingError::Payment(anyhow::anyhow!(+ "payments are not configured in this service"+ )))+ }++ async fn has_payment_method(+ &self,+ _customer_id: &str,+ _scope: SubscriptionScope,) -> Result<bool> {Err(BillingError::Payment(anyhow::anyhow!("payments are not configured in this service"diff --git a/crates/ai_billing/src/outbound/stripe_gateway/test.rs b/crates/ai_billing/src/outbound/stripe_gateway/test.rsindex faec9574c3..87859a0ced 100644--- a/crates/ai_billing/src/outbound/stripe_gateway/test.rs+++ b/crates/ai_billing/src/outbound/stripe_gateway/test.rs@@ -182,7 +182,7 @@ async fn pay_overage_invoice_updates_a_stale_open_invoice_before_paying() {).await.expect("pay overage invoice");- assert!(paid_now);+ assert_eq!(paid_now, InvoicePayment::Paid);let requests = server.received_requests().await.expect("recorded requests");let update_at = request_position(&requests, "POST", &format!("/v1/invoices/{INVOICE_ID}"));@@ -309,7 +309,7 @@ async fn pay_overage_invoice_skips_the_update_when_the_open_invoice_already_matc.pay_overage_invoice(Uuid::from_u128(3), INVOICE_ID, SubscriptionScope::Personal).await.expect("pay overage invoice");- assert!(paid_now);+ assert_eq!(paid_now, InvoicePayment::Paid);let requests = server.received_requests().await.expect("recorded requests");assert!(requests.iter().all(|request| {@@ -640,7 +640,7 @@ async fn pay_overage_invoice_keeps_a_stamped_scope_when_the_live_scope_differs()).await.expect("pay stamped invoice");- assert!(paid_now);+ assert_eq!(paid_now, InvoicePayment::Paid);let requests = server.received_requests().await.expect("recorded requests");let update = post_request(&requests, &format!("/v1/invoices/{INVOICE_ID}"));@@ -695,7 +695,7 @@ async fn pay_overage_invoice_preserves_a_stamped_personal_method_after_team_conv).await.expect("pay converted personal invoice");- assert!(paid_now);+ assert_eq!(paid_now, InvoicePayment::Paid);let requests = server.received_requests().await.expect("recorded requests");assert!(requests.iter().all(|request| {@@ -750,7 +750,7 @@ async fn pay_overage_invoice_returns_when_the_invoice_is_already_paid() {.pay_overage_invoice(Uuid::from_u128(8), INVOICE_ID, SubscriptionScope::Personal).await.expect("already paid invoice");- assert!(paid_now);+ assert_eq!(paid_now, InvoicePayment::Paid);let requests = server.received_requests().await.expect("recorded requests");assert!(requests.iter().all(|request| {@@ -1303,3 +1303,92 @@ async fn historical_direct_usage_invoices_are_never_paid_by_the_gateway() {));assert_eq!(server.received_requests().await.unwrap().len(), 1);}++#[tokio::test]+async fn void_credit_invoice_voids_an_open_invoice() {+ let server = MockServer::start().await;+ let open = open_invoice(Some(CURRENT_PAYMENT_METHOD), Some(PERSONAL_SCOPE_STAMP));+ Mock::given(method("GET"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(stripe_response(&open)))+ .mount(&server)+ .await;+ let mut voided = open.clone();+ voided.status = Some(InvoiceStatus::Void);+ Mock::given(method("POST"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}/void")))+ .respond_with(ResponseTemplate::new(200).set_body_json(stripe_response(&voided)))+ .expect(1)+ .mount(&server)+ .await;++ let outcome = gateway(&server)+ .void_credit_invoice(INVOICE_ID)+ .await+ .unwrap();++ assert_eq!(outcome, InvoiceVoid::Voided);+}++#[tokio::test]+async fn void_credit_invoice_reports_an_invoice_stripe_already_collected() {+ let server = MockServer::start().await;+ let paid = stripe_response(&paid_invoice(CURRENT_PAYMENT_METHOD, None));+ Mock::given(method("GET"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(&paid))+ .mount(&server)+ .await;++ let outcome = gateway(&server)+ .void_credit_invoice(INVOICE_ID)+ .await+ .unwrap();++ assert_eq!(outcome, InvoiceVoid::Paid);+ let requests = server.received_requests().await.unwrap();+ assert!(+ requests+ .iter()+ .all(|request| request.method.as_str() != "POST")+ );+}++#[test]+fn a_payment_that_stopped_for_3d_secure_needs_authentication() {+ let with_intent = |intent: stripe::PaymentIntent| {+ let mut invoice = open_invoice(Some(CURRENT_PAYMENT_METHOD), None);+ invoice.payment_intent = Some(Expandable::Object(Box::new(intent)));+ invoice+ };+ let requires_action = stripe::PaymentIntent {+ status: PaymentIntentStatus::RequiresAction,+ ..Default::default()+ };+ let declined_for_authentication = stripe::PaymentIntent {+ status: PaymentIntentStatus::RequiresPaymentMethod,+ last_payment_error: Some(Box::new(stripe::ApiErrors {+ decline_code: Some("authentication_required".to_string()),+ ..Default::default()+ })),+ ..Default::default()+ };+ let declined = stripe::PaymentIntent {+ status: PaymentIntentStatus::RequiresPaymentMethod,+ last_payment_error: Some(Box::new(stripe::ApiErrors {+ decline_code: Some("insufficient_funds".to_string()),+ ..Default::default()+ })),+ ..Default::default()+ };++ assert!(needs_authentication(&with_intent(requires_action)));+ assert!(needs_authentication(&with_intent(+ declined_for_authentication+ )));+ assert!(!needs_authentication(&with_intent(declined)));+ assert!(!needs_authentication(&open_invoice(+ Some(CURRENT_PAYMENT_METHOD),+ None+ )));+}diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjsindex d5f7361441..309c05d794 100644--- a/crates/code_execution/src/outbound/deno/sdk.mjs+++ b/crates/code_execution/src/outbound/deno/sdk.mjs@@ -9,7 +9,7 @@ async function cO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurre`);U=y.pop()??"";for(let a of y){let i=a.split(``),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var vS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},hS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},mS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},hj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(hS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=vS(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return CO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},CO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},mj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=mS(x),X=Object.entries(S).map(([G,L])=>CO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var uS=/\{[^{}]+\}/g,cS=({path:$,url:O})=>{let j=O,x=O.match(uS);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,hj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,mj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${CO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},U2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=cS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function px($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var z2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var I2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var H2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=hj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=mj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=CO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},T2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},dS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function R2($){for(let O of $.security??[]){if(dS($,O.name))continue;let j=await z2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var ax=($)=>U2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:H2($.querySerializer),url:$.url}),ix=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=cj($.headers,O.headers),j},lS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},cj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?lS(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class uj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var D2=()=>({error:new uj,request:new uj,response:new uj}),rS=H2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),pS={"Content-Type":"application/json"},jj=($={})=>({...I2,headers:pS,parseAs:"auto",querySerializer:rS,...$});var nx=($={})=>{let O=ix(jj(),$),j=()=>({...O}),x=(Q)=>{return O=ix(O,Q),j()},S=D2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:cj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await R2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=ax(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:px(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?T2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return N2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:px(I),url:z})};return{buildUrl:(Q)=>ax({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var _2=nx(jj());class M2{client;constructor($){this.client=$?.client??_2}}class A2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class dj extends M2{static __registry=new A2;constructor($){super($);dj.__registry.set(this,$?.key)}deleteAgentApiKey($){return($.client??this.client).delete({url:"/agents/{agent_id}/api-key",...$})}getAgentApiKey($){return($.client??this.client).get({url:"/agents/{agent_id}/api-key",...$})}putAgentApiKey($){return($.client??this.client).put({url:"/agents/{agent_id}/api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}setGithubPullRequestState($){return($.client??this.client).post({url:"/github_pull_requests/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}listGtmInviteLinks($){return($?.client??this.client).get({url:"/gtm-invite/links",...$})}createGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/links",...$,headers:{"Content-Type":"application/json",...$.headers}})}revokeGtmInviteLink($){return($.client??this.client).delete({url:"/gtm-invite/links/{id}",...$})}getGtmInviteOffer($){return($?.client??this.client).get({url:"/gtm-invite/offer",...$})}resolveGtmInviteLink($){return($.client??this.client).get({url:"/gtm-invite/public/{token}",...$})}redeemGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/redeem",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}macroApiToken($){return($.client??this.client).get({url:"/jwt/macro_api_token",...$})}refresh($){return($?.client??this.client).post({url:"/jwt/refresh",...$})}createInProgressLink($){return($?.client??this.client).post({url:"/link",...$})}emailConnectionProviders($){return($?.client??this.client).get({url:"/link/email/providers",...$})}deleteGithubLink($){return($?.client??this.client).delete({url:"/link/github",...$})}initGithubLink($){return($.client??this.client).post({url:"/link/github",...$})}checkGithubLinkStatus($){return($?.client??this.client).get({url:"/link/github/status",...$})}initGmailLink($){return($.client??this.client).post({url:"/link/gmail",...$})}checkGmailLinkStatus($){return($?.client??this.client).get({url:"/link/gmail/status",...$})}initOutlookLink($){return($?.client??this.client).post({url:"/link/outlook",...$})}appleLogin($){return($.client??this.client).post({url:"/login/apple",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordLogin($){return($.client??this.client).post({url:"/login/password",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessLogin($){return($.client??this.client).post({url:"/login/passwordless",...$,headers:{"Content-Type":"application/json",...$.headers}})}ssoLogin($){return($.client??this.client).get({url:"/login/sso",...$})}logout($){return($?.client??this.client).post({url:"/logout",...$})}createMergeRequest($){return($.client??this.client).post({url:"/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyMergeRequest($){return($.client??this.client).get({url:"/merge/verify/{code}",...$})}sendMobileWelcomeEmail($){return($.client??this.client).post({url:"/mobile-welcome-email",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessCallback($){return($.client??this.client).get({url:"/oauth/passwordless/{code}",...$})}oauthRedirect($){return($?.client??this.client).get({url:"/oauth/redirect",...$})}oauth2Callback($){return($.client??this.client).get({url:"/oauth2/{provider}/callback",...$})}getPermissions($){return($?.client??this.client).get({url:"/permissions",...$})}getUserPermissions($){return($?.client??this.client).get({url:"/permissions/me",...$})}getReferralCode($){return($?.client??this.client).get({url:"/referral/code",...$})}sendReferralCode($){return($.client??this.client).post({url:"/referral/send",...$,headers:{"Content-Type":"application/json",...$.headers}})}sessionCreation($){return($?.client??this.client).post({url:"/session",...$})}sessionLogin($){return($.client??this.client).get({url:"/session/login/{session_code}",...$})}getSystemStatus($){return($?.client??this.client).get({url:"/system-status",...$})}setSystemStatus($){return($.client??this.client).post({url:"/system-status",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSystemStatusHistory($){return($?.client??this.client).get({url:"/system-status/history",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteLink($){return($?.client??this.client).delete({url:"/team/invite-link",...$})}getTeamInviteLink($){return($?.client??this.client).get({url:"/team/invite-link",...$})}createTeamInviteLink($){return($?.client??this.client).post({url:"/team/invite-link",...$})}joinTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/join",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserLanguage($){return($?.client??this.client).get({url:"/user/language",...$})}putUserLanguage($){return($.client??this.client).put({url:"/user/language",...$,headers:{"Content-Type":"application/json",...$.headers}})}getLegacyUserPermissions($){return($?.client??this.client).get({url:"/user/legacy_user_permissions",...$})}getUserLinkExists($){return($.client??this.client).get({url:"/user/link_exists",...$})}deleteUser($){return($?.client??this.client).delete({url:"/user/me",...$})}getUserInfo($){return($?.client??this.client).get({url:"/user/me",...$})}getUserName($){return($?.client??this.client).get({url:"/user/name",...$})}putUserName($){return($?.client??this.client).put({url:"/user/name",...$})}patchUserOnboarding($){return($.client??this.client).patch({url:"/user/onboarding",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserOrganization($){return($?.client??this.client).get({url:"/user/organization",...$})}putProfilePicture($){return($.client??this.client).put({url:"/user/profile_picture",...$})}postProfilePictures($){return($.client??this.client).post({url:"/user/profile_pictures",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserQuota($){return($?.client??this.client).get({url:"/user/quota",...$})}createCheckoutSessionV2($){return($.client??this.client).post({url:"/user/stripe/checkoutv2",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSubscriptionStatus($){return($?.client??this.client).get({url:"/user/stripe/plan",...$})}changePlan($){return($.client??this.client).post({url:"/user/stripe/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPortalSession($){return($.client??this.client).post({url:"/user/stripe/portal",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTrialEligibility($){return($?.client??this.client).get({url:"/user/stripe/trial_eligibility",...$})}patchUserTutorial($){return($.client??this.client).patch({url:"/user/tutorial",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function P2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var vS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},hS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},mS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},hj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(hS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=vS(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return CO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},CO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},mj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=mS(x),X=Object.entries(S).map(([G,L])=>CO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var uS=/\{[^{}]+\}/g,cS=({path:$,url:O})=>{let j=O,x=O.match(uS);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,hj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,mj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${CO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},U2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=cS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function px($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var z2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var I2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var H2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=hj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=mj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=CO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},T2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},dS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function R2($){for(let O of $.security??[]){if(dS($,O.name))continue;let j=await z2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var ax=($)=>U2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:H2($.querySerializer),url:$.url}),ix=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=cj($.headers,O.headers),j},lS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},cj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?lS(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class uj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var D2=()=>({error:new uj,request:new uj,response:new uj}),rS=H2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),pS={"Content-Type":"application/json"},jj=($={})=>({...I2,headers:pS,parseAs:"auto",querySerializer:rS,...$});var nx=($={})=>{let O=ix(jj(),$),j=()=>({...O}),x=(Q)=>{return O=ix(O,Q),j()},S=D2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:cj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await R2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=ax(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:px(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?T2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return N2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:px(I),url:z})};return{buildUrl:(Q)=>ax({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var _2=nx(jj());class M2{client;constructor($){this.client=$?.client??_2}}class A2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class dj extends M2{static __registry=new A2;constructor($){super($);dj.__registry.set(this,$?.key)}deleteAgentApiKey($){return($.client??this.client).delete({url:"/agents/{agent_id}/api-key",...$})}getAgentApiKey($){return($.client??this.client).get({url:"/agents/{agent_id}/api-key",...$})}putAgentApiKey($){return($.client??this.client).put({url:"/agents/{agent_id}/api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}purchaseAiCredits($){return($.client??this.client).post({url:"/ai-billing/credits/purchase",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}setGithubPullRequestState($){return($.client??this.client).post({url:"/github_pull_requests/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}listGtmInviteLinks($){return($?.client??this.client).get({url:"/gtm-invite/links",...$})}createGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/links",...$,headers:{"Content-Type":"application/json",...$.headers}})}revokeGtmInviteLink($){return($.client??this.client).delete({url:"/gtm-invite/links/{id}",...$})}getGtmInviteOffer($){return($?.client??this.client).get({url:"/gtm-invite/offer",...$})}resolveGtmInviteLink($){return($.client??this.client).get({url:"/gtm-invite/public/{token}",...$})}redeemGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/redeem",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}macroApiToken($){return($.client??this.client).get({url:"/jwt/macro_api_token",...$})}refresh($){return($?.client??this.client).post({url:"/jwt/refresh",...$})}createInProgressLink($){return($?.client??this.client).post({url:"/link",...$})}emailConnectionProviders($){return($?.client??this.client).get({url:"/link/email/providers",...$})}deleteGithubLink($){return($?.client??this.client).delete({url:"/link/github",...$})}initGithubLink($){return($.client??this.client).post({url:"/link/github",...$})}checkGithubLinkStatus($){return($?.client??this.client).get({url:"/link/github/status",...$})}initGmailLink($){return($.client??this.client).post({url:"/link/gmail",...$})}checkGmailLinkStatus($){return($?.client??this.client).get({url:"/link/gmail/status",...$})}initOutlookLink($){return($?.client??this.client).post({url:"/link/outlook",...$})}appleLogin($){return($.client??this.client).post({url:"/login/apple",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordLogin($){return($.client??this.client).post({url:"/login/password",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessLogin($){return($.client??this.client).post({url:"/login/passwordless",...$,headers:{"Content-Type":"application/json",...$.headers}})}ssoLogin($){return($.client??this.client).get({url:"/login/sso",...$})}logout($){return($?.client??this.client).post({url:"/logout",...$})}createMergeRequest($){return($.client??this.client).post({url:"/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyMergeRequest($){return($.client??this.client).get({url:"/merge/verify/{code}",...$})}sendMobileWelcomeEmail($){return($.client??this.client).post({url:"/mobile-welcome-email",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessCallback($){return($.client??this.client).get({url:"/oauth/passwordless/{code}",...$})}oauthRedirect($){return($?.client??this.client).get({url:"/oauth/redirect",...$})}oauth2Callback($){return($.client??this.client).get({url:"/oauth2/{provider}/callback",...$})}getPermissions($){return($?.client??this.client).get({url:"/permissions",...$})}getUserPermissions($){return($?.client??this.client).get({url:"/permissions/me",...$})}getReferralCode($){return($?.client??this.client).get({url:"/referral/code",...$})}sendReferralCode($){return($.client??this.client).post({url:"/referral/send",...$,headers:{"Content-Type":"application/json",...$.headers}})}sessionCreation($){return($?.client??this.client).post({url:"/session",...$})}sessionLogin($){return($.client??this.client).get({url:"/session/login/{session_code}",...$})}getSystemStatus($){return($?.client??this.client).get({url:"/system-status",...$})}setSystemStatus($){return($.client??this.client).post({url:"/system-status",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSystemStatusHistory($){return($?.client??this.client).get({url:"/system-status/history",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteLink($){return($?.client??this.client).delete({url:"/team/invite-link",...$})}getTeamInviteLink($){return($?.client??this.client).get({url:"/team/invite-link",...$})}createTeamInviteLink($){return($?.client??this.client).post({url:"/team/invite-link",...$})}joinTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/join",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserLanguage($){return($?.client??this.client).get({url:"/user/language",...$})}putUserLanguage($){return($.client??this.client).put({url:"/user/language",...$,headers:{"Content-Type":"application/json",...$.headers}})}getLegacyUserPermissions($){return($?.client??this.client).get({url:"/user/legacy_user_permissions",...$})}getUserLinkExists($){return($.client??this.client).get({url:"/user/link_exists",...$})}deleteUser($){return($?.client??this.client).delete({url:"/user/me",...$})}getUserInfo($){return($?.client??this.client).get({url:"/user/me",...$})}getUserName($){return($?.client??this.client).get({url:"/user/name",...$})}putUserName($){return($?.client??this.client).put({url:"/user/name",...$})}patchUserOnboarding($){return($.client??this.client).patch({url:"/user/onboarding",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserOrganization($){return($?.client??this.client).get({url:"/user/organization",...$})}putProfilePicture($){return($.client??this.client).put({url:"/user/profile_picture",...$})}postProfilePictures($){return($.client??this.client).post({url:"/user/profile_pictures",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserQuota($){return($?.client??this.client).get({url:"/user/quota",...$})}createCheckoutSessionV2($){return($.client??this.client).post({url:"/user/stripe/checkoutv2",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSubscriptionStatus($){return($?.client??this.client).get({url:"/user/stripe/plan",...$})}changePlan($){return($.client??this.client).post({url:"/user/stripe/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPortalSession($){return($.client??this.client).post({url:"/user/stripe/portal",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTrialEligibility($){return($?.client??this.client).get({url:"/user/stripe/trial_eligibility",...$})}patchUserTutorial($){return($.client??this.client).patch({url:"/user/tutorial",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function P2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,``);let y=U.split(``);U=y.pop()??"";for(let a of y){let i=a.split(`diff --git a/crates/macro_db_client/migrations/20261026222654_ai_billing_smaller_auto_reload_defaults.sql b/crates/macro_db_client/migrations/20261026222654_ai_billing_smaller_auto_reload_defaults.sqlnew file mode 100644index 0000000000..7de24c776e--- /dev/null+++ b/crates/macro_db_client/migrations/20261026222654_ai_billing_smaller_auto_reload_defaults.sql@@ -0,0 +1,9 @@+-- Automatic reload starts smaller: reload below $5 back up to $25. Matches+-- AUTO_RELOAD_DEFAULT_MINIMUM_CENTS and AUTO_RELOAD_DEFAULT_TARGET_CENTS.+-- Existing rows keep their values; clients start an off Auto-Reload from the+-- plan catalog's defaults, and enabling always saves explicit thresholds.+SET LOCAL lock_timeout = '5s';++ALTER TABLE ai_billing_account+ ALTER COLUMN auto_reload_minimum_cents SET DEFAULT 500,+ ALTER COLUMN auto_reload_target_cents SET DEFAULT 2500;diff --git a/crates/macro_db_client/migrations/20261027151946_ai_credit_reload_purchases.sql b/crates/macro_db_client/migrations/20261027151946_ai_credit_reload_purchases.sqlnew file mode 100644index 0000000000..aa3bc4acd0--- /dev/null+++ b/crates/macro_db_client/migrations/20261027151946_ai_credit_reload_purchases.sql@@ -0,0 +1,12 @@+-- Card-on-file credit charges share ai_credit_reload: automatic reloads and+-- one-time purchases both count against the payer's monthly credit limit.+-- `kind` separates them so a failed purchase never pauses automatic reloads+-- and automatic retries never pick up a purchase. `purchased_by` records which+-- team member asked for a purchase; it is NULL for automatic reloads.+SET LOCAL lock_timeout = '5s';++CREATE TYPE ai_credit_reload_kind AS ENUM ('automatic', 'purchase');++ALTER TABLE ai_credit_reload+ ADD COLUMN kind ai_credit_reload_kind NOT NULL DEFAULT 'automatic',+ ADD COLUMN purchased_by TEXT;diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.mdindex fd3b941c8c..1fde4fc132 100644--- a/docs/agent-guide/ai-chat.md+++ b/docs/agent-guide/ai-chat.md@@ -909,8 +909,32 @@ for Premium, `AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS`, andused up and no credits or usage billing cover the request, sending a messageanswers HTTP 402 and the app opens the **AI usage limit** dialog (title`You've used this month's included AI`, or the spending-limit / failed-charge-variants). It shows **Monthly limit**, the message `Add additional credits to-keep going.`, and an `Open usage settings` button. Credit purchases live in+variants). It says when the included AI resets. When the viewer is the payer+on a paid plan, it offers **One-time** and, while Auto-Reload is off or+suspended, **Auto-reload**:++- **One-time** picks a credit pack ($25 / $50 / $100 from the plan catalog) and+ **Buy $25 in credits** charges the card on file right away, closing with an+ `Added $25 in credits. Resend your message.` toast. Team members see it too:+ it charges the team owner's card, shows **Team monthly limit** (`$X of $Y+ left`), and disables packs over what is left. A declined card shows inline;+ the payer gets **Add payment method**, a member is told to ask the owner.+ With no card on file (for example, removed in the billing portal), or a card+ that needs 3-D Secure, nothing is charged: the payer is sent to Stripe+ Checkout for the same pack and returns to the same page (Settings → Usage on+ the web origin from the native app, which opens Stripe in the system+ browser). A member is asked to have the owner add or update the card.+- **Auto-reload** shows the reload (`$25 when below $5`), an editable+ **Monthly limit** prefilled with the plan default ($200 Pro, $1,000 Max; blank+ means no limit), and **Turn on auto-reload**, which enables it in one click.+ Enabling reloads right away when the balance is low; on success the dialog+ closes with an `Auto-reload is on` toast and the user resends. If the card on+ file can't be charged, the button becomes **Add payment method** (Stripe+ billing portal, returning to Settings → Usage).++The primary action uses the black-and-white `primary` Button; **Usage settings** and+**Dismiss** are ghost buttons. Team members who don't pay see `Open usage+settings` only when they cannot buy (no paid, metered plan). Credit purchases and Auto-Reload thresholds also live inSettings → Usage; subscription changes live in Settings → Billing.The free plan is a hard cap: when its monthly allowance is used up, requestsdiff --git a/docs/agent-guide/settings.md b/docs/agent-guide/settings.mdindex de7e1c7e2a..5d3cb49c27 100644--- a/docs/agent-guide/settings.md+++ b/docs/agent-guide/settings.md@@ -411,12 +411,19 @@ the flag off. The production usage-limit dialog follows the same flag. Its**Monthly limit** meter displays a percentage using the backend's current-periodusage and allowance. The info button explains AI agent chat and AI documentediting. **Usage Credits** shows the dollar balance and `Add more`, which opens-**Need more usage?** with `$25` / `$50` / `$100` / `Other`. Supported amounts-redirect to Stripe Checkout; unsupported custom amounts are disabled. Free-accounts see `View plans` instead of purchase or reload controls; paid team-members who are not the payer see only “Usage credits are managed by your team.”-Their credit balance and automatic reload row are hidden, with no-credit-purchase action.+**Need more usage?** with `$25` / `$50` / `$100` / `Other`. **Buy $25 in+credits** charges the card on file right away (no Stripe Checkout redirect),+shows an `Added $25 in credits.` toast, and reports a declined card inline;+unsupported custom amounts are disabled. Without a card on file, or with a card+that needs 3-D Secure, the payer is sent to Stripe Checkout for the same pack+instead, and a team member is asked to have the owner add or update the card. Free accounts see `View plans` instead+of purchase or reload controls. Paid team members who are not the payer see the+shared balance with `Add more`, described as “Shared team balance. You can add+$X more this month, within your team's $Y limit.” Their purchases charge the+team owner's card and are capped by the team's monthly credit limit: the owner's+Auto-Reload monthly limit, or the plan default ($200 Pro, $1,000 Max) when the+owner set none. Packs over what is left are refused, and `Add more` is disabled+once no pack fits. Members never see the automatic reload row.Team owners who pay for their team's seats manage the shared credit balance andautomatic reload here in Usage, including purchases, balance thresholds, themonthly reload cap, and payment methods. Team payers see **Team Usage@@ -431,8 +438,9 @@ or automatic reload. The development paid-plan preview can still displaythose controls, with purchases disabled.The **Automatic reload** switch opens **Auto-Reload** without toggling directly.-It contains Minimum balance (default `$10`), Target balance (default `$100`),-optional Maximum monthly spend (`No limit`), a payment-method management link,+It contains Minimum balance (default `$5`), Target balance (default `$25`),+optional Maximum monthly spend (prefilled `$200` on Pro and `$1,000` on Max while+Auto-Reload is off; blank means no limit), a payment-method management link,and the automatic-charge warning. The dialog saves for paid payers:`Turn on auto-reload` enables automatic credit purchases with those thresholds,`Save` updates them while on, and `Turn off` disables automatic reload. The monthlydiff --git a/docs/runbooks/ai-quota-enforcement.md b/docs/runbooks/ai-quota-enforcement.mdindex 47565d0285..a3c7ff6b13 100644--- a/docs/runbooks/ai-quota-enforcement.md+++ b/docs/runbooks/ai-quota-enforcement.md@@ -165,10 +165,44 @@ automatic reload is enabled and not reload-suspended, settlement compares thecredit balance net of the period'suncovered usage with the payer's minimum balance and, below it, reloads up to thetarget balance. The minimum, target, and optional monthly spend limit are stored-per payer on `ai_billing_account` (defaults `$10`, `$100`, and no limit). The-monthly limit counts reloads Stripe may still collect (pending, paid, or failed-with an invoice) within the UTC calendar month, independent of the Stripe period-anchor; a remainder under the Stripe minimum charge is skipped. Each reload is one `ai_credit_reload` row reserved under the+per payer on `ai_billing_account` (column defaults `$5`, `$25`, and no limit).+Clients start an off Auto-Reload from the plan catalog: `auto_reload_defaults`+and each plan's `auto_reload_default_monthly_limit_cents` ($200 Pro, $1,000 Max). The+monthly limit is the team's monthly credit limit: it counts automatic reloads and+one-time card purchases Stripe may still collect (pending, paid, or failed with+an invoice) within the UTC calendar month, independent of the Stripe period+anchor; a remainder under the Stripe minimum charge is skipped.++One-time purchases (`POST /ai-billing/credits/purchase`, packs $25 / $50 / $100)+charge the payer's card on file through the same invoice path and are+`ai_credit_reload` rows with `kind = 'purchase'` and `purchased_by` set to the+buyer. Any paid, metered seat may buy. The payer's purchases are capped by their+monthly limit when set; a team member's always are, falling back to the plan+default when the owner set none. A declined purchase is marked failed with its+invoice kept open; buying the same pack again pays that invoice instead of+charging twice, while picking a different pack voids it first so the buyer is+never charged an amount they did not choose. A retried invoice found void or+uncollectible in Stripe is retired the same way and a fresh purchase reserved.+Purchases never suspend automatic reloads. Provider and storage errors are+returned as errors (the app asks the buyer to try again), never reported as a+declined card; the row keeps any invoice it opened, so the next attempt retries+it. If the collector dies after Stripe finalized an invoice but before the row+recorded it, the `invoice.paid` webhook matches the row by the+`macro_reload_id` stamped on the invoice and books the credits; such a stale+pending purchase stops counting toward the monthly limit after 10 minutes.+Purchase credits are labelled `Credit purchase` in `ai_credit_ledger`. Automatic reloads and the settlement sweep+only consider `kind = 'automatic'` rows. Before reserving, a purchase checks+that Stripe has a card to charge (the subscription's or customer's default+payment method, or a legacy default source); without one it reserves nothing+and returns `payment_method_required`, and the app sends the payer to the Stripe+Checkout credit endpoint (`/ai-billing/credits/checkout`) for the same pack. A+card that needs 3-D Secure can't be charged off-session: the purchase's invoice+is voided and it returns `authentication_required`, with the same checkout+fallback. Before either fallback, open invoices from declined purchases are+voided (rows become `failed` with no invoice), so a card added later can't+collect them on top of the checkout payment; one Stripe collected first is+booked instead. Checkout purchases are booked by the webhook and are not+counted against the monthly limit. Each reload is one `ai_credit_reload` row reserved under thepayer lock and collected as a one-off Stripe invoice stamped`macro_purpose = ai_credit_reload`; a paid invoice books an `ai_credit_ledger`purchase, idempotent on the invoice id. A declined invoice stays pending, whichdiff --git a/packages/sdk-docs/reference/generated/auth/types.gen/README.md b/packages/sdk-docs/reference/generated/auth/types.gen/README.mdindex fb191f0860..89c54d5e64 100644--- a/packages/sdk-docs/reference/generated/auth/types.gen/README.md+++ b/packages/sdk-docs/reference/generated/auth/types.gen/README.md@@ -97,6 +97,10 @@- [CreateTeamResponses](type-aliases/CreateTeamResponses.md)- [CreditCheckoutRequestBody](type-aliases/CreditCheckoutRequestBody.md)- [CreditCheckoutResponse](type-aliases/CreditCheckoutResponse.md)+- [CreditPurchaseRequestBody](type-aliases/CreditPurchaseRequestBody.md)+- [CreditPurchaseResponse](type-aliases/CreditPurchaseResponse.md)+- [CreditPurchaseSnapshot](type-aliases/CreditPurchaseSnapshot.md)+- [CreditPurchaseStatus](type-aliases/CreditPurchaseStatus.md)- [CurrentSystemStatus](type-aliases/CurrentSystemStatus.md)- [CursorApiKeyStatus](type-aliases/CursorApiKeyStatus.md)- [CursorModelOption](type-aliases/CursorModelOption.md)@@ -475,6 +479,11 @@- [ProfilePictureQueryParams](type-aliases/ProfilePictureQueryParams.md)- [ProfilePictures](type-aliases/ProfilePictures.md)- [PublicGtmInviteLink](type-aliases/PublicGtmInviteLink.md)+- [PurchaseAiCreditsData](type-aliases/PurchaseAiCreditsData.md)+- [PurchaseAiCreditsError](type-aliases/PurchaseAiCreditsError.md)+- [PurchaseAiCreditsErrors](type-aliases/PurchaseAiCreditsErrors.md)+- [PurchaseAiCreditsResponse](type-aliases/PurchaseAiCreditsResponse.md)+- [PurchaseAiCreditsResponses](type-aliases/PurchaseAiCreditsResponses.md)- [PutAgentApiKeyData](type-aliases/PutAgentApiKeyData.md)- [PutAgentApiKeyError](type-aliases/PutAgentApiKeyError.md)- [PutAgentApiKeyErrors](type-aliases/PutAgentApiKeyErrors.md)diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AutoReloadMonthlyBudget.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AutoReloadMonthlyBudget.mdindex 87e95532ab..a6af4e406b 100644--- a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AutoReloadMonthlyBudget.md+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/AutoReloadMonthlyBudget.md@@ -8,6 +8,6 @@ Calendar-month commitments that consume the payer's automatic reload cap.| Property | Type | Description || ------ | ------ | ------ |-| <a id="property-committed_cents"></a> `committed_cents` | `number` | Reloads paid, pending, or failed with an invoice that can still collect. Customer cents; manual credit purchases do not count. |+| <a id="property-committed_cents"></a> `committed_cents` | `number` | Reloads and one-time card purchases paid, pending, or failed with an invoice that can still collect. Customer cents; Checkout purchases do not count. || <a id="property-limit_reached"></a> `limit_reached` | `boolean` | Remaining cap cannot fund the minimum automatic reload charge. || <a id="property-resets_at"></a> `resets_at` | `string` | Start of the next UTC calendar month, independently of subscription renewal. |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreditPurchaseRequestBody.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreditPurchaseRequestBody.mdnew file mode 100644index 0000000000..3bb5abbf7c--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreditPurchaseRequestBody.md@@ -0,0 +1,11 @@+# Type Alias: CreditPurchaseRequestBody++> **CreditPurchaseRequestBody** = \{ `amountCents`: `number`; \}++Request body for [`purchase_credits_handler`].++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-amountcents"></a> `amountCents` | `number` | One of the catalog's credit packs, cents. |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreditPurchaseResponse.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreditPurchaseResponse.mdnew file mode 100644index 0000000000..3b6b6779a3--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreditPurchaseResponse.md@@ -0,0 +1,13 @@+# Type Alias: CreditPurchaseResponse++> **CreditPurchaseResponse** = \{ `amountCents`: `number`; `snapshot?`: `null` \| [`UsageSnapshot`](UsageSnapshot.md); `status`: [`CreditPurchaseStatus`](CreditPurchaseStatus.md); \}++Response for [`purchase_credits_handler`].++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-amountcents"></a> `amountCents` | `number` | Amount charged, cents: the requested pack, unless an earlier declined purchase that Stripe collected in the meantime was booked instead. |+| <a id="property-snapshot"></a> `snapshot?` | `null` \| [`UsageSnapshot`](UsageSnapshot.md) | - |+| <a id="property-status"></a> `status` | [`CreditPurchaseStatus`](CreditPurchaseStatus.md) | Whether the card on file paid. |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreditPurchaseSnapshot.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreditPurchaseSnapshot.mdnew file mode 100644index 0000000000..8a5d5cdef4--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreditPurchaseSnapshot.md@@ -0,0 +1,13 @@+# Type Alias: CreditPurchaseSnapshot++> **CreditPurchaseSnapshot** = \{ `committed_cents`: `number`; `monthly_limit_cents?`: `number` \| `null`; `resets_at`: `string`; \}++The monthly credit limit that applies to this user's one-time purchases.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-committed_cents"></a> `committed_cents` | `number` | Charged this month so far, including charges that may still collect. |+| <a id="property-monthly_limit_cents"></a> `monthly_limit_cents?` | `number` \| `null` | Most credits charged to the card on file per UTC calendar month, from automatic reloads and one-time purchases together, in customer cents. `null` when the payer set no limit; team members always have one. |+| <a id="property-resets_at"></a> `resets_at` | `string` | Start of the next UTC calendar month. |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreditPurchaseStatus.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreditPurchaseStatus.mdnew file mode 100644index 0000000000..b0c05f9a07--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/CreditPurchaseStatus.md@@ -0,0 +1,5 @@+# Type Alias: CreditPurchaseStatus++> **CreditPurchaseStatus** = `"paid"` \| `"declined"` \| `"payment_method_required"` \| `"authentication_required"`++How a one-time credit purchase charged to the card on file ended.diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PlanCatalogEntry.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PlanCatalogEntry.mdindex 6a0b886498..bbaf2a34b4 100644--- a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PlanCatalogEntry.md+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PlanCatalogEntry.md@@ -1,6 +1,6 @@# Type Alias: PlanCatalogEntry-> **PlanCatalogEntry** = \{ `included_ai_cents_per_seat`: `number`; `monthly_price_cents`: `number`; `purchasable`: `boolean`; `tier`: [`PlanTier`](PlanTier.md); \}+> **PlanCatalogEntry** = \{ `auto_reload_default_monthly_limit_cents?`: `number` \| `null`; `included_ai_cents_per_seat`: `number`; `monthly_price_cents`: `number`; `purchasable`: `boolean`; `tier`: [`PlanTier`](PlanTier.md); \}One plan in the catalog.@@ -8,6 +8,7 @@ One plan in the catalog.| Property | Type | Description || ------ | ------ | ------ |+| <a id="property-auto_reload_default_monthly_limit_cents"></a> `auto_reload_default_monthly_limit_cents?` | `number` \| `null` | Monthly automatic reload limit a payer on this plan starts from, cents. Absent for plans that cannot reload. || <a id="property-included_ai_cents_per_seat"></a> `included_ai_cents_per_seat` | `number` | Included AI per seat per period, in cents at provider cost. For the free plan this is its monthly hard cap. || <a id="property-monthly_price_cents"></a> `monthly_price_cents` | `number` | Monthly subscription price per seat, cents. || <a id="property-purchasable"></a> `purchasable` | `boolean` | Whether a new purchase or plan move may pick this plan today. |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PurchaseAiCreditsData.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PurchaseAiCreditsData.mdnew file mode 100644index 0000000000..769f8f3e45--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PurchaseAiCreditsData.md@@ -0,0 +1,12 @@+# Type Alias: PurchaseAiCreditsData++> **PurchaseAiCreditsData** = \{ `body`: [`CreditPurchaseRequestBody`](CreditPurchaseRequestBody.md); `path?`: `never`; `query?`: `never`; `url`: `"/ai-billing/credits/purchase"`; \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-body"></a> `body` | [`CreditPurchaseRequestBody`](CreditPurchaseRequestBody.md) |+| <a id="property-path"></a> `path?` | `never` |+| <a id="property-query"></a> `query?` | `never` |+| <a id="property-url"></a> `url` | `"/ai-billing/credits/purchase"` |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PurchaseAiCreditsError.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PurchaseAiCreditsError.mdnew file mode 100644index 0000000000..16649bb222--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PurchaseAiCreditsError.md@@ -0,0 +1,3 @@+# Type Alias: PurchaseAiCreditsError++> **PurchaseAiCreditsError** = [`PurchaseAiCreditsErrors`](PurchaseAiCreditsErrors.md)\[keyof [`PurchaseAiCreditsErrors`](PurchaseAiCreditsErrors.md)\]diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PurchaseAiCreditsErrors.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PurchaseAiCreditsErrors.mdnew file mode 100644index 0000000000..a54e62ab9a--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PurchaseAiCreditsErrors.md@@ -0,0 +1,13 @@+# Type Alias: PurchaseAiCreditsErrors++> **PurchaseAiCreditsErrors** = \{ `400`: [`AiBillingErrorBody`](AiBillingErrorBody.md); `401`: `unknown`; `402`: [`AiBillingErrorBody`](AiBillingErrorBody.md); `409`: [`AiBillingErrorBody`](AiBillingErrorBody.md); `500`: [`AiBillingErrorBody`](AiBillingErrorBody.md); \}++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-400"></a> `400` | [`AiBillingErrorBody`](AiBillingErrorBody.md) | Invalid pack or no payment account |+| <a id="property-401"></a> `401` | `unknown` | Unauthorized |+| <a id="property-402"></a> `402` | [`AiBillingErrorBody`](AiBillingErrorBody.md) | A paid plan is required |+| <a id="property-409"></a> `409` | [`AiBillingErrorBody`](AiBillingErrorBody.md) | Over the monthly credit limit, or an earlier purchase is still processing |+| <a id="property-500"></a> `500` | [`AiBillingErrorBody`](AiBillingErrorBody.md) | Internal server error |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PurchaseAiCreditsResponse.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PurchaseAiCreditsResponse.mdnew file mode 100644index 0000000000..ef08b5cce4--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PurchaseAiCreditsResponse.md@@ -0,0 +1,3 @@+# Type Alias: PurchaseAiCreditsResponse++> **PurchaseAiCreditsResponse** = [`PurchaseAiCreditsResponses`](PurchaseAiCreditsResponses.md)\[keyof [`PurchaseAiCreditsResponses`](PurchaseAiCreditsResponses.md)\]diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PurchaseAiCreditsResponses.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PurchaseAiCreditsResponses.mdnew file mode 100644index 0000000000..c8c59c4092--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/PurchaseAiCreditsResponses.md@@ -0,0 +1,9 @@+# Type Alias: PurchaseAiCreditsResponses++> **PurchaseAiCreditsResponses** = \{ `200`: [`CreditPurchaseResponse`](CreditPurchaseResponse.md); \}++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-200"></a> `200` | [`CreditPurchaseResponse`](CreditPurchaseResponse.md) | Purchase outcome and updated position |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/UsageSnapshot.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/UsageSnapshot.mdindex 157c4600ea..138d327652 100644--- a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/UsageSnapshot.md+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/UsageSnapshot.md@@ -1,6 +1,6 @@# Type Alias: UsageSnapshot-> **UsageSnapshot** = \{ `auto_reload`: [`AutoReloadSnapshot`](AutoReloadSnapshot.md); `blocked_reason?`: `null` \| [`DenyReason`](DenyReason.md); `can_manage_billing`: `boolean`; `credit_balance_cents`: `number`; `credits_consumed_cents`: `number`; `credits_shared_with_team`: `boolean`; `included_cents`: `number`; `overage_charged_cents`: `number`; `overage_enabled`: `boolean`; `overage_limit_cents`: `number`; `overage_suspended`: `boolean`; `payer`: `string`; `period_end`: `string`; `period_start`: `string`; `remaining_cents`: `number`; `seats`: `number`; `tier`: [`PlanTier`](PlanTier.md); `uncovered_cents`: `number`; `unlimited`: `boolean`; `used_cents`: `number`; \}+> **UsageSnapshot** = \{ `auto_reload`: [`AutoReloadSnapshot`](AutoReloadSnapshot.md); `blocked_reason?`: `null` \| [`DenyReason`](DenyReason.md); `can_manage_billing`: `boolean`; `credit_balance_cents`: `number`; `credit_purchase?`: `null` \| [`CreditPurchaseSnapshot`](CreditPurchaseSnapshot.md); `credits_consumed_cents`: `number`; `credits_shared_with_team`: `boolean`; `included_cents`: `number`; `overage_charged_cents`: `number`; `overage_enabled`: `boolean`; `overage_limit_cents`: `number`; `overage_suspended`: `boolean`; `payer`: `string`; `period_end`: `string`; `period_start`: `string`; `remaining_cents`: `number`; `seats`: `number`; `tier`: [`PlanTier`](PlanTier.md); `uncovered_cents`: `number`; `unlimited`: `boolean`; `used_cents`: `number`; \}The payer's current-period position, as shown in Billing settings and usedby the gate.@@ -13,6 +13,7 @@ by the gate.| <a id="property-blocked_reason"></a> `blocked_reason?` | `null` \| [`DenyReason`](DenyReason.md) | - || <a id="property-can_manage_billing"></a> `can_manage_billing` | `boolean` | Whether the requesting user is the payer. || <a id="property-credit_balance_cents"></a> `credit_balance_cents` | `number` | Shared prepaid credit balance, in customer cents. |+| <a id="property-credit_purchase"></a> `credit_purchase?` | `null` \| [`CreditPurchaseSnapshot`](CreditPurchaseSnapshot.md) | - || <a id="property-credits_consumed_cents"></a> `credits_consumed_cents` | `number` | Shared payer credits already applied to this period, in customer cents. || <a id="property-credits_shared_with_team"></a> `credits_shared_with_team` | `boolean` | Whether prepaid credits belong to the team, including a team with one seat. || <a id="property-included_cents"></a> `included_cents` | `number` | Included AI for this user's seat this period, in cents at provider cost. |diff --git a/packages/sdk/generated/auth/index.ts b/packages/sdk/generated/auth/index.tsindex 64e8569e49..a438890eb6 100644--- a/packages/sdk/generated/auth/index.ts+++ b/packages/sdk/generated/auth/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AbGroup, AgentApiKey, AgentApiKeyProvider, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, AutoReloadDefaults, AutoReloadMonthlyBudget, AutoReloadSnapshot, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, CheckoutSessionV2Response, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreatedTeamInviteLinkResponse, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkError, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponse, CreateTeamInviteLinkResponses, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CurrentSystemStatus, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteAgentApiKeyData, DeleteAgentApiKeyError, DeleteAgentApiKeyErrors, DeleteAgentApiKeyResponse, DeleteAgentApiKeyResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkError, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponse, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmailConnectionProviders, EmailConnectionProvidersData, EmailConnectionProvidersError, EmailConnectionProvidersErrors, EmailConnectionProvidersResponse, EmailConnectionProvidersResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAgentApiKeyData, GetAgentApiKeyError, GetAgentApiKeyErrors, GetAgentApiKeyResponse, GetAgentApiKeyResponses, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityError, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponse, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusError, GetSubscriptionStatusErrors, GetSubscriptionStatusResponse, GetSubscriptionStatusResponses, GetSystemStatusData, GetSystemStatusError, GetSystemStatusErrors, GetSystemStatusResponse, GetSystemStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkError, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponse, GetTeamByInviteLinkResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkError, GetTeamInviteLinkErrors, GetTeamInviteLinkResponse, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityError, GetTrialEligibilityErrors, GetTrialEligibilityResponse, GetTrialEligibilityResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLanguageData, GetUserLanguageError, GetUserLanguageErrors, GetUserLanguageResponse, GetUserLanguageResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubMergeMethod, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestLabel, GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry, GithubPullRequestMergeabilityRequest, GithubPullRequestMergeabilityResponse, GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestState, GithubPullRequestStatus, GithubPullRequestUser, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkError, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponse, JoinTeamByInviteLinkResponse2, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, Language, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, ListSystemStatusHistoryData, ListSystemStatusHistoryError, ListSystemStatusHistoryErrors, ListSystemStatusHistoryResponse, ListSystemStatusHistoryResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestError, MergeGithubPullRequestErrors, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse, MergeGithubPullRequestResponse2, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PublicGtmInviteLink, PutAgentApiKeyData, PutAgentApiKeyError, PutAgentApiKeyErrors, PutAgentApiKeyRequest, PutAgentApiKeyResponse, PutAgentApiKeyResponses, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserLanguageData, PutUserLanguageError, PutUserLanguageErrors, PutUserLanguageResponse, PutUserLanguageResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, SavedAgentApiKey, ScheduledSeatPlan, SeatPlan, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftError, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse, SetGithubPullRequestDraftResponse2, SetGithubPullRequestDraftResponses, SetGithubPullRequestStateData, SetGithubPullRequestStateError, SetGithubPullRequestStateErrors, SetGithubPullRequestStateRequest, SetGithubPullRequestStateResponse, SetGithubPullRequestStateResponse2, SetGithubPullRequestStateResponses, SetSystemStatusData, SetSystemStatusError, SetSystemStatusErrors, SetSystemStatusResponse, SetSystemStatusResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StatusUpdate, StripeSessionResponse, SubscriptionStatus, SystemStatus, SystemStatusHistory, Team, TeamInviteDetails, TeamInviteLinkResponse, TeamInviteLinkTeam, TeamInviteLinkToken, TeamInviteLinkTokenRequest, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, TrialEligibility, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadError, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponse, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateAutoReloadRequest, UpdateOverageRequest, UpstreamErrorCode, UpstreamErrorResponse, UsageSnapshot, UserLanguage, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';+export type { AbGroup, AgentApiKey, AgentApiKeyProvider, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, AutoReloadDefaults, AutoReloadMonthlyBudget, AutoReloadSnapshot, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, CheckoutSessionV2Response, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreatedTeamInviteLinkResponse, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkError, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponse, CreateTeamInviteLinkResponses, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CreditPurchaseRequestBody, CreditPurchaseResponse, CreditPurchaseSnapshot, CreditPurchaseStatus, CurrentSystemStatus, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteAgentApiKeyData, DeleteAgentApiKeyError, DeleteAgentApiKeyErrors, DeleteAgentApiKeyResponse, DeleteAgentApiKeyResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkError, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponse, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmailConnectionProviders, EmailConnectionProvidersData, EmailConnectionProvidersError, EmailConnectionProvidersErrors, EmailConnectionProvidersResponse, EmailConnectionProvidersResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAgentApiKeyData, GetAgentApiKeyError, GetAgentApiKeyErrors, GetAgentApiKeyResponse, GetAgentApiKeyResponses, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityError, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponse, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusError, GetSubscriptionStatusErrors, GetSubscriptionStatusResponse, GetSubscriptionStatusResponses, GetSystemStatusData, GetSystemStatusError, GetSystemStatusErrors, GetSystemStatusResponse, GetSystemStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkError, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponse, GetTeamByInviteLinkResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkError, GetTeamInviteLinkErrors, GetTeamInviteLinkResponse, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityError, GetTrialEligibilityErrors, GetTrialEligibilityResponse, GetTrialEligibilityResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLanguageData, GetUserLanguageError, GetUserLanguageErrors, GetUserLanguageResponse, GetUserLanguageResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubMergeMethod, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestLabel, GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry, GithubPullRequestMergeabilityRequest, GithubPullRequestMergeabilityResponse, GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestState, GithubPullRequestStatus, GithubPullRequestUser, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkError, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponse, JoinTeamByInviteLinkResponse2, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, Language, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, ListSystemStatusHistoryData, ListSystemStatusHistoryError, ListSystemStatusHistoryErrors, ListSystemStatusHistoryResponse, ListSystemStatusHistoryResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestError, MergeGithubPullRequestErrors, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse, MergeGithubPullRequestResponse2, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PublicGtmInviteLink, PurchaseAiCreditsData, PurchaseAiCreditsError, PurchaseAiCreditsErrors, PurchaseAiCreditsResponse, PurchaseAiCreditsResponses, PutAgentApiKeyData, PutAgentApiKeyError, PutAgentApiKeyErrors, PutAgentApiKeyRequest, PutAgentApiKeyResponse, PutAgentApiKeyResponses, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserLanguageData, PutUserLanguageError, PutUserLanguageErrors, PutUserLanguageResponse, PutUserLanguageResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, SavedAgentApiKey, ScheduledSeatPlan, SeatPlan, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftError, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse, SetGithubPullRequestDraftResponse2, SetGithubPullRequestDraftResponses, SetGithubPullRequestStateData, SetGithubPullRequestStateError, SetGithubPullRequestStateErrors, SetGithubPullRequestStateRequest, SetGithubPullRequestStateResponse, SetGithubPullRequestStateResponse2, SetGithubPullRequestStateResponses, SetSystemStatusData, SetSystemStatusError, SetSystemStatusErrors, SetSystemStatusResponse, SetSystemStatusResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StatusUpdate, StripeSessionResponse, SubscriptionStatus, SystemStatus, SystemStatusHistory, Team, TeamInviteDetails, TeamInviteLinkResponse, TeamInviteLinkTeam, TeamInviteLinkToken, TeamInviteLinkTokenRequest, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, TrialEligibility, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadError, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponse, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateAutoReloadRequest, UpdateOverageRequest, UpstreamErrorCode, UpstreamErrorResponse, UsageSnapshot, UserLanguage, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';diff --git a/packages/sdk/generated/auth/sdk.gen.ts b/packages/sdk/generated/auth/sdk.gen.tsindex 97a53a8adc..0b3314dd01 100644--- a/packages/sdk/generated/auth/sdk.gen.ts+++ b/packages/sdk/generated/auth/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponses, ChangePlanData, ChangePlanErrors, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateAiCreditCheckoutData, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkErrors, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponses, CreateTeamResponses, DeleteAgentApiKeyData, DeleteAgentApiKeyErrors, DeleteAgentApiKeyResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EmailConnectionProvidersData, EmailConnectionProvidersErrors, EmailConnectionProvidersResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetAgentApiKeyData, GetAgentApiKeyErrors, GetAgentApiKeyResponses, GetAiBillingPlansData, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryErrors, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferErrors, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusErrors, GetSubscriptionStatusResponses, GetSystemStatusData, GetSystemStatusErrors, GetSystemStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponses, GetTeamData, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkErrors, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityErrors, GetTrialEligibilityResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLanguageData, GetUserLanguageErrors, GetUserLanguageResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCodexEnvironmentsData, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksErrors, ListGtmInviteLinksResponses, ListSystemStatusHistoryData, ListSystemStatusHistoryErrors, ListSystemStatusHistoryResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestErrors, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanErrors, PatchTeamMemberPlanResponses, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PollCodexLoginData, PollCodexLoginResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PutAgentApiKeyData, PutAgentApiKeyErrors, PutAgentApiKeyResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserLanguageData, PutUserLanguageErrors, PutUserLanguageResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftResponses, SetGithubPullRequestStateData, SetGithubPullRequestStateErrors, SetGithubPullRequestStateResponses, SetSystemStatusData, SetSystemStatusErrors, SetSystemStatusResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, StartCodexLoginData, StartCodexLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';+import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponses, ChangePlanData, ChangePlanErrors, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateAiCreditCheckoutData, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkErrors, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponses, CreateTeamResponses, DeleteAgentApiKeyData, DeleteAgentApiKeyErrors, DeleteAgentApiKeyResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EmailConnectionProvidersData, EmailConnectionProvidersErrors, EmailConnectionProvidersResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetAgentApiKeyData, GetAgentApiKeyErrors, GetAgentApiKeyResponses, GetAiBillingPlansData, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryErrors, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferErrors, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusErrors, GetSubscriptionStatusResponses, GetSystemStatusData, GetSystemStatusErrors, GetSystemStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponses, GetTeamData, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkErrors, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityErrors, GetTrialEligibilityResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLanguageData, GetUserLanguageErrors, GetUserLanguageResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCodexEnvironmentsData, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksErrors, ListGtmInviteLinksResponses, ListSystemStatusHistoryData, ListSystemStatusHistoryErrors, ListSystemStatusHistoryResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestErrors, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanErrors, PatchTeamMemberPlanResponses, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PollCodexLoginData, PollCodexLoginResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PurchaseAiCreditsData, PurchaseAiCreditsErrors, PurchaseAiCreditsResponses, PutAgentApiKeyData, PutAgentApiKeyErrors, PutAgentApiKeyResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserLanguageData, PutUserLanguageErrors, PutUserLanguageResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftResponses, SetGithubPullRequestStateData, SetGithubPullRequestStateErrors, SetGithubPullRequestStateResponses, SetSystemStatusData, SetSystemStatusErrors, SetSystemStatusResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, StartCodexLoginData, StartCodexLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -117,6 +117,21 @@ export class Sdk extends HeyApiClient {});}+ /**+ * Buy a credit pack now, charged to the payer's card on file. Any paid team+ * member may buy, within the team's monthly credit limit.+ */+ public purchaseAiCredits<ThrowOnError extends boolean = false>(options: Options<PurchaseAiCreditsData, ThrowOnError>): RequestResult<PurchaseAiCreditsResponses, PurchaseAiCreditsErrors, ThrowOnError> {+ return (options.client ?? this.client).post<PurchaseAiCreditsResponses, PurchaseAiCreditsErrors, ThrowOnError>({+ url: '/ai-billing/credits/purchase',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }+/*** Retired direct-usage opt-in. Enabling is rejected; disabling remains supported.*/diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.tsindex 982d042e20..0f7935721b 100644--- a/packages/sdk/generated/auth/types.gen.ts+++ b/packages/sdk/generated/auth/types.gen.ts@@ -57,8 +57,9 @@ export type AutoReloadDefaults = {*/export type AutoReloadMonthlyBudget = {/**- * Reloads paid, pending, or failed with an invoice that can still collect.- * Customer cents; manual credit purchases do not count.+ * Reloads and one-time card purchases paid, pending, or failed with an+ * invoice that can still collect. Customer cents; Checkout purchases do+ * not count.*/committed_cents: number;/**@@ -378,6 +379,57 @@ export type CreditCheckoutResponse = {url: string;};+/**+ * Request body for [`purchase_credits_handler`].+ */+export type CreditPurchaseRequestBody = {+ /**+ * One of the catalog's credit packs, cents.+ */+ amountCents: number;+};++/**+ * Response for [`purchase_credits_handler`].+ */+export type CreditPurchaseResponse = {+ /**+ * Amount charged, cents: the requested pack, unless an earlier declined+ * purchase that Stripe collected in the meantime was booked instead.+ */+ amountCents: number;+ snapshot?: null | UsageSnapshot;+ /**+ * Whether the card on file paid.+ */+ status: CreditPurchaseStatus;+};++/**+ * The monthly credit limit that applies to this user's one-time purchases.+ */+export type CreditPurchaseSnapshot = {+ /**+ * Charged this month so far, including charges that may still collect.+ */+ committed_cents: number;+ /**+ * Most credits charged to the card on file per UTC calendar month, from+ * automatic reloads and one-time purchases together, in customer cents.+ * `null` when the payer set no limit; team members always have one.+ */+ monthly_limit_cents?: number | null;+ /**+ * Start of the next UTC calendar month.+ */+ resets_at: string;+};++/**+ * How a one-time credit purchase charged to the card on file ended.+ */+export type CreditPurchaseStatus = 'paid' | 'declined' | 'payment_method_required' | 'authentication_required';+/*** The status every user sees, without who set it.*/@@ -1384,6 +1436,11 @@ export type Permission = {* One plan in the catalog.*/export type PlanCatalogEntry = {+ /**+ * Monthly automatic reload limit a payer on this plan starts from,+ * cents. Absent for plans that cannot reload.+ */+ auto_reload_default_monthly_limit_cents?: number | null;/*** Included AI per seat per period, in cents at provider cost. For the* free plan this is its monthly hard cap.@@ -2015,6 +2072,7 @@ export type UsageSnapshot = {* Shared prepaid credit balance, in customer cents.*/credit_balance_cents: number;+ credit_purchase?: null | CreditPurchaseSnapshot;/*** Shared payer credits already applied to this period, in customer cents.*/@@ -2312,6 +2370,47 @@ export type CreateAiCreditCheckoutResponses = {export type CreateAiCreditCheckoutResponse = CreateAiCreditCheckoutResponses[keyof CreateAiCreditCheckoutResponses];+export type PurchaseAiCreditsData = {+ body: CreditPurchaseRequestBody;+ path?: never;+ query?: never;+ url: '/ai-billing/credits/purchase';+};++export type PurchaseAiCreditsErrors = {+ /**+ * Invalid pack or no payment account+ */+ 400: AiBillingErrorBody;+ /**+ * Unauthorized+ */+ 401: unknown;+ /**+ * A paid plan is required+ */+ 402: AiBillingErrorBody;+ /**+ * Over the monthly credit limit, or an earlier purchase is still processing+ */+ 409: AiBillingErrorBody;+ /**+ * Internal server error+ */+ 500: AiBillingErrorBody;+};++export type PurchaseAiCreditsError = PurchaseAiCreditsErrors[keyof PurchaseAiCreditsErrors];++export type PurchaseAiCreditsResponses = {+ /**+ * Purchase outcome and updated position+ */+ 200: CreditPurchaseResponse;+};++export type PurchaseAiCreditsResponse = PurchaseAiCreditsResponses[keyof PurchaseAiCreditsResponses];+export type UpdateAiBillingOverageData = {body: UpdateOverageRequest;path?: never;diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.jsonindex 125a6f72f1..77d4bd111d 100644--- a/packages/sdk/specs/auth.json+++ b/packages/sdk/specs/auth.json@@ -347,6 +347,78 @@}}},+ "/ai-billing/credits/purchase": {+ "post": {+ "tags": ["ai_billing"],+ "summary": "Buy a credit pack now, charged to the payer's card on file. Any paid team\nmember may buy, within the team's monthly credit limit.",+ "operationId": "purchase_ai_credits",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreditPurchaseRequestBody"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Purchase outcome and updated position",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreditPurchaseResponse"+ }+ }+ }+ },+ "400": {+ "description": "Invalid pack or no payment account",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AiBillingErrorBody"+ }+ }+ }+ },+ "401": {+ "description": "Unauthorized"+ },+ "402": {+ "description": "A paid plan is required",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AiBillingErrorBody"+ }+ }+ }+ },+ "409": {+ "description": "Over the monthly credit limit, or an earlier purchase is still processing",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AiBillingErrorBody"+ }+ }+ }+ },+ "500": {+ "description": "Internal server error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AiBillingErrorBody"+ }+ }+ }+ }+ }+ }+ },"/ai-billing/overage": {"patch": {"tags": ["ai_billing"],@@ -6217,7 +6289,7 @@"committed_cents": {"type": "integer","format": "int64",- "description": "Reloads paid, pending, or failed with an invoice that can still collect.\nCustomer cents; manual credit purchases do not count."+ "description": "Reloads and one-time card purchases paid, pending, or failed with an\ninvoice that can still collect. Customer cents; Checkout purchases do\nnot count."},"limit_reached": {"type": "boolean",@@ -6603,6 +6675,77 @@}}},+ "CreditPurchaseRequestBody": {+ "type": "object",+ "description": "Request body for [`purchase_credits_handler`].",+ "required": ["amountCents"],+ "properties": {+ "amountCents": {+ "type": "integer",+ "format": "int64",+ "description": "One of the catalog's credit packs, cents."+ }+ }+ },+ "CreditPurchaseResponse": {+ "type": "object",+ "description": "Response for [`purchase_credits_handler`].",+ "required": ["status", "amountCents"],+ "properties": {+ "amountCents": {+ "type": "integer",+ "format": "int64",+ "description": "Amount charged, cents: the requested pack, unless an earlier declined\npurchase that Stripe collected in the meantime was booked instead."+ },+ "snapshot": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/UsageSnapshot",+ "description": "The caller's position after the purchase. Absent when it could not be\nread; the purchase still happened, so refetch the summary instead."+ }+ ]+ },+ "status": {+ "$ref": "#/components/schemas/CreditPurchaseStatus",+ "description": "Whether the card on file paid."+ }+ }+ },+ "CreditPurchaseSnapshot": {+ "type": "object",+ "description": "The monthly credit limit that applies to this user's one-time purchases.",+ "required": ["committed_cents", "resets_at"],+ "properties": {+ "committed_cents": {+ "type": "integer",+ "format": "int64",+ "description": "Charged this month so far, including charges that may still collect."+ },+ "monthly_limit_cents": {+ "type": ["integer", "null"],+ "format": "int64",+ "description": "Most credits charged to the card on file per UTC calendar month, from\nautomatic reloads and one-time purchases together, in customer cents.\n`null` when the payer set no limit; team members always have one."+ },+ "resets_at": {+ "type": "string",+ "format": "date-time",+ "description": "Start of the next UTC calendar month."+ }+ }+ },+ "CreditPurchaseStatus": {+ "type": "string",+ "description": "How a one-time credit purchase charged to the card on file ended.",+ "enum": [+ "paid",+ "declined",+ "payment_method_required",+ "authentication_required"+ ]+ },"CurrentSystemStatus": {"allOf": [{@@ -7932,6 +8075,11 @@"purchasable"],"properties": {+ "auto_reload_default_monthly_limit_cents": {+ "type": ["integer", "null"],+ "format": "int64",+ "description": "Monthly automatic reload limit a payer on this plan starts from,\ncents. Absent for plans that cannot reload."+ },"included_ai_cents_per_seat": {"type": "integer","format": "int64",@@ -8807,6 +8955,17 @@"format": "int64","description": "Shared prepaid credit balance, in customer cents."},+ "credit_purchase": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/CreditPurchaseSnapshot",+ "description": "The monthly credit limit for one-time purchases charged to the card on\nfile. Present for paid, metered users, payer and team members alike."+ }+ ]+ },"credits_consumed_cents": {"type": "integer","format": "int64",diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex 1bb58a6a73..630ceb1a69 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -120,6 +120,7 @@ export const authExcluded = ['patchUserTutorial','pollCodexLogin','postProfilePictures',+ 'purchaseAiCredits','putAgentApiKey','putCursorApiKey','putCursorDefaultModel',diff --git a/services/authentication_service/src/api/swagger.rs b/services/authentication_service/src/api/swagger.rsindex 732a503414..557c09707b 100644--- a/services/authentication_service/src/api/swagger.rs+++ b/services/authentication_service/src/api/swagger.rs@@ -169,6 +169,7 @@ use model::user::{ai_billing::inbound::axum_router::update_overage_handler::<crate::api::context::AiBillingServiceType, crate::api::context::AuthorizationService>,ai_billing::inbound::axum_router::update_auto_reload_handler::<crate::api::context::AiBillingServiceType, crate::api::context::AuthorizationService>,ai_billing::inbound::axum_router::create_credit_checkout_handler::<crate::api::context::AiBillingServiceType, crate::api::context::AuthorizationService>,+ ai_billing::inbound::axum_router::purchase_credits_handler::<crate::api::context::AiBillingServiceType, crate::api::context::AuthorizationService>,/// /sessionsession::session_login::handler,@@ -300,6 +301,10 @@ use model::user::{ai_billing::AutoReloadSnapshot,ai_billing::inbound::axum_router::CreditCheckoutRequestBody,ai_billing::inbound::axum_router::CreditCheckoutResponse,+ ai_billing::inbound::axum_router::CreditPurchaseRequestBody,+ ai_billing::inbound::axum_router::CreditPurchaseResponse,+ ai_billing::CreditPurchaseStatus,+ ai_billing::CreditPurchaseSnapshot,// GitHub pull requestsEnrichGithubPullRequestsProxyRequest,diff --git a/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs b/services/authentication_service/src/api/webhooks/user/stripe_webhook.rsindex 03563800b4..4b3cc7dd35 100644--- a/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs+++ b/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs@@ -6,7 +6,7 @@ use crate::api::user::stripe::PaidPlan;use ai_billing::BillingService;use ai_billing::outbound::stripe_gateway::{- PURPOSE_AI_CREDIT_RELOAD, PURPOSE_AI_OVERAGE, PURPOSE_METADATA_KEY,+ PURPOSE_AI_CREDIT_RELOAD, PURPOSE_AI_OVERAGE, PURPOSE_METADATA_KEY, RELOAD_METADATA_KEY,};use analytics_client::{AnalyticsClient, MetaActionSource, MetaUserData};use anyhow::Context;@@ -261,8 +261,15 @@ async fn handle_payment_event(paid,"processing ai credit reload invoice event");+ // The reload id finds a paid invoice whose id never+ // reached its row.+ let reload_id = invoice+ .metadata+ .as_ref()+ .and_then(|m| m.get(RELOAD_METADATA_KEY))+ .and_then(|id| macro_uuid::string_to_uuid(id).ok());ctx.ai_billing_service- .mark_credit_reload_invoice(invoice_id.as_str(), paid)+ .mark_credit_reload_invoice(invoice_id.as_str(), reload_id, paid).await.context("failed to record ai credit reload invoice outcome")?;return Ok(());