Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. π₯
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
fix(api): gate /v2/agent credits after free-request consumption and cap runs at the balance (#5192)
Rakshith Ramprakashf05786e664db
diff --git a/apps/api/src/__tests__/routes/check-credits-middleware.test.ts b/apps/api/src/__tests__/routes/check-credits-middleware.test.tsindex 585b1976c..ed9b425f5 100644--- a/apps/api/src/__tests__/routes/check-credits-middleware.test.ts+++ b/apps/api/src/__tests__/routes/check-credits-middleware.test.ts@@ -252,6 +252,21 @@ describe("checkCreditsMiddleware β Autumn overage handling", () => {});});+describe("checkCreditsMiddleware β /agent", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("leaves the credit decision to the agent controller", async () => {+ const req = buildReq({ path: "/agent", body: { prompt: "x" } });+ const { res, nextCalled } = await runMiddleware(req);++ expect(nextCalled).toBe(true);+ expect(res.status).not.toHaveBeenCalled();+ expect(checkCreditsMock).not.toHaveBeenCalled();+ });+});+describe("checkCreditsMiddleware β agent-key denials", () => {beforeEach(() => {vi.clearAllMocks();diff --git a/apps/api/src/controllers/v2/__tests__/agent-credit-gate.test.ts b/apps/api/src/controllers/v2/__tests__/agent-credit-gate.test.tsnew file mode 100644index 000000000..0ceab23c4--- /dev/null+++ b/apps/api/src/controllers/v2/__tests__/agent-credit-gate.test.ts@@ -0,0 +1,169 @@+vi.mock("../../../lib/logger", () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+}));+vi.mock("../../../services/autumn/autumn.service", () => ({+ autumnService: { checkCredits: vi.fn(), hasAutoTopUp: vi.fn() },+}));++import { gateAgentCredits } from "../agent-credit-gate";+import { autumnService } from "../../../services/autumn/autumn.service";++const checkCredits = vi.mocked(autumnService.checkCredits);+const hasAutoTopUp = vi.mocked(autumnService.hasAutoTopUp);++const gate = (requestedMaxCredits?: number, orgId: string | null = "org-1") =>+ gateAgentCredits({+ teamId: "team-1",+ orgId,+ apiKeyId: 7,+ requestedMaxCredits,+ });++const asRequested = (maxCredits?: number) => ({+ allowed: true,+ maxCredits,+ stopOnInsufficientCredits: false,+});++describe("gateAgentCredits", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ hasAutoTopUp.mockResolvedValue(false);+ });++ it("blocks a team without overage at a zero balance", async () => {+ checkCredits.mockResolvedValueOnce({ allowed: false, remaining: 0 });++ expect(await gate()).toEqual({ allowed: false, balance: 0 });+ expect(checkCredits).toHaveBeenCalledTimes(1);+ expect(checkCredits).toHaveBeenCalledWith(+ expect.objectContaining({+ teamId: "team-1",+ orgId: "org-1",+ value: 20,+ properties: expect.objectContaining({ apiKeyId: 7 }),+ }),+ );+ });++ it("blocks a team below the minimum and reports its balance", async () => {+ checkCredits.mockResolvedValueOnce({ allowed: false, remaining: 12 });++ expect(await gate(5000)).toEqual({ allowed: false, balance: 12 });+ });++ it("caps maxCredits at the balance for a team without overage", async () => {+ checkCredits+ .mockResolvedValueOnce({ allowed: true, remaining: 640.6 })+ .mockResolvedValueOnce({ allowed: false, remaining: 640.6 });++ expect(await gate()).toEqual({+ allowed: true,+ maxCredits: 640,+ stopOnInsufficientCredits: true,+ });+ expect(checkCredits).toHaveBeenLastCalledWith(+ expect.objectContaining({ value: 660 }),+ );+ });++ it("never starts a capped run with a cap of zero or below", async () => {+ checkCredits+ .mockResolvedValueOnce({ allowed: true, remaining: 0 })+ .mockResolvedValueOnce({ allowed: false, remaining: 0 });++ expect(await gate()).toEqual({ allowed: false, balance: 0 });+ });++ it("keeps the default cap when the balance is above it", async () => {+ checkCredits+ .mockResolvedValueOnce({ allowed: true, remaining: 10000 })+ .mockResolvedValueOnce({ allowed: false, remaining: 10000 });++ expect(await gate()).toEqual({+ allowed: true,+ maxCredits: 2500,+ stopOnInsufficientCredits: true,+ });+ });++ it("caps a requested maxCredits above the balance", async () => {+ checkCredits+ .mockResolvedValueOnce({ allowed: true, remaining: 1000 })+ .mockResolvedValueOnce({ allowed: false, remaining: 1000 });++ expect(await gate(8000)).toMatchObject({+ maxCredits: 1000,+ stopOnInsufficientCredits: true,+ });+ });++ it("keeps a requested maxCredits below the balance but still stops at zero", async () => {+ checkCredits+ .mockResolvedValueOnce({ allowed: true, remaining: 1000 })+ .mockResolvedValueOnce({ allowed: false, remaining: 1000 });++ expect(await gate(300)).toEqual({+ allowed: true,+ maxCredits: 300,+ stopOnInsufficientCredits: true,+ });+ });++ it("passes an overage team through as requested", async () => {+ checkCredits+ .mockResolvedValueOnce({ allowed: true, remaining: 100 })+ .mockResolvedValueOnce({ allowed: true, remaining: 100 });++ expect(await gate(8000)).toEqual(asRequested(8000));+ expect(hasAutoTopUp).not.toHaveBeenCalled();+ });++ it("passes an overage team already below zero through as requested", async () => {+ checkCredits+ .mockResolvedValueOnce({ allowed: true, remaining: -5000 })+ .mockResolvedValueOnce({ allowed: true, remaining: -5000 });++ expect(await gate()).toEqual(asRequested(undefined));+ expect(checkCredits).toHaveBeenLastCalledWith(+ expect.objectContaining({ value: 20 }),+ );+ });++ it("passes an auto-recharge team through as requested", async () => {+ checkCredits+ .mockResolvedValueOnce({ allowed: true, remaining: 100 })+ .mockResolvedValueOnce({ allowed: false, remaining: 100 });+ hasAutoTopUp.mockResolvedValueOnce(true);++ expect(await gate(4000)).toEqual(asRequested(4000));+ expect(hasAutoTopUp).toHaveBeenCalledWith("org-1");+ });++ it("fails open when the first check can't be answered", async () => {+ checkCredits.mockResolvedValueOnce(null);++ expect(await gate(4000)).toEqual(asRequested(4000));+ expect(checkCredits).toHaveBeenCalledTimes(1);+ });++ it("fails open when the overage check can't be answered", async () => {+ checkCredits+ .mockResolvedValueOnce({ allowed: true, remaining: 100 })+ .mockResolvedValueOnce(null);++ expect(await gate(4000)).toEqual(asRequested(4000));+ });++ it("fails open on an allowed answer with no usable balance", async () => {+ checkCredits.mockResolvedValueOnce({ allowed: true, remaining: Infinity });++ expect(await gate()).toEqual(asRequested(undefined));+ expect(checkCredits).toHaveBeenCalledTimes(1);+ });++ it("fails open without an org", async () => {+ expect(await gate(4000, null)).toEqual(asRequested(4000));+ expect(checkCredits).not.toHaveBeenCalled();+ });+});diff --git a/apps/api/src/controllers/v2/__tests__/agent-credits.test.ts b/apps/api/src/controllers/v2/__tests__/agent-credits.test.tsnew file mode 100644index 000000000..dd83e9832--- /dev/null+++ b/apps/api/src/controllers/v2/__tests__/agent-credits.test.ts@@ -0,0 +1,176 @@+vi.mock("../../../lib/crawl-regex", async () => {+ const { z } = await import("zod");+ return {+ addPathRegexIssues: vi.fn(),+ pathPatternsSchema: z.array(z.string()),+ };+});+import { agentController } from "../agent";+vi.mock("../../../lib/logger", () => {+ const logger = {+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ child: vi.fn(),+ };+ logger.child.mockReturnValue(logger);+ return { logger };+});+vi.mock("../../../services/logging/log_job", () => ({ logRequest: vi.fn() }));+vi.mock("../../../lib/external-request-id", () => ({+ externalRequestId: () => undefined,+}));+vi.mock("../../../config", () => ({+ config: {+ EXTRACT_V3_BETA_URL: "https://agent.example",+ USE_DB_AUTHENTICATION: true,+ AGENT_INTEROP_SECRET: "test",+ },+}));+vi.mock("../../../db/rpc", () => ({ agentConsumeFreeRequestIfLeft: vi.fn() }));+vi.mock("../../../services/autumn/autumn.service", () => ({+ autumnService: { checkCredits: vi.fn(), hasAutoTopUp: vi.fn() },+}));+vi.mock("../../../lib/threat-protection/request", () => ({+ resolveThreatProtection: vi.fn().mockResolvedValue({}),+ checkUrlsAgainstThreatPolicy: vi.fn(),+}));+vi.mock("../../../lib/scrape-billing", () => ({+ calculateThreatScanCredits: vi.fn(),+}));+vi.mock("../../../services/billing/credit_billing", () => ({+ billTeam: vi.fn(),+}));+vi.mock("../../../lib/siem-logging", () => ({+ emitRejectedScrapeActivityEvents: vi.fn(),+}));+vi.mock("../agent-thread", () => ({+ fetchAgentThread: vi.fn(),+ threadErrorFor: vi.fn(),+}));++import { agentConsumeFreeRequestIfLeft } from "../../../db/rpc";+import { autumnService } from "../../../services/autumn/autumn.service";++const consumeFreeRequest = vi.mocked(agentConsumeFreeRequestIfLeft);+const checkCredits = vi.mocked(autumnService.checkCredits);+const hasAutoTopUp = vi.mocked(autumnService.hasAutoTopUp);++async function startAgent(body: Record<string, unknown>) {+ const req = {+ body: { prompt: "Find government contracts", ...body },+ auth: { team_id: "team-test", org_id: "org-test" },+ acuc: {+ flags: {},+ api_key: "test-key",+ api_key_id: 3,+ },+ };+ const res = { status: vi.fn().mockReturnThis(), json: vi.fn() };+ await agentController(req as any, res as any);+ const call = vi.mocked(fetch).mock.calls[0];+ return {+ res,+ sent: call ? JSON.parse(call[1]!.body as string) : undefined,+ };+}++describe("agent credit gate", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ hasAutoTopUp.mockResolvedValue(false);+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({ status: 200, json: async () => ({}) }),+ );+ });+ afterEach(() => vi.unstubAllGlobals());++ it("checks credits for maxCredits above the free cap, even with free requests left", async () => {+ consumeFreeRequest.mockResolvedValue([{ consumed: true }]);+ checkCredits.mockResolvedValueOnce({ allowed: false, remaining: 0 });++ const { res, sent } = await startAgent({ maxCredits: 5000 });++ expect(consumeFreeRequest).not.toHaveBeenCalled();+ expect(checkCredits).toHaveBeenCalled();+ expect(res.status).toHaveBeenCalledWith(402);+ expect(sent).toBeUndefined();+ });++ it("refuses a paid run at a zero balance with the balance in the error", async () => {+ consumeFreeRequest.mockResolvedValue([{ consumed: false }]);+ checkCredits.mockResolvedValueOnce({ allowed: false, remaining: 0 });++ const { res, sent } = await startAgent({});++ expect(res.status).toHaveBeenCalledWith(402);+ const payload = res.json.mock.calls[0][0];+ expect(payload.success).toBe(false);+ expect(payload.error).toContain("balance is 0 credits");+ expect(payload.error).toContain("Add credits");+ expect(sent).toBeUndefined();+ });++ it("still starts a free daily run at a balance of zero or below", async () => {+ consumeFreeRequest.mockResolvedValue([{ consumed: true }]);+ checkCredits.mockResolvedValue({ allowed: false, remaining: 0 });++ const { res, sent } = await startAgent({});++ expect(checkCredits).not.toHaveBeenCalled();+ expect(res.status).toHaveBeenCalledWith(200);+ expect(sent.isFreeRequest).toBe(true);+ expect(sent.stopOnInsufficientCredits).toBeUndefined();+ });++ it("sends the capped maxCredits and the stop flag for a team without overage", async () => {+ consumeFreeRequest.mockResolvedValue([{ consumed: false }]);+ checkCredits+ .mockResolvedValueOnce({ allowed: true, remaining: 700 })+ .mockResolvedValueOnce({ allowed: false, remaining: 700 });++ const { res, sent } = await startAgent({ maxCredits: 2000 });++ expect(res.status).toHaveBeenCalledWith(200);+ expect(sent.isFreeRequest).toBe(false);+ expect(sent.maxCredits).toBe(700);+ expect(sent.stopOnInsufficientCredits).toBe(true);+ });++ it("leaves an overage team's request untouched", async () => {+ consumeFreeRequest.mockResolvedValue([{ consumed: false }]);+ checkCredits.mockResolvedValue({ allowed: true, remaining: 50 });++ const { res, sent } = await startAgent({ maxCredits: 9000 });++ expect(res.status).toHaveBeenCalledWith(200);+ expect(sent.maxCredits).toBe(9000);+ expect(sent.stopOnInsufficientCredits).toBeUndefined();+ });++ it("leaves an auto-recharge team's request untouched", async () => {+ consumeFreeRequest.mockResolvedValue([{ consumed: false }]);+ checkCredits+ .mockResolvedValueOnce({ allowed: true, remaining: 50 })+ .mockResolvedValueOnce({ allowed: false, remaining: 50 });+ hasAutoTopUp.mockResolvedValueOnce(true);++ const { res, sent } = await startAgent({ maxCredits: 9000 });++ expect(res.status).toHaveBeenCalledWith(200);+ expect(sent.maxCredits).toBe(9000);+ expect(sent.stopOnInsufficientCredits).toBeUndefined();+ });++ it("fails open when billing can't answer", async () => {+ consumeFreeRequest.mockResolvedValue([{ consumed: false }]);+ checkCredits.mockResolvedValue(null);++ const { res, sent } = await startAgent({ maxCredits: 9000 });++ expect(res.status).toHaveBeenCalledWith(200);+ expect(sent.maxCredits).toBe(9000);+ expect(sent.stopOnInsufficientCredits).toBeUndefined();+ });+});diff --git a/apps/api/src/controllers/v2/__tests__/agent-rollout.test.ts b/apps/api/src/controllers/v2/__tests__/agent-rollout.test.tsindex 179ba2ea2..7ae496bcd 100644--- a/apps/api/src/controllers/v2/__tests__/agent-rollout.test.ts+++ b/apps/api/src/controllers/v2/__tests__/agent-rollout.test.ts@@ -23,6 +23,9 @@ vi.mock("../../../config", () => ({},}));vi.mock("../../../db/rpc", () => ({ agentConsumeFreeRequestIfLeft: vi.fn() }));+vi.mock("../../../services/autumn/autumn.service", () => ({+ autumnService: { checkCredits: vi.fn(), hasAutoTopUp: vi.fn() },+}));vi.mock("../../../lib/threat-protection/request", () => ({resolveThreatProtection: vi.fn().mockResolvedValue({}),checkUrlsAgainstThreatPolicy: vi.fn(),diff --git a/apps/api/src/controllers/v2/agent-credit-gate.ts b/apps/api/src/controllers/v2/agent-credit-gate.tsnew file mode 100644index 000000000..22c0e2cfe--- /dev/null+++ b/apps/api/src/controllers/v2/agent-credit-gate.ts@@ -0,0 +1,83 @@+import { autumnService } from "../../services/autumn/autumn.service";+import { logger } from "../../lib/logger";++export const AGENT_DEFAULT_MAX_CREDITS = 2500;+export const AGENT_MIN_CREDITS = 20;+export const CREDIT_CHECK_EXEMPT_TEAM_ID =+ "8c528896-7882-4587-a4b6-768b721b0b53";++export type AgentCreditGate =+ | { allowed: false; balance: number }+ | {+ allowed: true;+ maxCredits: number | undefined;+ stopOnInsufficientCredits: boolean;+ };++/**+ * Decides whether a paid agent run may start and how far it may spend.+ *+ * Autumn's `check` already applies each team's overage setting and spend+ * limit, so the gate learns whether a team can spend past its balance by+ * asking for a little more than that balance:+ *+ * - below the minimum: refused, as before.+ * - can spend past the balance (overage, unlimited): runs as requested.+ * - cannot, but has an auto top-up: runs as requested, as before.+ * - otherwise: `maxCredits` is capped at the balance, and the agent service+ * is told to stop the run if the balance runs out mid-flight.+ *+ * Fails open: whenever Autumn or firebill can't answer, the run starts as+ * requested.+ */+export async function gateAgentCredits({+ teamId,+ orgId,+ apiKeyId,+ requestedMaxCredits,+}: {+ teamId: string;+ orgId: string | null | undefined;+ apiKeyId: number | null;+ requestedMaxCredits: number | undefined;+}): Promise<AgentCreditGate> {+ const asRequested: AgentCreditGate = {+ allowed: true,+ maxCredits: requestedMaxCredits,+ stopOnInsufficientCredits: false,+ };+ if (!orgId || teamId === CREDIT_CHECK_EXEMPT_TEAM_ID) return asRequested;++ const check = (value: number, source: string) =>+ autumnService.checkCredits({+ teamId,+ orgId,+ value,+ properties: { source, path: "/agent", apiKeyId },+ });++ const minimum = await check(AGENT_MIN_CREDITS, "agentCreditGate");+ if (minimum === null) return asRequested;+ if (!minimum.allowed) return { allowed: false, balance: minimum.remaining };++ const balance = Math.floor(minimum.remaining);+ if (!Number.isFinite(balance)) return asRequested;+ const pastBalance = await check(+ Math.max(balance, 0) + AGENT_MIN_CREDITS,+ "agentCreditGate:overage",+ );+ if (pastBalance === null || pastBalance.allowed) return asRequested;+ if (await autumnService.hasAutoTopUp(orgId)) return asRequested;+ if (balance <= 0) return { allowed: false, balance };++ const requested = requestedMaxCredits ?? AGENT_DEFAULT_MAX_CREDITS;+ const maxCredits = Math.min(requested, balance);+ if (maxCredits < requested) {+ logger.info("Capping agent maxCredits at the team's balance", {+ teamId,+ requestedMaxCredits,+ maxCredits,+ });+ }+ return { allowed: true, maxCredits, stopOnInsufficientCredits: true };+}diff --git a/apps/api/src/controllers/v2/agent.ts b/apps/api/src/controllers/v2/agent.tsindex 906c58d90..8a2078d19 100644--- a/apps/api/src/controllers/v2/agent.ts+++ b/apps/api/src/controllers/v2/agent.ts@@ -22,6 +22,10 @@ import { calculateThreatScanCredits } from "../../lib/scrape-billing";import { billTeam } from "../../services/billing/credit_billing";import { emitRejectedScrapeActivityEvents } from "../../lib/siem-logging";import { fetchAgentThread, threadErrorFor } from "./agent-thread";+import {+ AGENT_DEFAULT_MAX_CREDITS,+ gateAgentCredits,+} from "./agent-credit-gate";export async function agentController(req: RequestWithAuth<{}, AgentResponse, AgentRequest>,@@ -179,9 +183,11 @@ export async function agentController(}}- // If maxCredits > 2500, skip free request consumption β this is always a paid request+ // A request above the free cap is always paid. Otherwise a free request is+ // consumed atomically here, and only a consumed one skips the credit gate.const highCreditRequest =- req.body.maxCredits !== undefined && req.body.maxCredits > 2500;+ req.body.maxCredits !== undefined &&+ req.body.maxCredits > AGENT_DEFAULT_MAX_CREDITS;let freeRequest: any;@@ -195,6 +201,28 @@ export async function agentController(? !!freeRequest?.[0]?.consumed: true;+ let maxCredits = req.body.maxCredits;+ let stopOnInsufficientCredits = false;+ if (!isFreeRequest) {+ const gate = await gateAgentCredits({+ teamId: req.auth.team_id,+ orgId: req.auth.org_id,+ apiKeyId: req.acuc?.api_key_id ?? null,+ requestedMaxCredits: req.body.maxCredits,+ });+ if (!gate.allowed) {+ logger.warn("Insufficient credits to start agent run", {+ balance: gate.balance,+ });+ return res.status(402).json({+ success: false,+ error: `Insufficient credits to start an agent run. Your team's credit balance is ${gate.balance} credits. Add credits at https://firecrawl.dev/pricing to continue.`,+ });+ }+ maxCredits = gate.maxCredits;+ stopOnInsufficientCredits = gate.stopOnInsufficientCredits;+ }+await logRequest({id: agentId,kind: "agent",@@ -226,7 +254,8 @@ export async function agentController(apiKeyId: req.acuc!.api_key_id ?? undefined,teamId: req.auth.team_id,isFreeRequest,- maxCredits: req.body.maxCredits ?? undefined,+ maxCredits: maxCredits ?? undefined,+ stopOnInsufficientCredits: stopOnInsufficientCredits || undefined,strictConstrainToURLs: req.body.strictConstrainToURLs ?? undefined,webhook: req.body.webhook ?? undefined,model: req.body.model,diff --git a/apps/api/src/db/rpc.ts b/apps/api/src/db/rpc.tsindex 3679e7506..a58beadce 100644--- a/apps/api/src/db/rpc.ts+++ b/apps/api/src/db/rpc.ts@@ -57,15 +57,6 @@ export function authCreditUsageChunkFromTeam();}-export function getAgentFreeRequestsLeft(- i_team_id: string,-): Promise<{ free_requests_left: number }[]> {- return execRows(- db,- sql`select * from get_agent_free_requests_left(i_team_id => ${i_team_id})`,- );-}-export function agentConsumeFreeRequestIfLeft(i_team_id: string,): Promise<{ consumed: boolean }[]> {diff --git a/apps/api/src/routes/shared.ts b/apps/api/src/routes/shared.tsindex a4a88619a..cc56a229c 100644--- a/apps/api/src/routes/shared.ts+++ b/apps/api/src/routes/shared.ts@@ -24,7 +24,7 @@ import { isSelfHosted } from "../lib/deployment";import { validate as isUuid } from "uuid";import { config } from "../config";-import { getAgentFreeRequestsLeft } from "../db/rpc";+import { CREDIT_CHECK_EXEMPT_TEAM_ID } from "../controllers/v2/agent-credit-gate";import {autumnService,CREDITS_FEATURE_ID,@@ -150,20 +150,10 @@ export function checkCreditsMiddleware(}}+ // The agent controller gates credits itself, after it has consumed a+ // free request: only a consumed one may skip the check.if (req.path.startsWith("/agent")) {- if (config.USE_DB_AUTHENTICATION) {- try {- const data = await getAgentFreeRequestsLeft(req.auth.team_id);- if (data?.[0]?.free_requests_left !== 0) {- return next();- }- } catch (freeRequestError) {- logger.warn("Failed to get agent free requests left", {- error: freeRequestError,- teamId: req.auth.team_id,- });- }- }+ return next();}const requestedCredits = minimum ?? 1;@@ -256,7 +246,7 @@ export function checkCreditsMiddleware();if (!res.headersSent &&- req.auth.team_id !== "8c528896-7882-4587-a4b6-768b721b0b53"+ req.auth.team_id !== CREDIT_CHECK_EXEMPT_TEAM_ID) {return res.status(402).json({success: false,diff --git a/apps/api/src/services/autumn/__tests__/autumn.service.test.ts b/apps/api/src/services/autumn/__tests__/autumn.service.test.tsindex 49e5bd5d6..e7217ccce 100644--- a/apps/api/src/services/autumn/__tests__/autumn.service.test.ts+++ b/apps/api/src/services/autumn/__tests__/autumn.service.test.ts@@ -823,6 +823,52 @@ describe("featureIdForBillingEndpoint", () => {// getTeamLimits (concurrency + rate-limit multiplier)// ---------------------------------------------------------------------------+describe("hasAutoTopUp", () => {+ const customer = (enabled: boolean, billingMethod?: string) => ({+ billingControls: {+ autoTopups: [+ { featureId: "CREDITS", enabled, threshold: 0, quantity: 1000 },+ ],+ },+ balances: {+ CREDITS: {+ breakdown: [+ { planId: "standard", price: null },+ ...(billingMethod+ ? [{ planId: "standard", price: { billingMethod } }]+ : []),+ ],+ },+ },+ });++ it("is true for an enabled top-up with a prepaid CREDITS item to buy", async () => {+ mockCustomerGet.mockResolvedValue(customer(true, "prepaid"));+ expect(await makeService().hasAutoTopUp("org-1")).toBe(true);+ expect(mockCustomerGet).toHaveBeenCalledWith({ customerId: "org-1" });+ });++ it("is false when the top-up is disabled", async () => {+ mockCustomerGet.mockResolvedValue(customer(false, "prepaid"));+ expect(await makeService().hasAutoTopUp("org-1")).toBe(false);+ });++ it("is false for an enabled top-up with nothing prepaid to buy (free plan)", async () => {+ mockCustomerGet.mockResolvedValue(customer(true));+ expect(await makeService().hasAutoTopUp("org-1")).toBe(false);+ });++ it("fails open (true) when Autumn errors", async () => {+ mockCustomerGet.mockRejectedValue(new Error("autumn down"));+ expect(await makeService().hasAutoTopUp("org-1")).toBe(true);+ });++ it("fails open (true) without an Autumn client", async () => {+ state.autumnClientRef = null;+ expect(await makeService().hasAutoTopUp("org-1")).toBe(true);+ });+});+describe("getTeamLimits", () => {const lowDefaults = {concurrency_limit: 2,diff --git a/apps/api/src/services/autumn/autumn.service.ts b/apps/api/src/services/autumn/autumn.service.tsindex b60c56d4f..e53ec5732 100644--- a/apps/api/src/services/autumn/autumn.service.ts+++ b/apps/api/src/services/autumn/autumn.service.ts@@ -565,6 +565,33 @@ export class AutumnService {}}+ /**+ * Whether the org has an auto top-up that can actually fire for CREDITS: it+ * is enabled, and the org holds a prepaid CREDITS item for it to buy. Autumn+ * enables the control on some free orgs, but a free plan has no prepaid item,+ * so nothing would ever be bought. Answers true when Autumn can't answer, so+ * callers fail open.+ */+ async hasAutoTopUp(orgId: string): Promise<boolean> {+ if (!autumnClient) return true;+ try {+ const customer = await autumnClient.customers.get({ customerId: orgId });+ const autoTopUp = customer.billingControls?.autoTopups?.some(+ topUp => topUp.featureId === CREDITS_FEATURE_ID && topUp.enabled,+ );+ const prepaid = customer.balances?.[CREDITS_FEATURE_ID]?.breakdown?.some(+ item => item.price?.billingMethod === "prepaid",+ );+ return !!autoTopUp && !!prepaid;+ } catch (error) {+ logger.warn("Autumn auto top-up lookup failed, failing open", {+ orgId,+ error,+ });+ return true;+ }+ }+/*** Attempts to reserve a team's credits in Autumn. See {@link LockCreditsResult}.*/diff --git a/apps/js-sdk/firecrawl/src/v2/types.ts b/apps/js-sdk/firecrawl/src/v2/types.tsindex d3ec5d097..02b0ec6d4 100644--- a/apps/js-sdk/firecrawl/src/v2/types.ts+++ b/apps/js-sdk/firecrawl/src/v2/types.ts@@ -300,7 +300,12 @@ export interface ScrapeOptions {}export type RedactPIIEntity =- "PERSON" | "EMAIL" | "PHONE" | "LOCATION" | "FINANCIAL" | "SECRET";+ | "PERSON"+ | "EMAIL"+ | "PHONE"+ | "LOCATION"+ | "FINANCIAL"+ | "SECRET";export interface RedactPIIOptions {/**@@ -347,7 +352,12 @@ export interface ThreatProtectionOptions {}export type ParseFileData =- Blob | File | Buffer | Uint8Array | ArrayBuffer | string;+ | Blob+ | File+ | Buffer+ | Uint8Array+ | ArrayBuffer+ | string;export interface ParseFile {data: ParseFileData;@@ -395,7 +405,11 @@ export interface WebhookConfig {// Agent webhook events differ from crawl: has 'action' and 'cancelled', no 'page'export type AgentWebhookEvent =- "started" | "action" | "completed" | "failed" | "cancelled";+ | "started"+ | "action"+ | "completed"+ | "failed"+ | "cancelled";export interface AgentWebhookConfig {url: string;@@ -516,7 +530,10 @@ export interface BrandingProfile {headerHeight?: string;footerHeight?: string;[key: string]:- number | string | Record<string, number | string | undefined> | undefined;+ | number+ | string+ | Record<string, number | string | undefined>+ | undefined;};tone?: {voice?: string;@@ -1014,7 +1031,10 @@ export interface SearchRequest {/** Compact by default; summary adds metadata, full includes contracts. */toolDetail?: "compact" | "summary" | "full";sources?: Array<- "web" | "news" | "images" | "alexandria"+ | "web"+ | "news"+ | "images"+ | "alexandria"| { type: "web" | "news" | "images" | "alexandria" }>;/**@@ -1265,7 +1285,9 @@ export interface MonitorSearchTarget {}export type MonitorTarget =- MonitorScrapeTarget | MonitorCrawlTarget | MonitorSearchTarget;+ | MonitorScrapeTarget+ | MonitorCrawlTarget+ | MonitorSearchTarget;export interface CreateMonitorRequest {name: string;@@ -1388,7 +1410,11 @@ export interface MonitorCheck {reservedCredits?: number | null;actualCredits?: number | null;billingStatus:- "not_applicable" | "reserved" | "confirmed" | "released" | "failed";+ | "not_applicable"+ | "reserved"+ | "confirmed"+ | "released"+ | "failed";summary: MonitorSummary;targetResults?: MonitorTargetResult[];notificationStatus?: unknown;@@ -1779,7 +1805,10 @@ export interface AgentListOptions {}export type AgentTraceAgentRole =- "orchestrator" | "subagent" | "browser" | "system";+ | "orchestrator"+ | "subagent"+ | "browser"+ | "system";export interface AgentTraceAgentIdentity {id: string;@@ -1792,6 +1821,7 @@ export interface AgentTraceError {code:| "cancelled"| "credit_limit_reached"+ | "insufficient_credits"| "parent_finished"| "refused"| "internal";@@ -1833,7 +1863,11 @@ export interface AgentTraceRunCancelRequestedEvent extends AgentTraceEventBase {export interface AgentTraceRunFinishedEvent extends AgentTraceEventBase {type: "run.finished";outcome:- "succeeded" | "failed" | "cancelled" | "refused" | "credit_limit_reached";+ | "succeeded"+ | "failed"+ | "cancelled"+ | "refused"+ | "credit_limit_reached";/** The canonical schema always writes this key (nullable), but older rows may omit it. */error?: AgentTraceError | null;}@@ -1850,12 +1884,14 @@ export interface AgentTraceAgentFinishedEvent extends AgentTraceEventBase {error?: AgentTraceError | null;}-export interface AgentTraceBrowserSessionStartedEvent extends AgentTraceEventBase {+export interface AgentTraceBrowserSessionStartedEvent+ extends AgentTraceEventBase {type: "browser.session.started";sessionId: string;}-export interface AgentTraceBrowserSessionFinishedEvent extends AgentTraceEventBase {+export interface AgentTraceBrowserSessionFinishedEvent+ extends AgentTraceEventBase {type: "browser.session.finished";sessionId: string;durationMs: number;@@ -2028,7 +2064,9 @@ export interface RequiresAction {url?: string;}-export function parseRequiresAction(value: unknown): RequiresAction | undefined {+export function parseRequiresAction(+ value: unknown,+): RequiresAction | undefined {if (!value || typeof value !== "object") return undefined;const record = value as Record<string, unknown>;if (typeof record.type !== "string") return undefined;diff --git a/apps/python-sdk/firecrawl/v2/types.py b/apps/python-sdk/firecrawl/v2/types.pyindex cacd179a7..846c84271 100644--- a/apps/python-sdk/firecrawl/v2/types.py+++ b/apps/python-sdk/firecrawl/v2/types.py@@ -1919,7 +1919,12 @@ class AgentTraceError(BaseModel):"""Structured error attached to terminal/error trace events."""code: Literal[- "cancelled", "credit_limit_reached", "parent_finished", "refused", "internal"+ "cancelled",+ "credit_limit_reached",+ "insufficient_credits",+ "parent_finished",+ "refused",+ "internal",]source: Literal["agent", "tool", "billing", "system"]retryable: bool