Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(ai-billing): add an operator CLI to grant users prepaid AI credit (#8438)

Wolf Mermelstein39901bd674eb
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index a837c9efeb..4efb3fd181 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -1530,6 +1530,109 @@
"crates/unfurl",
"crates/workspace-hack"
],
+ "ai_billing_cli": [
+ "crates/activity",
+ "crates/agent",
+ "crates/agent_runtime_protocol",
+ "crates/ai_billing",
+ "crates/ai_toolset",
+ "crates/ai_usage",
+ "crates/analytics_client",
+ "crates/attachment",
+ "crates/authentication_service_client",
+ "crates/bot_id",
+ "crates/bot_token",
+ "crates/broadcast",
+ "crates/calendar_events",
+ "crates/call",
+ "crates/channel_sender",
+ "crates/channels",
+ "crates/connection",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
+ "crates/contacts",
+ "crates/cowlike",
+ "crates/crm",
+ "crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
+ "crates/document_sub_type",
+ "crates/email",
+ "crates/email_api_client",
+ "crates/email_db_client",
+ "crates/email_utils",
+ "crates/entity_access",
+ "crates/entity_access_db_utils",
+ "crates/entity_access_management",
+ "crates/entity_mutation",
+ "crates/entity_registry/shared_entity_registry",
+ "crates/filter_ast",
+ "crates/folds/agent_fold",
+ "crates/frecency",
+ "crates/genai_telemetry",
+ "crates/generic_email_domains",
+ "crates/gmail_client",
+ "crates/google_token",
+ "crates/harness_id",
+ "crates/harness_token",
+ "crates/initiative",
+ "crates/invite_email",
+ "crates/ip_extractor",
+ "crates/item_filters",
+ "crates/kafka_util",
+ "crates/last_online_tracker",
+ "crates/lexical_client",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_aws_config",
+ "crates/macro_entrypoint",
+ "crates/macro_env",
+ "crates/macro_env_var",
+ "crates/macro_event_broker",
+ "crates/macro_event_topics",
+ "crates/macro_service_urls",
+ "crates/macro_tower_layers",
+ "crates/macro_user_id",
+ "crates/macro_uuid",
+ "crates/maybe_send",
+ "crates/mention_utils",
+ "crates/messages",
+ "crates/model",
+ "crates/model-entity",
+ "crates/model-error-response",
+ "crates/model_file_type",
+ "crates/model_notifications",
+ "crates/model_owner",
+ "crates/model_user",
+ "crates/models_ai_projection",
+ "crates/models_bulk_upload",
+ "crates/models_databases",
+ "crates/models_email",
+ "crates/models_entity_access_management",
+ "crates/models_pagination",
+ "crates/models_permissions",
+ "crates/models_properties",
+ "crates/models_sfs",
+ "crates/non_empty",
+ "crates/notification",
+ "crates/notification_state",
+ "crates/prompt",
+ "crates/properties",
+ "crates/rate_limit",
+ "crates/remote_env_var",
+ "crates/roles_and_permissions",
+ "crates/s3_key",
+ "crates/share_permission_db_utils",
+ "crates/sqs_client",
+ "crates/sqs_worker",
+ "crates/static_file_service_client",
+ "crates/system_properties",
+ "crates/teams",
+ "crates/trigger_context",
+ "crates/unfurl",
+ "crates/workspace-hack",
+ "tooling/ai_billing_cli"
+ ],
"ai_engine": [
"crates/ai_engine",
"crates/fig_engine"
diff --git a/.sqlx/query-e600403a6916550e59233b8ca1e99ed945c6e92de32fdedf3ae4924d57c45dd2.json b/.sqlx/query-e600403a6916550e59233b8ca1e99ed945c6e92de32fdedf3ae4924d57c45dd2.json
new file mode 100644
index 0000000000..8e89ee80b0
--- /dev/null
+++ b/.sqlx/query-e600403a6916550e59233b8ca1e99ed945c6e92de32fdedf3ae4924d57c45dd2.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO ai_credit_ledger (id, user_id, kind, delta_cents, note)\n VALUES ($1, $2, 'grant', $3, $4)\n ON CONFLICT (id) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Int8",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e600403a6916550e59233b8ca1e99ed945c6e92de32fdedf3ae4924d57c45dd2"
+}
diff --git a/Cargo.lock b/Cargo.lock
index f27100eeae..7d41f6840b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -921,6 +921,22 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "ai_billing_cli"
+version = "0.1.0"
+dependencies = [
+ "ai_billing",
+ "clap",
+ "macro_env_var",
+ "macro_user_id",
+ "macro_uuid",
+ "rootcause",
+ "sqlx",
+ "tokio",
+ "tracing",
+ "workspace-hack",
+]
+
[[package]]
name = "ai_engine"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 4922829a2a..c677415680 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -176,6 +176,7 @@ members = [
"services/worker_trigger",
"tooling/native_app_server",
"tooling/notification_sandbox",
+ "tooling/ai_billing_cli",
"tooling/seed_cli",
"tooling/xtask",
"tooling/xtask/crates/*",
diff --git a/crates/ai_billing/AGENTS.md b/crates/ai_billing/AGENTS.md
index 9a92f00271..ea7c3aa6c2 100644
--- a/crates/ai_billing/AGENTS.md
+++ b/crates/ai_billing/AGENTS.md
@@ -39,6 +39,8 @@ provider cost (plus markup for overage).
- Change a pricing number: Doppler (never hardcode) → `src/config.rs` →
`src/domain/pricing.rs`.
- Add an admission check: `src/domain/admission.rs` → `src/inbound/admission.rs`.
+- Grant a user credit (operator refund): `tooling/ai_billing_cli` →
+ `src/domain/credit_grant.rs` → `src/outbound/pg_credit_grant_repo.rs`.
## Checks
diff --git a/crates/ai_billing/src/composition.rs b/crates/ai_billing/src/composition.rs
index c7c370db50..d5c36bcadc 100644
--- a/crates/ai_billing/src/composition.rs
+++ b/crates/ai_billing/src/composition.rs
@@ -1,6 +1,6 @@
//! Composition helpers for hosts that gate and record AI usage without owning
-//! Stripe: quota admission, and the usage recorder that asks the
-//! authentication service to settle.
+//! Stripe: quota admission, the usage recorder that asks the
+//! authentication service to settle, and operator credit grants.
use crate::{
AiAdmissionService, AiPricing, AiUsageBilling, AiUsageEnforcement, BillingAdmissionService,
@@ -86,6 +86,35 @@ pub fn pg_admission_service(
)
}
+/// Postgres-backed [`CreditGrantService`] for operator tools.
+#[cfg(feature = "pg-admission")]
+pub type PgCreditGrantService = crate::domain::CreditGrantService<
+ RolesTeamsEntitlementSource<
+ roles_and_permissions::domain::service::UserRolesAndPermissionsServiceImpl<
+ roles_and_permissions::outbound::pgpool::MacroDB,
+ roles_and_permissions::outbound::pgpool::MacroDB,
+ >,
+ teams::outbound::team_repo::TeamRepositoryImpl,
+ >,
+ crate::outbound::PgCreditGrantRepo,
+>;
+
+/// Compose credit grants over one database pool. Needs no pricing or Stripe:
+/// the grant only books ledger credit, and the next settlement uses it.
+#[cfg(feature = "pg-admission")]
+pub fn pg_credit_grant_service(pool: PgPool) -> PgCreditGrantService {
+ crate::domain::CreditGrantService::new(
+ RolesTeamsEntitlementSource::new(
+ roles_and_permissions::domain::service::UserRolesAndPermissionsServiceImpl::new(
+ roles_and_permissions::outbound::pgpool::MacroDB::new(pool.clone()),
+ roles_and_permissions::outbound::pgpool::MacroDB::new(pool.clone()),
+ ),
+ teams::outbound::team_repo::TeamRepositoryImpl::new(pool.clone()),
+ ),
+ crate::outbound::PgCreditGrantRepo::new(pool),
+ )
+}
+
/// Compose admission from the host's existing roles service, team repository and
/// database pool. Both admission and billing receive the same explicit policy.
/// This service never settles usage, requests collection, or installs financial
diff --git a/crates/ai_billing/src/domain.rs b/crates/ai_billing/src/domain.rs
index 196fa37e75..24e8c5d128 100644
--- a/crates/ai_billing/src/domain.rs
+++ b/crates/ai_billing/src/domain.rs
@@ -2,6 +2,7 @@
//! the billing service, and the reconciliation sweep.
pub mod admission;
+pub mod credit_grant;
pub mod financial;
pub mod ledger;
pub mod models;
@@ -17,6 +18,7 @@ pub use admission::{
AdmissionFuture, AiAdmissionError, AiAdmissionService, BillingAdmissionService,
DisabledAiAdmissionService,
};
+pub use credit_grant::{CreditGrant, CreditGrantRepo, CreditGrantService, GrantTarget};
pub use ledger::{
ReloadState, SettlementPlan, SettlementPolicy, SettlementState, plan_reload, plan_settlement,
};
diff --git a/crates/ai_billing/src/domain/credit_grant.rs b/crates/ai_billing/src/domain/credit_grant.rs
new file mode 100644
index 0000000000..4eb4d596d5
--- /dev/null
+++ b/crates/ai_billing/src/domain/credit_grant.rs
@@ -0,0 +1,101 @@
+//! Credits granted by an operator, e.g. to refund a user's usage.
+//!
+//! A grant is a positive `grant` entry in the payer's prepaid credit ledger,
+//! in customer cents. Like purchased credits, it only funds paid usage beyond
+//! a seat's allowance, at the overage markup; it does not reset the allowance.
+
+use std::num::NonZeroU32;
+
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+
+use super::{BillingError, EntitlementSource, PlanTier, Result};
+
+#[cfg(test)]
+mod test;
+
+/// A grant to book. `id` makes it idempotent: booking the same id twice
+/// leaves one entry.
+#[derive(Debug, Clone)]
+pub struct CreditGrant {
+ /// Ledger entry id, a UUIDv7 chosen by the caller.
+ pub id: Uuid,
+ /// Customer cents to add to the payer's balance.
+ pub amount_cents: NonZeroU32,
+ /// Why the grant was issued and by whom; stored on the ledger entry.
+ pub note: String,
+}
+
+/// Who a grant for a user lands on.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct GrantTarget {
+ /// The account that owns the credit balance: the user, or their team owner.
+ pub payer: MacroUserIdStr<'static>,
+ /// The user's own plan.
+ pub tier: PlanTier,
+}
+
+/// Persists credit grants.
+pub trait CreditGrantRepo: Send + Sync + 'static {
+ /// Book `grant` on `payer`'s ledger. Returns `false` when an entry with
+ /// the grant's id already exists.
+ fn record_credit_grant(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ grant: &CreditGrant,
+ ) -> impl Future<Output = Result<bool>> + Send;
+
+ /// The payer's prepaid credit balance in customer cents.
+ fn credit_grant_balance_cents(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<i64>> + Send;
+}
+
+/// Grants credits to the account that pays for a user's AI usage.
+pub struct CreditGrantService<Entitlements, Repo> {
+ entitlements: Entitlements,
+ repo: Repo,
+}
+
+impl<Entitlements, Repo> CreditGrantService<Entitlements, Repo>
+where
+ Entitlements: EntitlementSource,
+ Repo: CreditGrantRepo,
+{
+ /// Build the service.
+ pub fn new(entitlements: Entitlements, repo: Repo) -> Self {
+ Self { entitlements, repo }
+ }
+
+ /// Resolve whose balance a grant for `user` would land on. Free users
+ /// are hard-capped at their allowance, so credits cannot help them.
+ pub async fn target(&self, user: &MacroUserIdStr<'_>) -> Result<GrantTarget> {
+ let entitlement = self.entitlements.entitlement(user).await?;
+ if !entitlement.tier.is_paid() {
+ return Err(BillingError::FreePlan);
+ }
+ Ok(GrantTarget {
+ payer: entitlement.payer,
+ tier: entitlement.tier,
+ })
+ }
+
+ /// The payer's current credit balance in customer cents.
+ pub async fn balance_cents(&self, payer: &MacroUserIdStr<'_>) -> Result<i64> {
+ self.repo.credit_grant_balance_cents(payer).await
+ }
+
+ /// Book `grant` for `user`'s payer. Returns the target and whether the
+ /// grant was newly booked.
+ #[tracing::instrument(skip(self, grant), fields(grant_id = %grant.id, amount_cents = grant.amount_cents), err)]
+ pub async fn grant(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ grant: &CreditGrant,
+ ) -> Result<(GrantTarget, bool)> {
+ let target = self.target(user).await?;
+ let inserted = self.repo.record_credit_grant(&target.payer, grant).await?;
+ Ok((target, inserted))
+ }
+}
diff --git a/crates/ai_billing/src/domain/credit_grant/test.rs b/crates/ai_billing/src/domain/credit_grant/test.rs
new file mode 100644
index 0000000000..060cb9a60b
--- /dev/null
+++ b/crates/ai_billing/src/domain/credit_grant/test.rs
@@ -0,0 +1,107 @@
+use super::*;
+use crate::domain::{Entitlement, PayerScope};
+use std::sync::Mutex;
+
+struct OneEntitlement(Entitlement);
+
+impl EntitlementSource for OneEntitlement {
+ async fn entitlement(&self, _: &MacroUserIdStr<'_>) -> Result<Entitlement> {
+ Ok(self.0.clone())
+ }
+ async fn stripe_customer_id(&self, _: &MacroUserIdStr<'_>) -> Result<Option<String>> {
+ Ok(None)
+ }
+ async fn team_payer(&self, _: Uuid) -> Result<Option<MacroUserIdStr<'static>>> {
+ Ok(None)
+ }
+}
+
+#[derive(Default)]
+struct RecordingRepo {
+ booked: Mutex<Vec<(String, Uuid, u32)>>,
+}
+
+impl CreditGrantRepo for RecordingRepo {
+ async fn record_credit_grant(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ grant: &CreditGrant,
+ ) -> Result<bool> {
+ let mut booked = self.booked.lock().unwrap();
+ if booked.iter().any(|(_, id, _)| *id == grant.id) {
+ return Ok(false);
+ }
+ booked.push((
+ payer.as_ref().to_string(),
+ grant.id,
+ grant.amount_cents.get(),
+ ));
+ Ok(true)
+ }
+ async fn credit_grant_balance_cents(&self, _: &MacroUserIdStr<'_>) -> Result<i64> {
+ Ok(0)
+ }
+}
+
+#[tokio::test]
+async fn team_member_grant_lands_on_team_owner_once() {
+ let owner = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ let member = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ let team_id = Uuid::parse_str("01a15302-4b49-7df3-8b84-40b43624d747").unwrap();
+ let service = CreditGrantService::new(
+ OneEntitlement(Entitlement {
+ tier: PlanTier::Premium,
+ seat_tiers: vec![PlanTier::Premium, PlanTier::Premium],
+ unlimited: false,
+ payer: owner.clone(),
+ billed_users: vec![owner.clone(), member.clone()],
+ scope: PayerScope::TeamMember { team_id },
+ }),
+ RecordingRepo::default(),
+ );
+ let grant = CreditGrant {
+ id: Uuid::parse_str("019a0f6e-0000-7000-8000-000000000001").unwrap(),
+ amount_cents: NonZeroU32::new(1500).unwrap(),
+ note: "refund".to_string(),
+ };
+
+ let (target, inserted) = service.grant(&member, &grant).await.unwrap();
+ let (_, retried) = service.grant(&member, &grant).await.unwrap();
+
+ assert_eq!(
+ target,
+ GrantTarget {
+ payer: owner,
+ tier: PlanTier::Premium,
+ }
+ );
+ assert!(inserted);
+ assert!(!retried);
+ assert_eq!(
+ *service.repo.booked.lock().unwrap(),
+ vec![(
+ "macro|[email protected]".to_string(),
+ Uuid::parse_str("019a0f6e-0000-7000-8000-000000000001").unwrap(),
+ 1500,
+ )]
+ );
+}
+
+#[tokio::test]
+async fn free_user_grant_is_refused() {
+ let user = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ let service = CreditGrantService::new(
+ OneEntitlement(Entitlement::personal(user.clone(), PlanTier::Free)),
+ RecordingRepo::default(),
+ );
+ let grant = CreditGrant {
+ id: Uuid::parse_str("019a0f6e-0000-7000-8000-000000000002").unwrap(),
+ amount_cents: NonZeroU32::new(1500).unwrap(),
+ note: "refund".to_string(),
+ };
+
+ let result = service.grant(&user, &grant).await;
+
+ assert!(matches!(result, Err(BillingError::FreePlan)));
+ assert!(service.repo.booked.lock().unwrap().is_empty());
+}
diff --git a/crates/ai_billing/src/outbound.rs b/crates/ai_billing/src/outbound.rs
index 5eed0823bc..4956ffef7d 100644
--- a/crates/ai_billing/src/outbound.rs
+++ b/crates/ai_billing/src/outbound.rs
@@ -1,4 +1,4 @@
-//! Outbound adapters: Postgres, Stripe, the roles + teams entitlement resolver,
+//! Outbound adapters: Postgres (including operator credit grants), Stripe, the roles + teams entitlement resolver,
//! the internal settlement trigger and subscription-period reader, the
//! sweep's candidate finder, and the settling usage recorder.
@@ -6,6 +6,7 @@ pub mod entitlement;
pub mod http_payment_gateway;
pub mod http_settlement_trigger;
pub mod pg_billing_repo;
+pub mod pg_credit_grant_repo;
pub mod pg_funding_repo;
pub mod pg_settlement_candidates;
pub mod pg_usage_reader;
@@ -16,6 +17,7 @@ pub use entitlement::RolesTeamsEntitlementSource;
pub use http_payment_gateway::HttpPaymentGateway;
pub use http_settlement_trigger::HttpSettlementTrigger;
pub use pg_billing_repo::PgBillingRepo;
+pub use pg_credit_grant_repo::PgCreditGrantRepo;
pub use pg_funding_repo::PgFundingRepo;
pub use pg_settlement_candidates::PgSettlementCandidates;
pub use pg_usage_reader::PgUsageReader;
diff --git a/crates/ai_billing/src/outbound/pg_credit_grant_repo.rs b/crates/ai_billing/src/outbound/pg_credit_grant_repo.rs
new file mode 100644
index 0000000000..044a8c81f5
--- /dev/null
+++ b/crates/ai_billing/src/outbound/pg_credit_grant_repo.rs
@@ -0,0 +1,70 @@
+//! Postgres adapter for operator credit grants on `ai_credit_ledger`.
+
+#[cfg(test)]
+mod test;
+
+use super::pg_funding_repo::lock_payer;
+use crate::domain::credit_grant::{CreditGrant, CreditGrantRepo};
+use crate::domain::{BillingError, Result};
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+
+/// Postgres-backed [`CreditGrantRepo`].
+#[derive(Clone)]
+pub struct PgCreditGrantRepo {
+ pool: PgPool,
+}
+
+impl PgCreditGrantRepo {
+ /// Create a repo over a connection pool.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+fn storage(e: impl Into<anyhow::Error>) -> BillingError {
+ BillingError::Storage(e.into())
+}
+
+impl CreditGrantRepo for PgCreditGrantRepo {
+ async fn record_credit_grant(
+ &self,
+ payer: &MacroUserIdStr<'_>,
+ grant: &CreditGrant,
+ ) -> Result<bool> {
+ let mut tx = self.pool.begin().await.map_err(storage)?;
+ // Same row lock as purchases and settlement, so a grant never lands
+ // in the middle of a settlement's balance read.
+ lock_payer(&mut tx, payer.as_ref()).await.map_err(storage)?;
+ let result = sqlx::query!(
+ r#"
+ INSERT INTO ai_credit_ledger (id, user_id, kind, delta_cents, note)
+ VALUES ($1, $2, 'grant', $3, $4)
+ ON CONFLICT (id) DO NOTHING
+ "#,
+ grant.id,
+ payer.as_ref(),
+ i64::from(grant.amount_cents.get()),
+ grant.note,
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(storage)?;
+ tx.commit().await.map_err(storage)?;
+ Ok(result.rows_affected() == 1)
+ }
+
+ async fn credit_grant_balance_cents(&self, payer: &MacroUserIdStr<'_>) -> Result<i64> {
+ sqlx::query_scalar!(
+ r#"
+ SELECT COALESCE(SUM(delta_cents), 0)::bigint AS "balance!"
+ FROM ai_credit_ledger
+ WHERE user_id = $1
+ "#,
+ payer.as_ref(),
+ )
+ .fetch_one(&self.pool)
+ .await
+ .map_err(storage)
+ }
+}
diff --git a/crates/ai_billing/src/outbound/pg_credit_grant_repo/test.rs b/crates/ai_billing/src/outbound/pg_credit_grant_repo/test.rs
new file mode 100644
index 0000000000..1a2c21bed8
--- /dev/null
+++ b/crates/ai_billing/src/outbound/pg_credit_grant_repo/test.rs
@@ -0,0 +1,22 @@
+use super::*;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_uuid::Uuid;
+use std::num::NonZeroU32;
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn grant_adds_to_balance_once_per_id(pool: PgPool) {
+ let repo = PgCreditGrantRepo::new(pool);
+ let payer = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ let grant = CreditGrant {
+ id: Uuid::parse_str("019a0f6e-0000-7000-8000-000000000001").unwrap(),
+ amount_cents: NonZeroU32::new(1500).unwrap(),
+ note: "manual grant: usage refund".to_string(),
+ };
+
+ let first = repo.record_credit_grant(&payer, &grant).await.unwrap();
+ let retry = repo.record_credit_grant(&payer, &grant).await.unwrap();
+
+ assert!(first);
+ assert!(!retry);
+ assert_eq!(repo.credit_grant_balance_cents(&payer).await.unwrap(), 1500);
+}
diff --git a/tooling/ai_billing_cli/AGENTS.md b/tooling/ai_billing_cli/AGENTS.md
new file mode 100644
index 0000000000..4348a78191
--- /dev/null
+++ b/tooling/ai_billing_cli/AGENTS.md
@@ -0,0 +1,36 @@
+# ai_billing_cli
+
+## What it is
+
+Operator CLI for AI billing (`ai-billing`). `grant-credits` adds prepaid AI
+credit to the account that pays for a user, e.g. to refund usage. The use case
+lives in `crates/ai_billing` (`domain/credit_grant.rs`); this binary only
+parses arguments and prints.
+
+## Recipes
+
+- Dry run, then book with the id it printed:
+
+ ```bash
+ DATABASE_URL=... cargo run -p ai_billing_cli -- grant-credits \
+ --user 'macro|[email protected]' --amount-cents 1500 \
+ --reason 'refund of October usage, by <you>'
+ # ...then the same command plus --execute --grant-id <printed id>
+ ```
+
+- Prod: use the `DATABASE_URL` from Doppler `global_databases` / `prd`. The
+ database only accepts allowlisted IPs (security group `macrodb-sg-prod`),
+ such as the NYC office; elsewhere, tunnel through an allowlisted machine.
+ Writing to prod needs explicit permission (root `CLAUDE.md`).
+
+## Checks
+
+- `cargo test -p ai_billing credit_grant` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Credit is in customer cents and funds only usage beyond a paid plan's
+ allowance, at the overage markup (`AI_USAGE_OVERAGE_MARKUP_PERCENT`): $15 of
+ credit covers $12 of usage at a 25% markup. It does not reset the allowance,
+ and free users are refused (they are hard-capped).
+- `--user` takes the billing id `macro|<email>`, not the `macro_user` UUID.
diff --git a/tooling/ai_billing_cli/CLAUDE.md b/tooling/ai_billing_cli/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/tooling/ai_billing_cli/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/tooling/ai_billing_cli/Cargo.toml b/tooling/ai_billing_cli/Cargo.toml
new file mode 100644
index 0000000000..8bfb2639cb
--- /dev/null
+++ b/tooling/ai_billing_cli/Cargo.toml
@@ -0,0 +1,21 @@
+[package]
+edition = "2024"
+name = "ai_billing_cli"
+publish = false
+version = "0.1.0"
+
+[[bin]]
+name = "ai-billing"
+path = "src/main.rs"
+
+[dependencies]
+ai_billing = { path = "../../crates/ai_billing", features = ["pg-admission"] }
+clap = { workspace = true }
+macro_env_var = { path = "../../crates/macro_env_var" }
+macro_user_id = { path = "../../crates/macro_user_id" }
+macro_uuid = { path = "../../crates/macro_uuid" }
+rootcause = { workspace = true }
+sqlx = { workspace = true }
+tokio = { workspace = true }
+tracing = { workspace = true }
+workspace-hack = { version = "0.1", path = "../../crates/workspace-hack" }
diff --git a/tooling/ai_billing_cli/src/main.rs b/tooling/ai_billing_cli/src/main.rs
new file mode 100644
index 0000000000..0aecb490ee
--- /dev/null
+++ b/tooling/ai_billing_cli/src/main.rs
@@ -0,0 +1,114 @@
+//! Operator CLI for AI billing. See `AGENTS.md` for how to point it at an
+//! environment.
+
+use std::num::NonZeroU32;
+use std::process::ExitCode;
+
+use ai_billing::composition::pg_credit_grant_service;
+use ai_billing::domain::CreditGrant;
+use clap::{Parser, Subcommand};
+use macro_env_var::env_var;
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use sqlx::postgres::PgPoolOptions;
+
+env_var! {
+ struct DatabaseUrl;
+}
+
+#[derive(Parser)]
+#[command(name = "ai-billing", about = "Operator tools for AI billing")]
+struct Cli {
+ #[command(subcommand)]
+ command: Command,
+}
+
+#[derive(Subcommand)]
+enum Command {
+ /// Add prepaid AI credit to the balance of the account that pays for a
+ /// user. Credit funds usage beyond the plan allowance at the overage
+ /// markup; it does not reset the allowance. Prints a dry run unless
+ /// `--execute` is passed.
+ GrantCredits {
+ /// The user, as `macro|<email>`. A team member's grant lands on the
+ /// team owner's balance.
+ #[arg(long)]
+ user: String,
+ /// Customer cents to add, e.g. 1500 for $15.00 of credit.
+ #[arg(long)]
+ amount_cents: NonZeroU32,
+ /// Why, and who issued it. Stored on the ledger entry.
+ #[arg(long)]
+ reason: String,
+ /// Ledger entry id. Pass the id a dry run printed: re-running with the
+ /// same id never books a second grant.
+ #[arg(long)]
+ grant_id: Option<Uuid>,
+ /// Book the grant. Without it, nothing is written.
+ #[arg(long)]
+ execute: bool,
+ },
+}
+
+#[tokio::main]
+async fn main() -> ExitCode {
+ match run(Cli::parse()).await {
+ Ok(()) => ExitCode::SUCCESS,
+ Err(report) => {
+ eprintln!("{report}");
+ ExitCode::FAILURE
+ }
+ }
+}
+
+async fn run(cli: Cli) -> Result<(), rootcause::Report> {
+ let Command::GrantCredits {
+ user,
+ amount_cents,
+ reason,
+ grant_id,
+ execute,
+ } = cli.command;
+ let user = MacroUserIdStr::try_from(user)?;
+ let pool = PgPoolOptions::new()
+ .max_connections(2)
+ .connect(&DatabaseUrl::new()?)
+ .await?;
+ let service = pg_credit_grant_service(pool);
+ let grant = CreditGrant {
+ id: grant_id.unwrap_or_else(macro_uuid::generate_uuid_v7),
+ amount_cents,
+ note: format!("manual grant: {reason}"),
+ };
+
+ let target = service.target(&user).await?;
+ let balance = service.balance_cents(&target.payer).await?;
+ println!("user: {}", user.as_ref());
+ println!(
+ "payer: {} ({:?} plan)",
+ target.payer.as_ref(),
+ target.tier
+ );
+ println!("balance: {balance} cents");
+ println!("grant: {amount_cents} cents, id {}", grant.id);
+ println!("note: {}", grant.note);
+ if !execute {
+ println!(
+ "dry run: nothing written. Re-run with --execute --grant-id {}",
+ grant.id
+ );
+ return Ok(());
+ }
+
+ let (_, inserted) = service.grant(&user, &grant).await?;
+ let balance = service.balance_cents(&target.payer).await?;
+ if inserted {
+ println!("booked. balance now {balance} cents");
+ } else {
+ println!(
+ "grant {} was already booked. balance {balance} cents",
+ grant.id
+ );
+ }
+ Ok(())
+}