/**
 * Cloud-inference billing flow helpers.
 *
 * Wrap a single hosted-inference run in the Studiograph Cloud
 * reserve → settle/release lifecycle. Shared by every server route that
 * drives the agent (chat + quick capture + the import pipeline that calls
 * capture), so hosted inference is metered consistently — not just on chat.
 *
 * Semantics (unchanged from the original chat.ts implementation):
 *  - reserve: on failure, throw only when billing is REQUIRED; otherwise log
 *    and proceed unmetered (best-effort).
 *  - settle: report actual usage; release the reservation when there was no
 *    billable usage.
 *  - release: return an unsettled reservation (error/abort path).
 *
 * When Cloud billing isn't configured (self-hosted / non-managed), the client
 * is not configured: reserve() returns null and settle/release no-op, so local
 * behavior is unchanged.
 */
import { createInferenceUsageSummary, inferenceUsageToBillableCents, } from '../services/cloud-inference-billing.js';
import { log } from '../utils/log.js';
export async function reserveCloudInference(cloudBilling, agent, description) {
    try {
        const model = agent.getModelSelection();
        return await cloudBilling.reserve({
            estimatedCents: cloudBilling.estimateCents(),
            provider: model.provider,
            model: model.modelId,
            requestId: cloudBilling.nextRequestId('chat'),
            description,
        });
    }
    catch (err) {
        if (cloudBilling.isRequired())
            throw err;
        log.warn(`[cloud-billing] reservation skipped: ${err instanceof Error ? err.message : String(err)}`);
        return null;
    }
}
export async function settleCloudInference(cloudBilling, reservation, usage) {
    if (!reservation)
        return;
    const summary = usage ?? createInferenceUsageSummary();
    const actualCents = inferenceUsageToBillableCents(summary);
    try {
        if (actualCents === null) {
            await cloudBilling.release(reservation, 'No billable model usage was reported.');
            return;
        }
        await cloudBilling.settle(reservation, {
            actualCents,
            inputTokens: summary.inputTokens,
            outputTokens: summary.outputTokens,
            description: 'Settled hosted Studiograph inference.',
        });
    }
    catch (err) {
        if (cloudBilling.isRequired())
            throw err;
        log.warn(`[cloud-billing] settlement skipped: ${err instanceof Error ? err.message : String(err)}`);
    }
}
export async function releaseCloudInference(cloudBilling, reservation, reason) {
    if (!reservation)
        return;
    try {
        await cloudBilling.release(reservation, reason);
    }
    catch (err) {
        if (cloudBilling.isRequired())
            throw err;
        log.warn(`[cloud-billing] release skipped: ${err instanceof Error ? err.message : String(err)}`);
    }
}
//# sourceMappingURL=cloud-billing-flow.js.map