# Live demo: the Limitr engine in your browser

> The Limitr engine running live in your browser. Change prices, costs, limits, and modes, and watch usage, revenue, cost, and margin move call by call.

# Live demo

This is the real engine (`@formata/limitr`) running in your browser as WebAssembly, with a small policy of four
entitlements: AI tokens, seats, outcomes, and storage.

Each dot is a call. Dots that cross the line were allowed (`allow(...)` returned `true`) and were metered and
priced; the rest were denied by a limit. Change a price, a cost, a limit, its mode, or how often it resets, and the
next calls use the new policy. The charts show usage, denials, revenue, cost, and margin as they happen.

:::note
The controls change the policy directly, in your browser. With [Limitr Cloud](./tutorial/going-to-cloud.md), a
published policy change reaches every running engine the same way, in seconds.
:::

## Simulation
export const demoKinds = [
    { kind: 'tokens', label: 'AI Tokens', color: '#5b8dee', weight: 3, amountRange: [500, 4000] },
    { kind: 'seats', label: 'Seats', color: '#9b7ede', weight: 1, amountRange: [-1, 3] },
    { kind: 'outcomes', label: 'Outcomes', color: '#4dbbb0', weight: 2, amountRange: [1, 5] },
    { kind: 'storage', label: 'Storage (MB)', color: '#c9a227', weight: 2, amountRange: [1, 10] },
];
export const demoPolicy = `
policy: {
    credits: {
        token: { unit: 'token', price: { amount: 0.000004 }, overhead_cost: 0.000003, stof_units: 'int' }
        seat: { unit: 'seat', price: { amount: 5 }, overhead_cost: 0, stof_units: 'int' }
        outcome: { unit: 'outcome', price: { amount: 0.25 }, overhead_cost: 0.10, stof_units: 'int' }
        mb_storage: { unit: 'mb_storage', price: { amount: 0.003 }, overhead_cost: 0.001, stof_units: 'MB' }

        // Internal denial reporting
        denial: { stof_units: 'int' }
    }
    plans: {
        demo: {
            label: 'Demo Plan'
            entitlements: {
                tokens: { 
                    limit: { credit: 'token', mode: 'soft', value: 1000, minimum: 0, resets: true, reset_inc: 20s }
                }
                seats: {
                    limit: { credit: 'seat', mode: 'hard', value: 10, minimum: 0, resets: true, reset_inc: 60s }
                }
                outcomes: {
                    limit: { credit: 'outcome', mode: 'soft', value: 20, minimum: 0, resets: true, reset_inc: 10s }
                }
                storage: {
                    limit: { credit: 'mb_storage', mode: 'soft', value: 5MiB, minimum: 0, resets: true, reset_inc: 60s }
                }

                denials: {
                    limit: { credit: 'denial', mode: 'observe', resets: true, reset_inc: 1min }
                }
            }
        }
    }
}

#[main]
fn main() {
    self.policy.create_customer('demo', 'demo');
    
    // USD spend & overhead last 5 min observers - margin can be determined using both
    self.policy.add_customer_cap('demo', 0, id='usd_charged_observer', credit='usd',
        exchangeable=true, ignore_grants=true, overage_only=true, observe_only=true, overhead_cost=false, follow_decrements=false,
        resets=true, reset_inc=1min
    );
    self.policy.add_customer_cap('demo', 0, id='usd_overhead_observer', credit='usd',
        exchangeable=true, ignore_grants=true, overage_only=false, observe_only=true, overhead_cost=true, follow_decrements=false,
        resets=true, reset_inc=1min
    );
}

#[meter-limit]
fn usage_limit_hit(event: obj) {
    // we're just graphing all denials over time, and the meter is set to reset every 5 min anyways on the customer, so keeping it easy here
    self.policy.allow('demo', 'denials', 1);
}

// Set credit helpers for interactivity

// how much will the customer get charged?
fn set_credit_price(credit: str, amount: float) {
    const c = self.policy.credits.get(credit);
    if (c != null) c.price.amount = amount;
}

// how much do we get charged in overhead to deliver a credit?
fn set_credit_overhead(credit: str, amount: float) {
    const c = self.policy.credits.get(credit);
    if (c != null) c.overhead_cost = amount;
}

// Set entitlement helpers for interactivity

// 'hard' will block all overage, 'soft' will allow & bill for overage
fn set_entitlement_mode(entitlement: str, mode: str) {
    const ent = self.policy.plans.demo.entitlements.get(entitlement);
    if (ent != null) {
        ent.limit.mode = mode;
    }
}

// included value (not billed for)
fn set_entitlement_value(entitlement: str, value: float) {
    const ent = self.policy.plans.demo.entitlements.get(entitlement);
    if (ent != null) {
        ent.limit.value = value;
    }
}

// how long until meter resets to 0 (resets overage)
fn set_entitlement_reset_inc(entitlement: str, inc: float) {
    const ent = self.policy.plans.demo.entitlements.get(entitlement);
    if (ent != null) {
        ent.limit.reset_inc = inc;
    }
}`;

