### List top-level configuration sections Source: https://github.com/zonastery/bursar/blob/main/samples/python/notebooks/01_first_pricing_config.ipynb Loads the shared demo configuration and prints its top-level keys. Requires the notebook server started from samples/python/notebooks/ and the setup tutorial completed. ```python from shared import base_config, start_postgres_store, cleanup, publish_config from bursar.config import load_config_from_dict, ConfigError config = base_config() print("top-level sections:", sorted(config.keys())) ``` -------------------------------- ### Setup: start Postgres store and create pro-plan users Source: https://github.com/zonastery/bursar/blob/main/samples/python/notebooks/10_analytics.ipynb Initializes the Postgres store, publishes the base configuration, and creates three demo users on the pro plan with 5000 credits each. The pro plan has no free allowance, so all deductions become real spend. ```python import atexit from shared import start_postgres_store, cleanup, base_config, publish_config, USER_ADA, USER_ALEX, USER_JAMAL from datetime import UTC, datetime, timedelta from decimal import Decimal from bursar.metrics import UsageMetrics store, pgdata = start_postgres_store() atexit.register(cleanup, pgdata) burssar = publish_config(store, base_config()) credits = bursar.credits for user, account in ( (USER_ADA, "acct_ada"), (USER_ALEX, "acct_alex"), (USER_JAMAL, "acct_jamal"), ): bursar.accounts.on_account_created(user, account) credits.set_user_plan(user, "pro") credits.add_credits( user, Decimal(5000), idempotency_key=f"analytics:seed:{account}" ) print("users on pro plan") ``` -------------------------------- ### Setup: start Postgres store and create account Source: https://github.com/zonastery/bursar/blob/main/samples/python/notebooks/05_plans_and_allowances.ipynb Initializes a temporary Postgres store, publishes the base config, and creates an account for USER_ADA. The on_account_created hook assigns the free plan by default. Prints the assigned plan key. ```python from decimal import Decimal from bursar.metrics import UsageMetrics from shared import cleanup, base_config, publish_config, start_postgres_store, USER_ADA def completion(output=Decimal(500)): return UsageMetrics( operation="completion", measures={ "input_tokens": Decimal(1000), "output_tokens": output, "cache_read_tokens": Decimal(200), }, dimensions={"model": "gpt-4o"}, ) def execution(jobs=Decimal(1)): return UsageMetrics( operation="execution", measures={"jobs": jobs, "compute_seconds": Decimal(30)}, dimensions={"model": "gpt-4o"}, ) store, pgdata = start_postgres_store() burssar = publish_config(store, base_config()) burssar.accounts.on_account_created(USER_ADA, "signup") print("created on plan:", burssar.credits.get_user_plan(USER_ADA).plan_key) ``` -------------------------------- ### Setup: start Postgres store and configure user with purchased credits Source: https://github.com/zonastery/bursar/blob/main/samples/python/notebooks/07_credit_tiers_and_expiry.ipynb Initializes the sandbox: starts a temporary Postgres store, publishes the base config, creates USER_ADA on the pro plan, and adds 100 purchased credits. Prints 'ready' when complete. ```python from decimal import Decimal from datetime import UTC, datetime, timedelta from time import sleep from bursar.metrics import UsageMetrics from shared import cleanup, base_config, publish_config, start_postgres_store, USER_ADA def completion(output=Decimal(500)): return UsageMetrics( operation="completion", measures={ "input_tokens": Decimal(1000), "output_tokens": output, "cache_read_tokens": Decimal(200), }, dimensions={"model": "gpt-4o"}, ) store, pgdata = start_postgres_store() bursar = publish_config(store, base_config()) bursar.accounts.on_account_created(USER_ADA, "signup") bursar.credits.set_user_plan(USER_ADA, "pro") bursar.credits.add_credits(USER_ADA, Decimal("100.00"), entry_type="purchase", idempotency_key="buy") print("ready") ``` -------------------------------- ### Setup: start Postgres store and publish config Source: https://github.com/zonastery/bursar/blob/main/samples/python/notebooks/09_teams.ipynb Initializes a throwaway Postgres cluster, runs the bursar schema, and publishes the demo configuration. Returns a Bursar facade bound to the store. ```python import atexit from shared import start_postgres_store, cleanup, base_config, publish_config, USER_ADA, USER_ALEX, USER_JAMAL from decimal import Decimal from bursar.metrics import UsageMetrics store, pgdata = start_postgres_store() atexit.register(cleanup, pgdata) bursar = publish_config(store, base_config()) credits = bursar.credits print("config published") ``` -------------------------------- ### Example output of bursar config get Source: https://github.com/zonastery/bursar/blob/main/samples/python/notebooks/13_cli_and_deployment.ipynb Truncated example of the JSON output from 'bursar config get', showing the revision id, config document, and version number. ```json { "id": "019fbb6d-...", "config": { "version": 1, "catalog": {"default_plan": "free"}, "pricing": {"operations": {"completion": {...}, "execution": {...}}, "rate_cards": {"standard": {...}}}, "credits": {"buckets": {"promotional": {"priority": 1}, "purchased": {"priority": 10}}, "default_bucket": "purchased"}, "plans": {"free": {...}, "pro": {...}}, "commerce": {"providers": {"stripe": {"type": "stripe"}}, "offers": {...}} }, "version": 3 } ``` -------------------------------- ### Run Docusaurus development server Source: https://github.com/zonastery/bursar/blob/main/docs/README.md Starts the local documentation server. The prestart hook regenerates API, notebook, and database artifacts before Docusaurus starts. ```bash npm start ``` -------------------------------- ### Setup: start Postgres store and configure pro plan Source: https://github.com/zonastery/bursar/blob/main/samples/python/notebooks/04_credit_lifecycle.ipynb Initializes a temporary PostgreSQL store, publishes the base pricing config, and creates USER_ADA on the pro plan. Defines helper functions for completion and execution usage metrics. Requires the shared helper to create a disposable PostgreSQL environment. ```python from decimal import Decimal from bursar.metrics import UsageMetrics from shared import cleanup, base_config, publish_config, start_postgres_store, USER_ADA def completion(output=Decimal(500)): return UsageMetrics( operation="completion", measures={ "input_tokens": Decimal(1000), "output_tokens": output, "cache_read_tokens": Decimal(200), }, dimensions={"model": "gpt-4o"}, ) def execution(jobs=Decimal(1)): return UsageMetrics( operation="execution", measures={"jobs": jobs, "compute_seconds": Decimal(30)}, dimensions={"model": "gpt-4o"}, ) store, pgdata = start_postgres_store() bursar = publish_config(store, base_config()) bursar.accounts.on_account_created(USER_ADA, "signup") bursar.credits.set_user_plan(USER_ADA, "pro") print("temporary postgres:", pgdata) ``` -------------------------------- ### Install dependencies for documentation Source: https://github.com/zonastery/bursar/blob/main/docs/README.md Install Python, JavaScript, and documentation dependencies from the repository root and package directories. Requires Node.js 22+, Bun 1.4.4, and Python 3.12-3.15. ```bash cd python uv sync --group dev uv pip install --python .venv sphinx sphinx-markdown-builder cd ../javascript bun ci cd ../docs npm ci ``` -------------------------------- ### Setup: configure sandbox and pricing Source: https://github.com/zonastery/bursar/blob/main/samples/python/notebooks/08_leases_and_financial_safety.ipynb Initializes a temporary Postgres store, creates user USER_ADA on the pro plan with 100 credits, and sets pricing so execution costs 0.04 credits per job. Prints 'ready' after setup. ```python from decimal import Decimal from time import sleep from bursar.metrics import UsageMetrics from shared import cleanup, base_config, publish_config, start_postgres_store, USER_ADA def execution(jobs=Decimal(1)): return UsageMetrics( operation="execution", measures={"jobs": jobs, "compute_seconds": Decimal(30)}, dimensions={"model": "gpt-4o"}, ) store, pgdata = start_postgres_store() bursar = publish_config(store, base_config()) bursar.accounts.on_account_created(USER_ADA, "signup") bursar.credits.set_user_plan(USER_ADA, "pro") bursar.credits.add_credits(USER_ADA, Decimal("100.00"), entry_type="purchase", idempotency_key="buy") print("ready") ``` -------------------------------- ### Install TypeScript package Source: https://github.com/zonastery/bursar/blob/main/docs/docs/quickstart.mdx Installs the Node.js package for TypeScript applications. Requires Node.js 22 or newer. ```bash npm install @zonastery/bursar pg ``` -------------------------------- ### Pricing Engine configuration and calculation example Source: https://github.com/zonastery/bursar/blob/main/docs/docs/python-api/pricing-engine.mdx Uses the canonical demo configuration with rate card 'standard' and per-million-token rates for 'gpt-4o'/'gpt-4o-mini'. Includes an expression-based fallback for unmatched models. The example calculates cost for 2,000,000 input tokens and 500,000 output tokens, asserting a total of 0.01. ```python from decimal import Decimal config = { "version": 1, "pricing": { "operations": { "completion": { "measures": { "input_tokens": {"unit": "token"}, "output_tokens": {"unit": "token"}, "cache_read_tokens": {"unit": "token"}, }, "dimensions": {"model": {"type": "string"}}, } }, "rate_cards": { "standard": { "operations": { "completion": { "rules": [ { "when": {"model": {"op": "in", "values": ["gpt-4o", "gpt-4o-mini"]}}, "charge": { "type": "sum", "components": [ {"type": "per_unit", "measure": "input_tokens", "rate": "0.0025", "unit_size": "1000000"}, {"type": "per_unit", "measure": "output_tokens", "rate": "0.0100", "unit_size": "1000000"}, {"type": "per_unit", "measure": "cache_read_tokens", "rate": "0.00125", "unit_size": "1000000"}, ], }, } ], "unmatched": { "action": "charge", "charge": { "type": "expression", "formula": "input_tokens * 0.005 + output_tokens * 0.015", }, }, } } } }, }, "credits": {}, } engine = PricingEngine.from_dict(config) cost = engine.calculate( UsageMetrics( operation="completion", measures={"input_tokens": 2_000_000, "output_tokens": 500_000}, dimensions={"model": "gpt-4o"}, ) ) assert cost.total == Decimal("0.01") # 2,000,000 × 0.0025/M + 500,000 × 0.0100/M ``` -------------------------------- ### Install Google ADK adapter Source: https://github.com/zonastery/bursar/blob/main/README.md Installs the optional Google ADK integration adapter for Go. Requires Go 1.26.11 or newer. Releases publish the matching golang/integrations/googleadk/v2.0.6 tag. ```bash go get github.com/Zonastery/bursar/golang/integrations/googleadk/v2 ``` -------------------------------- ### Create account and add credits (Go) Source: https://github.com/zonastery/bursar/blob/main/docs/docs/quickstart.mdx Go example for creating an account and adding credits with an idempotency key. The signup event assigns the 'standard' plan from 'catalog.default_plan'. The purchase appends one ledger entry and creates spendable credit in the 'purchased' bucket. ```go accountID := "11111111-1111-4111-8111-111111111111" if _, err := sdk.Accounts.OnAccountCreated(ctx, bursar.AccountCreatedInput{ AccountID: accountID, EventKey: "signup:11111111", }); err != nil { log.Fatal(err) } grant, err := sdk.Credits.AddCredits(ctx, accountID, bursar.MustAmount("100.000000"), bursar.AddCreditsOptions{ Type: "purchase", IdempotencyKey: "purchase:quickstart:11111111", }) if err != nil { log.Fatal(err) } log.Println(grant.EntryID, grant.NewBalance) ``` -------------------------------- ### Invoke the skill with $bursar Source: https://github.com/zonastery/bursar/blob/main/docs/docs/agent-skills.mdx Example requests that invoke the `$bursar` skill explicitly to apply the integration workflow. The skill should cause the agent to identify the installed Bursar version, inspect relevant local types, preserve tenant isolation, and verify idempotency before changing code. ```text Use $bursar to add replay-safe token usage charges to this API route. ``` ```text Use $bursar to review this checkout webhook for double-credit risks. ``` ```text Use $bursar to add a reserve and settle flow around this background job. ``` -------------------------------- ### Install Go SDK module Source: https://github.com/zonastery/bursar/blob/main/README.md Installs the versioned Go SDK module for Bursar. Go consumers select module versions like @v2.0.6; the repository tag is golang/v2.0.6. ```bash go get github.com/Zonastery/bursar/golang/v2 ``` -------------------------------- ### Run the web service Source: https://github.com/zonastery/bursar/blob/main/web/README.md Starts the bursar-web HTTP server. Requires Go 1.26+. ```bash go run ./cmd/bursar-web ``` -------------------------------- ### JavaScript SDK setup with Bun Source: https://github.com/zonastery/bursar/blob/main/CONTRIBUTING.md Install JavaScript SDK dependencies using Bun 1.4.4. The published SDK is ESM for Node.js 22 or newer; Bun is only for development. ```bash cd bursar/javascript bun ci # Bun 1.4.4; installs the committed bun.lock ``` -------------------------------- ### Use Dodo provider factory (Python) Source: https://github.com/zonastery/bursar/blob/main/docs/docs/guides/subscription-integration.mdx Replaces the Stripe client and factory with Dodo. Requires installing `bursar[postgres,dodo]`. The factory is lazy and receives Bursar's event sink. `DODO_SETUP_PRODUCT_ID` is the Dodo subscription product for mandate-only payment-method setup when no active subscription exists. ```python from typing import Literal from dodopayments import AsyncDodoPayments from bursar.providers import DodoProvider dodo_environment: Literal["live_mode", "test_mode"] = ( "live_mode" if os.environ.get("DODO_PAYMENTS_ENVIRONMENT") == "live_mode" else "test_mode" ) dodo = AsyncDodoPayments( bearer_token=os.environ["DODO_PAYMENTS_API_KEY"], environment=dodo_environment, ) def dodo_factory(context): return DodoProvider( get_client=lambda: dodo, webhook_key=os.environ["DODO_PAYMENTS_WEBHOOK_KEY"], setup_product_id=os.environ["DODO_SETUP_PRODUCT_ID"], event_sink=context.event_sink, ) ``` -------------------------------- ### Go SDK setup and test Source: https://github.com/zonastery/bursar/blob/main/CONTRIBUTING.md Download Go module dependencies and run tests. The Go SDK supports Go 1.25 and 1.26 and is a versioned source module. ```bash cd golang go mod download go test ./... ``` -------------------------------- ### Install Bursar and run migration Source: https://github.com/zonastery/bursar/blob/main/docs/docs/quickstart.mdx Installs the Python package with PostgreSQL support and runs the migration CLI. Requires Python 3.12-3.15 and PostgreSQL 16+ with pg_partman and pg_jsonschema. Use a development database; the command is idempotent and fails if an applied migration file changed. ```bash python -m pip install "bursar[postgres]" export BURSAR_MIGRATION_DATABASE_URL="postgresql://bursar_migrator:password@localhost:5432/bursar" bursar migrate ``` -------------------------------- ### Setup sandbox and user for quota tutorial Source: https://github.com/zonastery/bursar/blob/main/samples/python/notebooks/06_quotas_and_spend_caps.ipynb Initializes a temporary Postgres store with standard config, creates user USER_ADA on the pro plan with 200 credits, and defines a completion metric helper. Run this before quota operations. ```python from decimal import Decimal from bursar.metrics import UsageMetrics from shared import cleanup, base_config, publish_config, start_postgres_store, USER_ADA def completion(output=Decimal(500)): return UsageMetrics( operation="completion", measures={ "input_tokens": Decimal(1000), "output_tokens": output, "cache_read_tokens": Decimal(200), }, dimensions={"model": "gpt-4o"}, ) store, pgdata = start_postgres_store() bursar = publish_config(store, base_config()) bursar.accounts.on_account_created(USER_ADA, "signup") bursar.credits.set_user_plan(USER_ADA, "pro") bursar.credits.add_credits(USER_ADA, Decimal("200.00"), entry_type="purchase", idempotency_key="topup") print("ready") ``` -------------------------------- ### Create account and add credits (Python) Source: https://github.com/zonastery/bursar/blob/main/docs/docs/quickstart.mdx Python example for creating an account and adding credits with an idempotency key. The signup event assigns the 'standard' plan from 'catalog.default_plan'. The purchase appends one ledger entry and creates spendable credit in the 'purchased' bucket. ```python from decimal import Decimal account_id = "11111111-1111-4111-8111-111111111111" bursar.accounts.on_account_created( account_id, event_key="signup:11111111", ) grant = bursar.credits.add_credits( account_id, Decimal("100.000000"), entry_type="purchase", idempotency_key="purchase:quickstart:11111111", ) print(grant.entry_id, grant.new_balance) ``` -------------------------------- ### Start throwaway Postgres store and print store info Source: https://github.com/zonastery/bursar/blob/main/samples/python/notebooks/00_why_bursar_and_setup.ipynb Launches a throwaway Postgres cluster, runs schema migrations, and provisions a tenant. The second return value is the data directory that must be cleaned up at the end of the notebook. ```python # Everything in this series runs against a throwaway Postgres cluster. # start_postgres_store() launches one, runs the bursar schema migrations, # and provisions a tenant; the second return value is the data directory # that must be cleaned up at the end of the notebook. from decimal import Decimal from shared import start_postgres_store, cleanup, base_config, publish_config, USER_ADA store, pgdata = start_postgres_store() print("store type:", type(store).__name__) print("tenant id:", store.tenant_id) ``` -------------------------------- ### Install the bursar skill globally Source: https://github.com/zonastery/bursar/blob/main/docs/docs/agent-skills.mdx Installs the `bursar` skill globally with the `--global` flag. Use only when every project on the workstation should use the skill. ```bash npx skills add zonastery/bursar@bursar --global ``` -------------------------------- ### Function examples Source: https://github.com/zonastery/bursar/blob/main/docs/docs/concepts/expressions.mdx Table of supported functions with arity, description, and example expressions. Wrong arity or `percentile`'s `p` outside 0..100 raises `ExpressionError`. ```text ceil(input_tokens * 0.001) ``` ```text floor(output_tokens / 1000) ``` ```text round(input_tokens * 0.001) ``` ```text min(cost_a, cost_b) ``` ```text max(0, model_cost - allowance) ``` ```text if(input_tokens > 1000, cost_a, cost_b) ``` ```text tier(input_tokens, 10000, 5, 100000, 10, 20) ``` ```text clamp(tool_calls, 0, 100) ``` ```text percentile(95, model_cost_1, model_cost_2) ``` -------------------------------- ### Install and run migrations with bursar migrate Source: https://github.com/zonastery/bursar/blob/main/README.md Installs the bursar Python package with PostgreSQL support, sets the migration database URL, and runs the migration CLI. Safe to re-run because it records checksums. Use a dedicated migration principal, not runtime credentials. ```bash python -m pip install "bursar[postgres]" export BURSAR_MIGRATION_DATABASE_URL=postgresql://bursar_migrator@db.example.com/bursar bursar migrate ``` -------------------------------- ### RTK Command Chain Example Source: https://github.com/zonastery/bursar/blob/main/AGENTS.md In command chains, prefix each segment with rtk. This example shows chaining git add and git commit with rtk. ```bash rtk git add . && rtk git commit -m "msg" ``` -------------------------------- ### Install and run migrations with Python CLI Source: https://github.com/zonastery/bursar/blob/main/docs/docs/javascript-api/stores.mdx Install the bursar package with PostgreSQL support and run the bundled migrations using the Python CLI before constructing any store. Set the BURSAR_MIGRATION_DATABASE_URL environment variable to the database connection string. ```bash pip install "bursar[postgres]" BURSAR_MIGRATION_DATABASE_URL=postgres://... bursar migrate ``` -------------------------------- ### Create Bursar runtime with storage adapters (Python) Source: https://github.com/zonastery/bursar/blob/main/docs/docs/guides/storage-backends.mdx Composes the runtime with Postgres, optional ClickHouse and S3 adapters, and outbox options. Requires database URLs, tenant ID, and provider environment. Call start() with load_catalog=True to initialize. ```python from bursar.storage import BursarRuntimeOptions, BursarRuntimeStartOptions, create_bursar_runtime runtime = create_bursar_runtime( BursarRuntimeOptions( postgres=database_url, operator_postgres=operator_database_url, tenant_id=tenant_id, provider_environment="test", clickhouse=clickhouse_options, s3=s3_options, outbox=outbox_options, ) ) runtime.start(BursarRuntimeStartOptions(load_catalog=True)) ``` -------------------------------- ### Create account and add credits (TypeScript) Source: https://github.com/zonastery/bursar/blob/main/docs/docs/quickstart.mdx TypeScript example for creating an account and adding credits with an idempotency key. The signup event assigns the 'standard' plan from 'catalog.default_plan'. The purchase appends one ledger entry and creates spendable credit in the 'purchased' bucket. ```typescript const accountId = "11111111-1111-4111-8111-111111111111"; await bursar.accounts.onAccountCreated({ accountId, eventKey: "signup:11111111", }); const grant = await bursar.credits.addCredits(accountId, "100.000000", { type: "purchase", idempotencyKey: "purchase:quickstart:11111111", }); console.log(grant.entryId, grant.newBalance); ``` -------------------------------- ### tier() example with comments Source: https://github.com/zonastery/bursar/blob/main/docs/docs/concepts/expressions.mdx Example of `tier()` function. Returns `r_i` for the first threshold where `value < t_i`, else `default`. Argument count must be even and at least 4. ```text tier(input_tokens, 10000, 5, 100000, 10, 20) # value < 10000 → 5 # value < 100000 → 10 # otherwise → 20 (default) ``` -------------------------------- ### Python SDK setup with uv Source: https://github.com/zonastery/bursar/blob/main/CONTRIBUTING.md Clone the repository and set up the Python SDK. Use `uv sync` for runtime dependencies, `uv sync --extra test` for test tooling, or `uv sync --group dev` for the full development group. ```bash git clone https://github.com/Zonastery/bursar.git cd bursar/python uv sync # runtime deps uv sync --extra test # ruff, pyright, pytest, testcontainers # or, for the full dev group (notebooks, psycopg2, etc.): uv sync --group dev ``` -------------------------------- ### Bootstrap a tenant with config using bursar tenant bootstrap Source: https://github.com/zonastery/bursar/blob/main/samples/python/notebooks/13_cli_and_deployment.ipynb Provisions a tenant and publishes its first config in one step. Validates the config file before provisioning, so a malformed document never leaves a tenant that cannot start. ```bash bursar tenant bootstrap promo pricing.prod.yaml --label "initial: standard rate card" # -> Tenant 3f6a2b7e-8c1d-4e9a-9f2b-7c0d5e1a3b4c bootstrapped successfully (config applied). ``` -------------------------------- ### Export, validate, and set config revisions with `bursar config` Source: https://github.com/zonastery/bursar/blob/main/samples/python/notebooks/13_cli_and_deployment.ipynb Recommended edit-publish loop: export the live revision, edit it, validate without a database, then publish with an audit label. Always start from a previously valid document. ```bash # 1. Export the live revision bursar config export 3 > current.json # 2. Edit it in your editor (or a script) # 3. Validate the edit - no database required bursar config validate current.json # 4. Publish the new revision with an audit label bursar config set current.json --label "change-43: sonnet-4.1 rates" ``` -------------------------------- ### Add credits, get balance, and deduct for a completion Source: https://github.com/zonastery/bursar/blob/main/samples/python/notebooks/00_why_bursar_and_setup.ipynb Shows adding a 50-credit purchase, reading the balance, and running one completion. The free plan's 10,000-credit monthly allowance absorbs the deduction while the purchased balance stays untouched. Uses UsageMetrics with token counts for a gpt-4o completion. ```python added = bursar.credits.add_credits( USER_ADA, Decimal("50"), entry_type="purchase", idempotency_key="setup:purchase:ada" ) print("added:", added.amount, "-> balance", added.new_balance) balance = bursar.credits.get_balance(USER_ADA) print("balance:", balance.balance, "| lifetime purchased:", balance.lifetime_purchased) # One gpt-4o completion: 1,000 input + 500 output + 200 cached tokens. from bursar.metrics import UsageMetrics deduction = bursar.credits.deduct( USER_ADA, UsageMetrics( operation="completion", measures={ "input_tokens": Decimal(1000), "output_tokens": Decimal(500), "cache_read_tokens": Decimal(200), }, dimensions={"model": "gpt-4o"}, ), idempotency_key="setup-001", ) print("charged:", deduction.amount, "| from allowance:", deduction.allowance_consumed) print("balance after:", deduction.balance_after) ``` -------------------------------- ### Create Bursar runtime with storage adapters (TypeScript) Source: https://github.com/zonastery/bursar/blob/main/docs/docs/guides/storage-backends.mdx Composes the runtime with Postgres, optional ClickHouse and S3 adapters, and outbox options. Requires database URLs, tenant ID, and provider environment. Await start() with loadCatalog: true to initialize. ```ts import { createBursarRuntime } from "@zonastery/bursar/node"; const runtime = await createBursarRuntime({ postgres: databaseUrl, operatorPostgres: operatorDatabaseUrl, tenantId, providerEnvironment: "test", clickhouse: clickhouseOptions, s3: s3Options, outbox: outboxOptions, }); await runtime.start({ loadCatalog: true }); ``` -------------------------------- ### Construct storage runtime with storageRuntime.NewBursarRuntime Source: https://github.com/zonastery/bursar/blob/main/docs/docs/go-api/index.mdx Use this to create a complete process runtime with the storage composition root. It accepts database URLs or caller-owned pools and keeps tenant-bound primary and unscoped operator connections distinct. The runtime validates the tenant UUID and optional slug, constructs the facade, recovery and maintenance handles, optional ClickHouse/S3 projections, and the outbox worker. Its Start method verifies identity and retries catalog loading; Health and State are race-safe local snapshots that never perform network or database I/O. ```go package main import ( "context" "log" "os" bursar "github.com/Zonastery/bursar/golang/v2" storageRuntime "github.com/Zonastery/bursar/golang/v2/storage/runtime" ) func main() { ctx := context.Background() runtime, err := storageRuntime.NewBursarRuntime(ctx, storageRuntime.Options{ TenantID: os.Getenv("BURSAR_TENANT_ID"), // UUID TenantSlug: os.Getenv("BURSAR_TENANT_SLUG"), ProviderEnvironment: bursar.ProviderEnvironmentTest, DatabaseURL: os.Getenv("DATABASE_URL"), OperatorDatabaseURL: os.Getenv("BURSAR_OPERATOR_DATABASE_URL"), }) if err != nil { log.Fatal(err) } if err := runtime.Start(ctx); err != nil { // Verifies identity and retries catalog loading. log.Fatal(err) } defer runtime.Close(context.Background()) if !runtime.Health(ctx).Ready { log.Fatal("Bursar runtime is not ready") } } ``` -------------------------------- ### Set up event emitter and subscribe to credit events Source: https://github.com/zonastery/bursar/blob/main/samples/python/notebooks/11_events.ipynb Initializes a PostgreSQL store, creates a CreditEventEmitter, registers a handler for various credit event types, and builds a Bursar instance with the emitter. The handler records each event's type and data, printing them. Requires completing the credit lifecycle and lease tutorials and starting the notebook server from samples/python/notebooks/. ```python import atexit from shared import start_postgres_store, cleanup, base_config, publish_config, USER_ADA from decimal import Decimal from bursar import Bursar from bursar.credits.events import CreditEventEmitter from bursar.credits.service_types import ReserveOptions from bursar.metrics import UsageMetrics store, pgdata = start_postgres_store() atexit.register(cleanup, pgdata) publish_config(store, base_config()) emitter = CreditEventEmitter() seen = [] def record(event): seen.append((event.type, event.data or {})) print(event.type, "-", event.data or {}) for event_type in [ "credits.plan_changed", "credits.added", "credits.deducted", "credits.deduct_failed", "credits.refunded", "credits.refund_failed", "credits.reserved", "credits.reservation_released", "credits.quota_threshold", ]: emitter.on(event_type, record) bursar = Bursar(credit_store=store, emitter=emitter) credits = bursar.credits bursar.accounts.on_account_created(USER_ADA, "acct_ada") print("events facade ready") ``` -------------------------------- ### Go SDK initialization Source: https://github.com/zonastery/bursar/blob/main/README.md Initializes a PostgresStore and Bursar SDK, loads the catalog, and closes the store. Requires Go 1.26+. ```go package main import ( "context" "log" "os" bursar "github.com/Zonastery/bursar/golang/v2" ) func main() { ctx := context.Background() store, err := bursar.NewPostgresStore(ctx, os.Getenv("DATABASE_URL"), bursar.PostgresStoreOptions{ TenantID: os.Getenv("BURSAR_TENANT_ID"), ProviderEnvironment: bursar.ProviderEnvironmentTest, }) if err != nil { log.Fatal(err) } defer store.Close() sdk, err := bursar.New(bursar.Options{CreditStore: store}) if err != nil { log.Fatal(err) } if err := sdk.LoadCatalog(ctx); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Use Dodo provider factory (TypeScript) Source: https://github.com/zonastery/bursar/blob/main/docs/docs/guides/subscription-integration.mdx Replaces the Stripe client and factory with Dodo. Requires installing `dodopayments`. The factory is lazy and receives Bursar's event sink. `DODO_SETUP_PRODUCT_ID` is the Dodo subscription product for mandate-only payment-method setup when no active subscription exists. ```ts import type { CommerceProviderFactory } from "@zonastery/bursar"; import { DodoProvider } from "@zonastery/bursar/providers/dodo"; import DodoPayments from "dodopayments"; const dodo = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY!, environment: process.env.DODO_PAYMENTS_ENVIRONMENT === "live_mode" ? "live_mode" : "test_mode", }); const dodoFactory: CommerceProviderFactory = (context) => new DodoProvider({ getClient: () => dodo, webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY!, setupProductId: process.env.DODO_SETUP_PRODUCT_ID!, eventSink: context.eventSink, }); ``` -------------------------------- ### Construct PostgresStore (Python) Source: https://github.com/zonastery/bursar/blob/main/docs/docs/guides/storage-backends.mdx Create a tenant-bound store. Pass the provisioned tenant UUID as a keyword argument and set provider_environment to "test". ```python store = PostgresStore( database_url, tenant_id=tenant_id, provider_environment="test", ) ``` -------------------------------- ### Summarize credits, plans, offers, and admission policies Source: https://github.com/zonastery/bursar/blob/main/samples/python/notebooks/01_first_pricing_config.ipynb Prints bucket priorities and default bucket, a summary of each plan (rank, rate card, operations, features, allowance, quotas, admission policy), sorted offer keys, and sorted admission policy keys. Use to review the product configuration for credits, plans, commerce, and admission. ```python print( "buckets:", {k: bucket["priority"] for k, bucket in config["credits"]["buckets"].items()}, "| default:", config["credits"]["default_bucket"], ) for key, plan in config["plans"].items(): summary = { "rank": plan["rank"], "rate_card": plan["rate_card"], "operations": plan["allowed_operations"], "features": plan.get("features", {}), "allowance": plan.get("credit_allowance", {}).get("amount"), "quotas": list(plan.get("quotas", {}).keys()), "admission_policy": plan.get("admission_policy"), } print(f"plan {key}:", summary) print("offers:", sorted(config["commerce"]["offers"].keys())) print("admission policies:", sorted(config["admission"]["policies"].keys())) ``` -------------------------------- ### Install @zonastery/bursar with npm Source: https://github.com/zonastery/bursar/blob/main/docs/docs/javascript-api/index.mdx Install the package. Requires Node.js 22 or newer; the package is ESM-only. ```bash npm install @zonastery/bursar pg ``` -------------------------------- ### Boolean operators examples Source: https://github.com/zonastery/bursar/blob/main/docs/docs/concepts/expressions.mdx Table of boolean operators with example expressions. `and`, `or`, and `not` are supported. Chained comparisons are not allowed; use explicit `and` form. ```text tool_calls > 0 and tool_calls <= 10 ``` ```text tool_calls == 0 or cache_read_tokens > 0 ``` ```text 5 if not (tool_calls > 10) else 10 ``` -------------------------------- ### Install the bursar skill at project scope Source: https://github.com/zonastery/bursar/blob/main/docs/docs/agent-skills.mdx Installs the `bursar` skill at project scope using the Skills CLI. Project scope allows team review and versioning with the application. Use `--global` only when every project on the workstation should use the skill. ```bash npx skills add zonastery/bursar@bursar ``` -------------------------------- ### Create tenant and set environment variables Source: https://github.com/zonastery/bursar/blob/main/README.md Creates a tenant with a specific ID and sets the application database URL and tenant ID environment variables. Provision bursar_ops and bursar_app as separate SET-only members of bursar_operator and bursar_client respectively. ```bash export BURSAR_OPERATOR_DATABASE_URL=postgresql://bursar_ops@db.example.com/bursar bursar tenant create acme --id 018f7f5f-7b4a-7000-8000-000000000001 export DATABASE_URL=postgresql://bursar_app@db.example.com/bursar export BURSAR_TENANT_ID=018f7f5f-7b4a-7000-8000-000000000001 ``` -------------------------------- ### Install Bursar Python plugin for Google ADK Source: https://github.com/zonastery/bursar/blob/main/docs/docs/guides/google-adk.mdx Install the Bursar Python integration with the Google ADK and PostgreSQL extras. The Python integration is tested against Google ADK 2.7 and is an optional extra, so applications that do not use ADK do not install ADK transitively. ```bash pip install "bursar[google-adk,postgres]" ``` -------------------------------- ### Install bursar with Postgres backend Source: https://github.com/zonastery/bursar/blob/main/docs/docs/python-api/index.mdx Install the bursar Python SDK with the Postgres backend using pip. Requires Python 3.12 through 3.15. ```bash pip install "bursar[postgres]" ``` -------------------------------- ### Invalid config JSON error example Source: https://github.com/zonastery/bursar/blob/main/samples/python/notebooks/13_cli_and_deployment.ipynb Example of structured validator errors from --json, matching ConfigError.errors() shapes. ```json { "valid": false, "errors": [ { "type": "decimal_string", "loc": ["pricing", "rate_cards", "standard", "operations", "completion", "rules", 0, "charge", "sum", "components", 0, "per_unit", "rate"], "msg": "must be a base-10 decimal string", "input": 0.0025 } ] } ``` -------------------------------- ### Record usage and deduct credits (Go) Source: https://github.com/zonastery/bursar/blob/main/docs/docs/quickstart.mdx Calculates a quote for 800 input tokens, then deducts credits using the idempotency key 'request:quickstart:0195'. Logs the charge amount and entry ID. Reusing the same idempotency key with the same payload returns the original result without a new ledger entry; a different payload returns a conflict. ```go engine, err := sdk.Catalog.Engine() if err != nil { log.Fatal(err) } quote, err := engine.Calculate(bursar.UsageMetrics{ Operation: "completion", Measures: map[string]bursar.Amount{"input_tokens": bursar.MustAmount("800")}, Dimensions: map[string]any{"model": "example-model"}, }) if err != nil { log.Fatal(err) } charge, err := sdk.Credits.Deduct(ctx, accountID, quote.Total, bursar.DeductWithAllowanceOptions{ Operation: "completion", IdempotencyKey: "request:quickstart:0195", OperationUsageOptions: bursar.OperationUsageOptions{ Measures: map[string]bursar.Amount{"input_tokens": bursar.MustAmount("800")}, Dimensions: map[string]any{"model": "example-model"}, }, }) if err != nil { log.Fatal(err) } log.Println(charge.Amount, charge.EntryID) ``` -------------------------------- ### Set environment variables and manage config versions Source: https://github.com/zonastery/bursar/blob/main/docs/docs/cli.mdx Requires DATABASE_URL, BURSAR_TENANT_ID, and BURSAR_PROVIDER_ENVIRONMENT. Commands publish, activate, list, pin, apply, export, and diff catalog versions. ```bash export DATABASE_URL=postgresql://bursar_app@db.example.com/bursar export BURSAR_TENANT_ID=018f7f5f-7b4a-7000-8000-000000000001 export BURSAR_PROVIDER_ENVIRONMENT=test bursar config set ./pricing.yaml # publish + activate a new version (--label, --rollout) bursar config get # print the active version as JSON bursar config list # list all versions (* = active) bursar config activate 3 # switch the active version (--rollout) bursar config pin # hold one current assignment on its revision bursar config pin --unpin # remove that hold bursar config apply-due --limit 100 # apply due renewal-effective changes bursar config export 3 # dump one version as JSON bursar config diff 2 3 # unified diff between two versions ``` -------------------------------- ### Install Bursar with Stripe and Postgres (Python) Source: https://github.com/zonastery/bursar/blob/main/docs/docs/guides/subscription-integration.mdx Install the Bursar Python SDK with PostgreSQL and Stripe extras. Use this before integrating a payment provider. ```bash python -m pip install "bursar[postgres,stripe]" ``` -------------------------------- ### Install Bursar with Stripe and Postgres (TypeScript) Source: https://github.com/zonastery/bursar/blob/main/docs/docs/guides/subscription-integration.mdx Install the Bursar TypeScript SDK along with PostgreSQL and Stripe dependencies. Use this before integrating a payment provider. ```bash npm install @zonastery/bursar pg stripe ``` -------------------------------- ### Create a tenant with bursar tenant create Source: https://github.com/zonastery/bursar/blob/main/samples/python/notebooks/13_cli_and_deployment.ipynb Provisions a tenant and prints its UUID. Use --id to pin a specific UUID and --display-name for an optional display name. ```bash bursar tenant create acme --display-name "Acme Production" # -> 3f6a2b7e-8c1d-4e9a-9f2b-7c0d5e1a3b4c ``` -------------------------------- ### Install Bursar OpenTelemetry extra (Python) Source: https://github.com/zonastery/bursar/blob/main/docs/docs/guides/opentelemetry.mdx Install Bursar's API-only extra for Python. This adds the OpenTelemetry API without configuring an SDK or exporter. ```bash pip install "bursar[opentelemetry]" ``` -------------------------------- ### Install Bursar and OpenTelemetry API (JavaScript) Source: https://github.com/zonastery/bursar/blob/main/docs/docs/guides/opentelemetry.mdx Install the optional peer alongside Bursar for JavaScript. This adds the OpenTelemetry API without configuring an SDK or exporter. ```bash npm install @zonastery/bursar @opentelemetry/api ``` -------------------------------- ### Construct PostgresStore (TypeScript) Source: https://github.com/zonastery/bursar/blob/main/docs/docs/guides/storage-backends.mdx Create a tenant-bound store. Pass the provisioned tenant UUID in the constructor options object and set providerEnvironment to "test". ```typescript const store = new PostgresStore({ postgres: databaseUrl, tenantId, providerEnvironment: "test", }); ``` -------------------------------- ### Comparison operators examples Source: https://github.com/zonastery/bursar/blob/main/docs/docs/concepts/expressions.mdx Table of comparison operators with example expressions. `in` / `not in` are substring containment checks (both sides coerced to strings). Chained comparisons (`a < b < c`) are not supported and raise `ExpressionError` at parse time. ```text output_tokens == 0 ``` ```text output_tokens != 0 ``` ```text output_tokens < 1000 ``` ```text output_tokens <= 1000 ``` ```text output_tokens > 1000 ``` ```text output_tokens >= 1000 ``` ```text "gpt-4" in model ``` ```text "batch" not in job_type ``` -------------------------------- ### percentile() examples Source: https://github.com/zonastery/bursar/blob/main/docs/docs/concepts/expressions.mdx Examples of `percentile()` function. Sorts values and computes p-th percentile via linear interpolation. Requires at least 2 arguments; `p` outside 0..100 raises `ExpressionError`. ```text percentile(50, input_tokens, output_tokens, tool_calls) # median of 3 values ``` ```text percentile(0, a, b, c) # min ``` ```text percentile(100, a, b, c) # max ``` -------------------------------- ### Install Bursar Python SDK with PostgreSQL support Source: https://github.com/zonastery/bursar/blob/main/python/README.md Install the SDK with the recommended PostgreSQL extra. Other extras include stripe, dodo, s3, google-adk, and test. ```bash python -m pip install "bursar[postgres]" ``` -------------------------------- ### Validate and publish pricing configuration Source: https://github.com/zonastery/bursar/blob/main/docs/docs/quickstart.mdx Validates the pricing file, sets it as the active configuration with a label, and lists configurations. Run after saving pricing.yaml. ```bash bursar config validate pricing.yaml bursar config set pricing.yaml --label "quickstart" bursar config list ``` -------------------------------- ### Go: Construct Bursar facade with PostgresStore Source: https://github.com/zonastery/bursar/blob/main/docs/docs/quickstart.mdx Reads DATABASE_URL, BURSAR_TENANT_ID, and BURSAR_PROVIDER_ENVIRONMENT from the environment, then binds a PostgresStore to the tenant and constructs the Bursar facade. Keep the store tenant-bound for its full lifetime; never set a session-scoped tenant value on a shared connection pool. ```go package main import ( "context" "log" "os" bursar "github.com/Zonastery/bursar/golang/v2" ) func main() { ctx := context.Background() store, err := bursar.NewPostgresStore(ctx, os.Getenv("DATABASE_URL"), bursar.PostgresStoreOptions{ TenantID: os.Getenv("BURSAR_TENANT_ID"), ProviderEnvironment: bursar.ProviderEnvironmentTest, }) if err != nil { log.Fatal(err) } defer store.Close() sdk, err := bursar.New(bursar.Options{CreditStore: store}) if err != nil { log.Fatal(err) } if err := sdk.LoadCatalog(ctx); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Get active config with bursar config get Source: https://github.com/zonastery/bursar/blob/main/samples/python/notebooks/13_cli_and_deployment.ipynb Prints the canonical JSON of the active revision: the revision id, version number, and full config document (money as decimal strings, defaults filled in). ```bash bursar config get ``` -------------------------------- ### Set up Bursar facade (Python) Source: https://github.com/zonastery/bursar/blob/main/docs/docs/guides/credit-lifecycle.mdx Publishes a validated configuration and binds a PostgresStore facade for the tenant. Requires a database URL, tenant ID, and a base configuration from shared module. ```python from bursar import Bursar, PostgresStore from shared import USER_ADA, base_config, publish_config bursar = publish_config( PostgresStore( database_url, tenant_id=tenant_id, provider_environment="test", ), base_config(), ) user_id = USER_ADA ``` -------------------------------- ### PricingEngine.from_dict Source: https://github.com/zonastery/bursar/blob/main/docs/docs/python-api/pricing-engine.mdx Creates a PricingEngine instance from a canonical config document. Validates the configuration and raises ConfigError on invalid input. ```APIDOC ## PricingEngine.from_dict ### Description Creates a PricingEngine instance from a canonical config document. Validates the configuration and raises ConfigError on invalid input. ### Method Constructor ### Parameters - **config_dict** (dict) - Required - The canonical configuration document. ### Returns - **PricingEngine** - An engine instance. ### Exceptions - **ConfigError** - Raised if the configuration is invalid (unknown fields, undeclared measures/dimensions, invalid matcher types, unsafe cross-references). ### Request Example ```python from bursar import PricingEngine engine = PricingEngine.from_dict(config_dict) ``` ```