export function MonetizeFieldDemo() {
    const policyRef = useRef(undefined);
    const [ready, setReady] = useState(false);

    const onDecision = async (particle) => {
        const policy = policyRef.current;
        if (!policy) return false;
        try {
            return await policy.allow('demo', particle.kind, particle.amount);
        } catch {
            return false;
        }
    };

    const getCurrentCustomerChargedUSD = async () => {
        const policy = policyRef.current;
        if (!policy) return null;
        /*
            export interface LimitrCap {
                id: string;
                credit: string;
                value: number;
                exchangeable: boolean;
                ignore_grants: boolean;
                overage_only: boolean;
                observe_only: boolean;
                overhead_cost: boolean;
                follow_decrements: boolean;
                scope: string[] | null;
                meter_value: number;
                created_on: number;
                started: number | null;
                resets: boolean;
                reset_inc: number | null;
                reset_sch: string | null;
                last_reset: number | null;
                expires_on: number | null;
            }
        */
        const cap = await policy.customerCap('demo', 'usd_charged_observer');
        if (cap) {
            return cap.meter_value; // number
        }
        return null;
    };
    const getCurrentOverheadUSD = async () => {
        const policy = policyRef.current;
        if (!policy) return null;
        const cap = await policy.customerCap('demo', 'usd_overhead_observer');
        if (cap) {
            return cap.meter_value; // number
        }
        return null;
    };
    const margin = (charged, overhead) => charged > 0 ? Math.round((charged - overhead)/charged * 10000) / 100 : 0;
    const getCurrentTokens = async () => {
        const policy = policyRef.current;
        if (!policy) return null;
        return await policy.value('demo', 'tokens') ?? 0;
    };
    const getCurrentSeats = async () => {
        const policy = policyRef.current;
        if (!policy) return null;
        return await policy.value('demo', 'seats') ?? 0;
    };
    const getCurrentOutcomes = async () => {
        const policy = policyRef.current;
        if (!policy) return null;
        return await policy.value('demo', 'outcomes') ?? 0;
    };
    const getCurrentStorage = async () => {
        const policy = policyRef.current;
        if (!policy) return null;
        return await policy.value('demo', 'storage') ?? 0;
    };
    const getCurrentDenials = async () => {
        const policy = policyRef.current;
        if (!policy) return null;
        return await policy.value('demo', 'denials') ?? 0;
    };

    // CONSOLIDATED from 8 per-credit wrapper functions (setTokenPrice,
    // setSeatPrice, ... setStorageOverhead) into 2 generic ones — those 8
    // were each a thin wrapper around the same two already-generic Stof
    // functions (set_credit_price/set_credit_overhead), just with the
    // credit name hardcoded per function. Consolidating here so
    // UsageControls can drive all four kinds through one set of handlers
    // instead of needing kind-specific wiring — and so adding mode/
    // value/reset didn't mean writing 12 MORE near-identical wrappers on
    // top of the existing 8.
    //
    // kind (the entitlement name, e.g. 'tokens') and credit (e.g.
    // 'token') aren't the same string for every kind — confirmed against
    // the actual policy text before writing this, not assumed.
    const CREDIT_BY_KIND = { tokens: 'token', seats: 'seat', outcomes: 'outcome', storage: 'mb_storage' };

    const setKindPrice = async (kind, price) => {
        const policy = policyRef.current;
        if (!policy) return;
        const credit = CREDIT_BY_KIND[kind];
        if (!credit) return;
        await policy.doc.call('root.set_credit_price', credit, price);
    };
    const setKindOverhead = async (kind, overhead) => {
        const policy = policyRef.current;
        if (!policy) return;
        const credit = CREDIT_BY_KIND[kind];
        if (!credit) return;
        await policy.doc.call('root.set_credit_overhead', credit, overhead);
    };
    // Entitlement calls use `kind` directly (kind IS the entitlement
    // name), not the credit mapping above.
    const setKindLimitValue = async (kind, value) => {
        const policy = policyRef.current;
        if (!policy) return;
        await policy.doc.call('root.set_entitlement_value', kind, value);
    };
    const setKindLimitMode = async (kind, mode) => {
        const policy = policyRef.current;
        if (!policy) return;
        await policy.doc.call('root.set_entitlement_mode', kind, mode);
    };
    const setKindReset = async (kind, resetIncSeconds) => {
        const policy = policyRef.current;
        if (!policy) return;
        await policy.doc.call('root.set_entitlement_reset_inc', kind, resetIncSeconds);
    };

    // Seeds for UsageControls' inputs — there's no getter for price/
    // overhead/mode/reset_inc yet (only setters), so these have to be
    // copied from demoPolicy's own starting values by hand. If the
    // policy text above changes, this needs updating to match — nothing
    // detects drift between the two automatically.
    //
    // TWO REAL CAVEATS, not guesses papered over:
    //   - seats and storage both have `resets: false` with NO reset_inc
    //     in the policy at all — defaulted to 0 here. Editing the Reset
    //     control for either won't have a visible effect unless `resets`
    //     itself also gets turned on, which isn't a control this exposes.
    //   - storage's actual limit is `5MiB` (a Stof binary-mebibyte
    //     literal), not a plain number — defaulted to 5 assuming an
    //     MB-ish display matching demoKinds' own "Storage (MB)" label,
    //     but MiB and MB aren't the same unit (1 MiB ≈ 1.048576 MB) —
    //     worth a real check, not treated as exact here.
    const usageControlDefaults = {
        tokens: { price: 0.000004, overhead: 0.000003, limitValue: 1000, mode: 'soft', resetInc: 20 },
        seats: { price: 5, overhead: 0, limitValue: 10, mode: 'hard', resetInc: 60 },
        outcomes: { price: 0.25, overhead: 0.10, limitValue: 20, mode: 'soft', resetInc: 10 },
        storage: { price: 0.003, overhead: 0.001, limitValue: 5, mode: 'soft', resetInc: 60 },
    };

    const MAX_POINTS = 120;
    const [datasets, setDatasets] = useState({
        tokens: [],
        seats: [],
        outcomes: [],
        storage: [],
        denials: [],
        chargedUSD: [], // this is the "revenue over time" series
        overheadUSD: [],
        marginPct: [],
    });
    const push = (arr, v, t) => (v == null ? arr : [...arr.slice(-(MAX_POINTS - 1)), { t, v }]);

    useEffect(() => {
        let cancelled = false;

        const tick = async () => {
            const [tokens, seats, outcomes, storage, denials, chargedUSD, overheadUSD] =
                await Promise.all([
                    getCurrentTokens(),
                    getCurrentSeats(),
                    getCurrentOutcomes(),
                    getCurrentStorage(),
                    getCurrentDenials(),
                    getCurrentCustomerChargedUSD(),
                    getCurrentOverheadUSD(),
                ]);
            if (cancelled) return;

            const t = Date.now();
            const marginPct = chargedUSD != null && overheadUSD != null
                ? margin(chargedUSD, overheadUSD)
                : null;

            setDatasets((prev) => ({
                tokens: push(prev.tokens, tokens, t),
                seats: push(prev.seats, seats, t),
                outcomes: push(prev.outcomes, outcomes, t),
                storage: push(prev.storage, storage, t),
                denials: push(prev.denials, denials, t),
                chargedUSD: push(prev.chargedUSD, chargedUSD, t),
                overheadUSD: push(prev.overheadUSD, overheadUSD, t),
                marginPct: push(prev.marginPct, marginPct, t),
            }));
        };

        ensureStofReady()
            .then(() => runStof('', 'stof', { policyDoc: demoPolicy, policyDocFormat: 'stof', temp: false }))
            .then((result) => {
                if (cancelled) return;
                if (result.error || !result.policy) {
                    // Surfaced as a console error rather than a thrown
                    // exception — a broken demo policy shouldn't take the
                    // whole docs page down, just fail to show the field.
                    console.error('MonetizeFieldDemo: policy setup failed —', result.output);
                    return;
                }
                policyRef.current = result.policy;
                result.policy.addHandler('update_datasets_handler', (key, value) => {
                    const events = ['meter-overage', 'meter-reset', 'meter-changed', 'meter-limit'];
                    if (events.includes(key)) {
                        tick();
                    }
                });
                setReady(true);
            });
        return () => {
            cancelled = true;
        };
    }, []);

    if (!ready) {
        return Loading the runtime…;
    }

    return (
        <>
            <UsageDecisionField kinds={demoKinds} onDecision={onDecision} />
            <UsageControls
                kinds={demoKinds}
                initialValues={usageControlDefaults}
                onSetPrice={setKindPrice}
                onSetOverhead={setKindOverhead}
                onSetLimitValue={setKindLimitValue}
                onSetLimitMode={setKindLimitMode}
                onSetReset={setKindReset}
            />
            <UsageCurrentValues datasets={datasets} kinds={demoKinds} />
            <UsageChartPanel datasets={datasets} kinds={demoKinds} />
        </>
    );
}

<MonetizeFieldDemo />

---

## How it works

The demo is a small React app around the same package you'd install (`npm i @formata/limitr`), with Chart.js for the
charts.

1. **Load the policy** with `Limitr.new(policy)`, and create one customer on the `demo` plan.
2. **Every dot** carries an entitlement and an amount, and calls `allow('demo', entitlement, amount)` when it reaches
   the line. It continues if the answer is `true`.
3. **Revenue and cost** are counted by two `observe_only` [spend caps](./reference/spend-caps) in USD: one counts
   overage (what the customer is billed), the other counts cost (`overhead_cost: true`). They reset every minute.
   Margin is the difference. Prices, costs, and limits change while the demo runs, so these are never a simple
   usage times price.
4. **An event handler** (`meter-changed`, `meter-overage`, `meter-limit`, `meter-reset`) reads the meters and caps
   after every call and updates the charts.
5. **The controls** change the policy's prices, costs, limits, modes, and resets in place.

Dots come in four kinds. Higher weights appear more often, and each dot's amount is in its range:

```ts
const demoKinds = [
    { kind: 'tokens', label: 'AI Tokens', color: '#5b8dee', weight: 3, amountRange: [500, 4000] },
    { kind: 'seats', label: 'Seats', color: '#9b7ede', weight: 1, amountRange: [-1, 3] },
    { kind: 'outcomes', label: 'Outcomes', color: '#4dbbb0', weight: 2, amountRange: [1, 5] },
    { kind: 'storage', label: 'Storage (MB)', color: '#c9a227', weight: 2, amountRange: [1, 10] },
];
```

### The policy

One plan, with short periods so the charts move:

- **tokens**: $4 per million charged, $3 per million cost, 1,000 included every 20 seconds, soft (overage billed).
- **seats**: $5 a seat past the limit, a hard limit of 10, resets every minute.
- **outcomes**: $0.25 charged, $0.10 cost, 20 included every 10 seconds, soft.
- **storage**: $0.003 per MB charged, $0.001 cost, 5 MiB included, soft, resets every minute.
- **denials**: an `observe` limit that counts denied calls for the chart (you wouldn't need this in a real policy).

```stof
policy: {
    credits: {
        token: { unit: 'token', price: { amount: 0.000004 }, overhead_cost: 0.000003, stof_units: 'int' }
        seat: { unit: 'seat', price: { amount: 5 }, overhead_cost: 0, stof_units: 'int' }
        outcome: { unit: 'outcome', price: { amount: 0.25 }, overhead_cost: 0.10, stof_units: 'int' }
        mb_storage: { unit: 'mb_storage', price: { amount: 0.003 }, overhead_cost: 0.001, stof_units: 'MB' }
        denial: { stof_units: 'int' }
    }
    plans: {
        demo: {
            label: 'Demo Plan'
            entitlements: {
                tokens: { limit: { credit: 'token', mode: 'soft', value: 1000, minimum: 0, resets: true, reset_inc: 20s } }
                seats: { limit: { credit: 'seat', mode: 'hard', value: 10, minimum: 0, resets: true, reset_inc: 60s } }
                outcomes: { limit: { credit: 'outcome', mode: 'soft', value: 20, minimum: 0, resets: true, reset_inc: 10s } }
                storage: { limit: { credit: 'mb_storage', mode: 'soft', value: 5MiB, minimum: 0, resets: true, reset_inc: 60s } }
                denials: { limit: { credit: 'denial', mode: 'observe', resets: true, reset_inc: 1min } }
            }
        }
    }
}
```
