Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

feat(agent): accept exchange.onTermsRequired; type terms-required fields in gateway and SDKs (#4759)

Rakshith Ramprakashc144f0591e38
diff --git a/apps/api/src/__tests__/snips/v2/agent-thread.test.ts b/apps/api/src/__tests__/snips/v2/agent-thread.test.ts
index b19bbf288..66fc7dd57 100644
--- a/apps/api/src/__tests__/snips/v2/agent-thread.test.ts
+++ b/apps/api/src/__tests__/snips/v2/agent-thread.test.ts
@@ -132,6 +132,21 @@ describe("Agent thread parameter validation", () => {
scrapeTimeout,
);
+ it(
+ "rejects an unknown exchange.onTermsRequired",
+ async () => {
+ const response = await agentRaw({
+ urls: [TEST_SUITE_WEBSITE],
+ prompt: "What does this page offer?",
+ exchange: { onTermsRequired: "fail" },
+ });
+
+ expect(response.statusCode).toBe(400);
+ expect(response.body.success).toBe(false);
+ },
+ scrapeTimeout,
+ );
+
it(
"rejects an unknown mode",
async () => {
diff --git a/apps/api/src/controllers/v2/__tests__/agent-status.test.ts b/apps/api/src/controllers/v2/__tests__/agent-status.test.ts
index 284a29691..8b32257c4 100644
--- a/apps/api/src/controllers/v2/__tests__/agent-status.test.ts
+++ b/apps/api/src/controllers/v2/__tests__/agent-status.test.ts
@@ -283,3 +283,173 @@ describe("agentRequestSchema model and effort resolution", () => {
).toThrow();
});
});
+
+describe("agentRequestSchema exchange.onTermsRequired", () => {
+ const base = { prompt: "Find the key business contact at exa.ai" };
+
+ it.each(["skip", "ask"] as const)(
+ "forwards onTermsRequired %s unchanged",
+ onTermsRequired => {
+ const parsed = agentRequestSchema.parse({
+ ...base,
+ exchange: { onTermsRequired },
+ });
+
+ expect(parsed.exchange).toEqual({ onTermsRequired });
+ },
+ );
+
+ it("leaves onTermsRequired unset when omitted so the thread inherits it", () => {
+ const parsed = agentRequestSchema.parse({
+ ...base,
+ exchange: { requireApproval: true },
+ });
+
+ expect(parsed.exchange).toEqual({ requireApproval: true });
+ expect(parsed.exchange?.onTermsRequired).toBeUndefined();
+ });
+
+ it("accepts onTermsRequired alongside an approve continuation", () => {
+ const approve = {
+ approvalId: "0199aaaa-0000-7000-8000-000000000000",
+ callIds: ["apollo"],
+ };
+ const parsed = agentRequestSchema.parse({
+ ...base,
+ exchange: { onTermsRequired: "ask", approve },
+ });
+
+ expect(parsed.exchange).toEqual({ onTermsRequired: "ask", approve });
+ });
+
+ it("rejects decline.callIds: a terms offer is declined as a whole", () => {
+ expect(
+ agentRequestSchema.safeParse({
+ ...base,
+ exchange: {
+ decline: {
+ approvalId: "0199aaaa-0000-7000-8000-000000000000",
+ callIds: ["apollo"],
+ },
+ },
+ }).success,
+ ).toBe(false);
+ });
+
+ it.each(["fail", "accept", "auto", "", true])(
+ "rejects onTermsRequired %s",
+ onTermsRequired => {
+ expect(
+ agentRequestSchema.safeParse({
+ ...base,
+ exchange: { onTermsRequired },
+ }).success,
+ ).toBe(false);
+ },
+ );
+
+ it("still rejects unknown exchange fields", () => {
+ expect(
+ agentRequestSchema.safeParse({
+ ...base,
+ exchange: { onTermsRequired: "ask", autoAcceptTerms: true },
+ }).success,
+ ).toBe(false);
+ });
+});
+
+describe("agentStatusController terms-required passthrough", () => {
+ const req = {
+ params: { jobId: "job-123" },
+ auth: { team_id: "team-123" },
+ } as RequestWithAuth<{ jobId: string }, any, any>;
+
+ it("returns skippedProviders, requiresAction and a terms pending approval unchanged", async () => {
+ const approvalId = "0199aaaa-0000-7000-8000-000000000000";
+ const exchange = {
+ enabled: true,
+ requireApproval: false,
+ onTermsRequired: "ask",
+ paidCalls: 0,
+ creditsUsed: null,
+ skippedProviders: [
+ {
+ provider: "apollo",
+ name: "Apollo",
+ capability: "people/search",
+ adds: "verified work emails and direct phone numbers",
+ reason: "terms_required",
+ version: "F-1.0.0",
+ termsUrl: "https://www.firecrawl.dev/app/alexandria/apollo",
+ },
+ ],
+ requiresAction: {
+ type: "accept_terms",
+ approvalId,
+ providers: [
+ {
+ provider: "apollo",
+ name: "Apollo",
+ capability: "people/search",
+ version: "F-1.0.0",
+ digest: null,
+ url: "https://www.firecrawl.dev/app/alexandria/apollo",
+ show: {
+ provider: "firecrawl",
+ capability: "terms/show",
+ options: { provider: "apollo" },
+ },
+ accept: {
+ provider: "firecrawl",
+ capability: "terms/accept",
+ options: {
+ provider: "apollo",
+ version: "F-1.0.0",
+ digest: null,
+ confirmed: true,
+ },
+ },
+ },
+ ],
+ },
+ };
+ const pendingApproval = {
+ id: approvalId,
+ kind: "terms",
+ reason: "Apollo could add verified work emails.",
+ calls: [],
+ terms: [
+ {
+ provider: "apollo",
+ name: "Apollo",
+ version: "F-1.0.0",
+ digest: null,
+ url: "https://www.firecrawl.dev/app/alexandria/apollo",
+ },
+ ],
+ resolution: null,
+ };
+ (getAgentJobAccess as Mock).mockResolvedValue({
+ teamId: "team-123",
+ expiresAtMs: Date.now() + 60_000,
+ });
+ (getExtractV3AgentStatus as Mock).mockResolvedValue({
+ id: "job-123",
+ success: true,
+ status: "success",
+ model: "spark-2",
+ exchange,
+ pendingApproval,
+ });
+
+ const res = {
+ status: vi.fn().mockReturnThis(),
+ json: vi.fn(),
+ } as unknown as Response;
+ await agentStatusController(req, res);
+
+ const body = (res.json as Mock).mock.calls[0][0];
+ expect(body.exchange).toEqual(exchange);
+ expect(body.pendingApproval).toEqual(pendingApproval);
+ });
+});
diff --git a/apps/api/src/controllers/v2/types.ts b/apps/api/src/controllers/v2/types.ts
index 88ecc7bd1..515a5ed7a 100644
--- a/apps/api/src/controllers/v2/types.ts
+++ b/apps/api/src/controllers/v2/types.ts
@@ -1061,6 +1061,11 @@ const agentWebhookSchema = createWebhookSchema([
// Forwarded verbatim to the agent service, which owns every default and the
// per-thread inheritance rules; the gateway only validates the shape.
+// The one list of onTermsRequired modes: the request schema and the response
+// summary type both derive from it.
+const AGENT_ON_TERMS_REQUIRED = ["skip", "ask"] as const;
+type AgentOnTermsRequired = (typeof AGENT_ON_TERMS_REQUIRED)[number];
+
const agentExchangeSchema = z.strictObject({
enabled: z.boolean().optional(),
toolkits: z.array(z.string()).optional(),
@@ -1078,6 +1083,13 @@ const agentExchangeSchema = z.strictObject({
approvalId: z.string().uuid(),
})
.optional(),
+ // What to do when a provider the agent would use needs data terms the team
+ // has not accepted: "skip" (the agent service's default) or "ask".
+ // Gated providers are never called in any mode, and there is deliberately
+ // no auto-accept: terms are only accepted by a human-authorized
+ // terms/accept or in the dashboard. Omitted on a follow-up turn means the
+ // previous turn's value.
+ onTermsRequired: z.enum(AGENT_ON_TERMS_REQUIRED).optional(),
});
export const agentRequestSchema = z
@@ -1647,9 +1659,39 @@ export type AgentSuggestion = {
prompt: string;
};
-export type AgentPendingApproval = {
+// A provider the agent would have used but could not, because the team has
+// not accepted its data terms.
+type AgentTermsGate = {
+ provider: string;
+ name: string;
+ logo?: string;
+ capability?: string;
+ // What it would have added, in the agent's words.
+ adds?: string;
+ // The gating agreement version and document digest terms/accept needs.
+ // digest is null when the catalog published none; terms/show returns it.
+ version: string;
+ digest: string | null;
+ // Where a person accepts the terms in the dashboard.
+ url: string;
+};
+
+type AgentPendingApprovalBase = {
id: string;
reason: string;
+ resolution: null | {
+ approved: boolean;
+ // Calls approved. Ignored on terms offers.
+ callIds: string[];
+ always: boolean;
+ byRunId: string;
+ };
+};
+
+// Paid calls waiting for approval. `kind` is absent on items written before
+// terms offers existed.
+type AgentPendingCallsApproval = AgentPendingApprovalBase & {
+ kind?: "calls";
calls: {
id: string;
provider: string;
@@ -1658,23 +1700,82 @@ export type AgentPendingApproval = {
more?: Record<string, unknown>[];
creditsEstimate: number | null;
}[];
- resolution: null | {
- approved: boolean;
- callIds: string[];
- always: boolean;
- byRunId: string;
- };
+ terms?: never;
+};
+
+// Providers whose data terms need accepting ("ask" mode). `calls`
+// stays empty so clients reading only the calls shape see nothing to run.
+type AgentPendingTermsApproval = AgentPendingApprovalBase & {
+ kind: "terms";
+ calls: [];
+ terms: AgentTermsGate[];
};
+export type AgentPendingApproval =
+ | AgentPendingCallsApproval
+ | AgentPendingTermsApproval;
+
// What a run did with Exchange, as the agent service reports it. `toolkits` and
// `requireApproval` are what the run resolved to after thread inheritance, so
// they describe the run rather than echoing the request.
+type AgentSkippedProvider = {
+ provider: string;
+ name: string;
+ capability?: string;
+ adds?: string;
+ reason: "terms_required";
+ version: string;
+ termsUrl: string;
+};
+
+// The Exchange calls a calling agent makes to accept a provider's terms once
+// its user has explicitly agreed. The agent service never executes them.
+type AgentTermsRequiredAction = {
+ type: "accept_terms";
+ // The `terms` pending approval that answers this: accept the terms, then
+ // continue the thread with `exchange.approve: { approvalId }` (or decline).
+ approvalId: string;
+ providers: {
+ provider: string;
+ name: string;
+ capability?: string;
+ adds?: string;
+ version: string;
+ // null when the catalog published no digest; terms/show returns it.
+ digest: string | null;
+ url: string;
+ show: {
+ provider: "firecrawl";
+ capability: "terms/show";
+ options: { provider: string };
+ };
+ accept: {
+ provider: "firecrawl";
+ capability: "terms/accept";
+ options: {
+ provider: string;
+ version: string;
+ // null when the catalog published no digest; terms/show returns it.
+ digest: string | null;
+ confirmed: true;
+ };
+ };
+ }[];
+};
+
export type AgentExchangeSummary = {
enabled: boolean;
toolkits?: string[];
requireApproval?: boolean;
+ onTermsRequired?: AgentOnTermsRequired;
paidCalls: number;
creditsUsed: number | null;
+ // The terms fields below (and onTermsRequired) appear only when the agent
+ // service's terms gate is on for the thread; it is rolling out.
+ // Gated providers that would have helped and were not used. Any mode.
+ skippedProviders?: AgentSkippedProvider[];
+ // "ask" mode, when a terms offer ended the turn.
+ requiresAction?: AgentTermsRequiredAction;
};
export type AgentResponse =
diff --git a/apps/api/src/lib/agent-hints.ts b/apps/api/src/lib/agent-hints.ts
index 448dd8aa0..26e9e36ce 100644
--- a/apps/api/src/lib/agent-hints.ts
+++ b/apps/api/src/lib/agent-hints.ts
@@ -8,7 +8,7 @@ export interface AgentHintContext {
canUseInteract?: boolean;
}
-export const AGENT_HINT_LOW_CREDIT_THRESHOLD = 100;
+const AGENT_HINT_LOW_CREDIT_THRESHOLD = 100;
const SEARCH_CLUSTER_MIN_RESULTS = 4;
const SEARCH_CLUSTER_MIN_ORIGIN_RESULTS = 3;
const SEARCH_CLUSTER_MIN_SHARE = 0.75;
diff --git a/apps/js-sdk/firecrawl/src/__tests__/unit/v2/agent-thread.unit.test.ts b/apps/js-sdk/firecrawl/src/__tests__/unit/v2/agent-thread.unit.test.ts
index b635be6bd..6a334ea47 100644
--- a/apps/js-sdk/firecrawl/src/__tests__/unit/v2/agent-thread.unit.test.ts
+++ b/apps/js-sdk/firecrawl/src/__tests__/unit/v2/agent-thread.unit.test.ts
@@ -161,4 +161,126 @@ describe("v2.agent threads unit", () => {
"/v2/agent/threads/thread-1?includeData=true",
);
});
+ test("startAgent forwards exchange.onTermsRequired and a terms approve", async () => {
+ const post = okPost();
+ const exchange = {
+ onTermsRequired: "ask" as const,
+ approve: { approvalId: "0199aaaa-0000-7000-8000-000000000000" },
+ };
+
+ await startAgent({ post } as any, {
+ prompt: "Continue",
+ threadId: "thread-1",
+ exchange,
+ });
+
+ expect(post).toHaveBeenCalledWith("/v2/agent", {
+ prompt: "Continue",
+ threadId: "thread-1",
+ exchange,
+ });
+ });
+
+ test("startAgent forwards exchange.onTermsRequired skip", async () => {
+ const post = okPost();
+
+ await startAgent({ post } as any, {
+ prompt: "Find the key business contact at exa.ai",
+ exchange: { onTermsRequired: "skip" },
+ });
+
+ expect(post).toHaveBeenCalledWith("/v2/agent", {
+ prompt: "Find the key business contact at exa.ai",
+ exchange: { onTermsRequired: "skip" },
+ });
+ });
+
+ test("getAgentStatus parses skippedProviders, requiresAction and a terms approval", async () => {
+ const approvalId = "0199aaaa-0000-7000-8000-000000000000";
+ const get = jest.fn().mockResolvedValue({
+ status: 200,
+ data: {
+ success: true,
+ status: "completed",
+ data: null,
+ model: "spark-2",
+ expiresAt: "2026-09-02T00:00:00.000Z",
+ exchange: {
+ enabled: true,
+ onTermsRequired: "ask",
+ paidCalls: 0,
+ creditsUsed: null,
+ skippedProviders: [
+ {
+ provider: "apollo",
+ name: "Apollo",
+ capability: "people/search",
+ adds: "verified work emails",
+ reason: "terms_required",
+ version: "F-1.0.0",
+ termsUrl: "https://www.firecrawl.dev/app/alexandria/apollo",
+ },
+ ],
+ requiresAction: {
+ type: "accept_terms",
+ approvalId,
+ providers: [
+ {
+ provider: "apollo",
+ name: "Apollo",
+ version: "F-1.0.0",
+ digest: null,
+ url: "https://www.firecrawl.dev/app/alexandria/apollo",
+ show: {
+ provider: "firecrawl",
+ capability: "terms/show",
+ options: { provider: "apollo" },
+ },
+ accept: {
+ provider: "firecrawl",
+ capability: "terms/accept",
+ options: {
+ provider: "apollo",
+ version: "F-1.0.0",
+ digest: null,
+ confirmed: true,
+ },
+ },
+ },
+ ],
+ },
+ },
+ pendingApproval: {
+ id: approvalId,
+ kind: "terms",
+ reason: "Apollo could add verified work emails.",
+ calls: [],
+ terms: [
+ {
+ provider: "apollo",
+ name: "Apollo",
+ version: "F-1.0.0",
+ digest: null,
+ url: "https://www.firecrawl.dev/app/alexandria/apollo",
+ },
+ ],
+ resolution: null,
+ },
+ },
+ });
+
+ const status = await getAgentStatus({ get } as any, "agent-job");
+
+ expect(status.exchange!.onTermsRequired).toBe("ask");
+ expect(status.exchange!.skippedProviders![0].reason).toBe("terms_required");
+ const action = status.exchange!.requiresAction!;
+ expect(action.approvalId).toBe(approvalId);
+ expect(action.providers[0].accept.capability).toBe("terms/accept");
+ expect(action.providers[0].accept.options.digest).toBeNull();
+ const pending = status.pendingApproval!;
+ expect(pending.kind).toBe("terms");
+ if (pending.kind !== "terms") throw new Error("expected a terms approval");
+ expect(pending.calls).toEqual([]);
+ expect(pending.terms[0].provider).toBe("apollo");
+ });
});
diff --git a/apps/js-sdk/firecrawl/src/v2/types.ts b/apps/js-sdk/firecrawl/src/v2/types.ts
index fc60719ce..b048701ed 100644
--- a/apps/js-sdk/firecrawl/src/v2/types.ts
+++ b/apps/js-sdk/firecrawl/src/v2/types.ts
@@ -1453,9 +1453,83 @@ export interface AgentExchangeOptions {
toolkits?: string[];
maxCalls?: number;
requireApproval?: boolean;
- /** Answers a pendingApproval from the previous turn of the thread. */
+ /**
+ * Answers a pendingApproval from the previous turn of the thread. A `terms`
+ * approval is accepted or declined as a whole: `callIds` and `always` are
+ * ignored on it.
+ */
approve?: { approvalId: string; callIds?: string[]; always?: boolean };
decline?: { approvalId: string };
+ /**
+ * What to do when a provider the agent would use needs data terms the team
+ * has not accepted. Gated providers are never called in any mode:
+ * - "skip" (server default): answer with accepted providers only and list
+ * the gated ones in `exchange.skippedProviders`.
+ * - "ask": the same, plus `exchange.requiresAction` and a `terms`
+ * pendingApproval. Get your user's explicit consent, call terms/accept,
+ * then continue the thread with `approve: { approvalId }`.
+ * Terms gating is rolling out: until it is on for a thread, none of the
+ * terms fields appear. There is no auto-accept mode. Omitted on a follow-up turn inherits the
+ * previous turn's value.
+ */
+ onTermsRequired?: AgentOnTermsRequired;
+}
+
+export type AgentOnTermsRequired = "skip" | "ask";
+
+/** A gated provider the run would have used but did not. */
+export interface AgentSkippedProvider {
+ provider: string;
+ name: string;
+ capability?: string;
+ /** What it would have added, in the agent's words. */
+ adds?: string;
+ reason: "terms_required";
+ /** The gating terms version. */
+ version: string;
+ /** Where a person accepts the terms in the dashboard. */
+ termsUrl: string;
+}
+
+/**
+ * The exact Exchange calls to view and accept a provider's terms. Nothing here
+ * is executed for you, and terms/accept must only be called after the user
+ * has explicitly agreed to that provider's terms.
+ */
+export interface AgentTermsRequiredAction {
+ type: "accept_terms";
+ /**
+ * The `terms` pendingApproval that answers this. After the user agrees and
+ * terms/accept succeeds, continue the thread with
+ * `exchange.approve: { approvalId }`, or refuse with `decline`.
+ */
+ approvalId: string;
+ providers: {
+ provider: string;
+ name: string;
+ capability?: string;
+ adds?: string;
+ version: string;
+ /** null when the catalog published no digest; terms/show returns it. */
+ digest: string | null;
+ url: string;
+ show: {
+ provider: "firecrawl";
+ capability: "terms/show";
+ options: { provider: string };
+ };
+ accept: {
+ provider: "firecrawl";
+ capability: "terms/accept";
+ options: {
+ provider: string;
+ version: string;
+ /** null when the catalog published no digest; terms/show returns it. */
+ digest: string | null;
+ confirmed: true;
+ };
+ };
+ }[];
}
/** Per-run summary reported on a status response. */
@@ -1464,8 +1538,26 @@ export interface AgentExchangeSummary {
/** What the run resolved to after thread inheritance, not what it requested. */
toolkits?: string[];
requireApproval?: boolean;
+ onTermsRequired?: AgentOnTermsRequired;
paidCalls: number;
creditsUsed: number | null;
+ /** Gated providers that would have helped and were not used. Any mode. */
+ skippedProviders?: AgentSkippedProvider[];
+ /** "ask" mode, when a terms offer ended the turn. */
+ requiresAction?: AgentTermsRequiredAction;
+}
+
+/** A provider in a `terms` pendingApproval. */
+export interface AgentTermsGate {
+ provider: string;
+ name: string;
+ logo?: string;
+ capability?: string;
+ adds?: string;
+ version: string;
+ /** null when the catalog published no digest; terms/show returns it. */
+ digest: string | null;
+ url: string;
}
/** A follow-up the agent offers for the next turn of the thread. */
@@ -1474,26 +1566,52 @@ export interface AgentSuggestion {
prompt: string;
}
-/** A turn that ended waiting for the caller to allow or refuse paid calls. */
-export interface PendingApproval {
+/** A paid call a `calls` pendingApproval is holding back. */
+export interface PendingApprovalCall {
+ id: string;
+ provider: string;
+ capability: string;
+ input: Record<string, unknown>;
+ more?: Record<string, unknown>[];
+ creditsEstimate: number | null;
+}
+
+interface PendingApprovalBase {
id: string;
reason: string;
- calls: {
- id: string;
- provider: string;
- capability: string;
- input: Record<string, unknown>;
- more?: Record<string, unknown>[];
- creditsEstimate: number | null;
- }[];
resolution: null | {
approved: boolean;
+ /** Calls approved. Ignored on terms offers. */
callIds: string[];
always: boolean;
byRunId: string;
};
}
+/**
+ * A turn that ended waiting for the caller to allow or refuse paid calls.
+ * `kind` is absent on items written before terms offers existed.
+ */
+export interface PendingCallsApproval extends PendingApprovalBase {
+ kind?: "calls";
+ calls: PendingApprovalCall[];
+ terms?: never;
+}
+
+/**
+ * A turn that ended waiting for the caller to accept providers' data terms
+ * ("ask" mode). `calls` is always empty (typed `never[]` rather
+ * than `[]` so existing `pendingApproval.calls[0]` code still compiles).
+ */
+export interface PendingTermsApproval extends PendingApprovalBase {
+ kind: "terms";
+ calls: never[];
+ terms: AgentTermsGate[];
+}
+
+/** Narrow on `kind === "terms"`. */
+export type PendingApproval = PendingCallsApproval | PendingTermsApproval;
+
export interface AgentResponse {
success: boolean;
id: string;
diff --git a/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_agent_thread.py b/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_agent_thread.py
index 5424f959a..bd4c616fe 100644
--- a/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_agent_thread.py
+++ b/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_agent_thread.py
@@ -55,6 +55,40 @@ class TestAgentThreadRequestPreparation:
assert data["exchange"] == {"enabled": True, "maxCalls": 4}
+ def test_exchange_on_terms_required_serialized_by_alias(self):
+ data = _prepare_agent_request(
+ None,
+ prompt="Continue",
+ thread_id="thread-1",
+ exchange=AgentExchangeOptions(
+ on_terms_required="ask",
+ approve={"approvalId": "0199aaaa-0000-7000-8000-000000000000"},
+ ),
+ )
+
+ assert data["exchange"] == {
+ "onTermsRequired": "ask",
+ "approve": {"approvalId": "0199aaaa-0000-7000-8000-000000000000"},
+ }
+
+ def test_exchange_on_terms_required_skip_serialized(self):
+ data = _prepare_agent_request(
+ None,
+ prompt="Find the key business contact at exa.ai",
+ exchange=AgentExchangeOptions(on_terms_required="skip"),
+ )
+
+ assert data["exchange"] == {"onTermsRequired": "skip"}
+
+ def test_exchange_on_terms_required_rejects_unknown_mode(self):
+ import pytest
+ from pydantic import ValidationError
+
+ with pytest.raises(ValidationError):
+ AgentExchangeOptions(on_terms_required="accept")
+ with pytest.raises(ValidationError):
+ AgentExchangeOptions(on_terms_required="fail")
+
def test_start_agent_forwards_thread_id(self):
client = Mock()
response = Mock()
@@ -136,6 +170,95 @@ class TestAgentThreadStatusParsing:
assert response.pending_approval.calls[0].credits_estimate == 5
assert response.exchange.paid_calls == 0
+ def test_terms_required_status_payload(self):
+ approval_id = "0199aaaa-0000-7000-8000-000000000000"
+ response = AgentResponse(
+ **{
+ "success": True,
+ "id": "job-3",
+ "status": "completed",
+ "model": "spark-2",
+ "exchange": {
+ "enabled": True,
+ "onTermsRequired": "ask",
+ "paidCalls": 0,
+ "creditsUsed": None,
+ "skippedProviders": [
+ {
+ "provider": "apollo",
+ "name": "Apollo",
+ "capability": "people/search",
+ "adds": "verified work emails",
+ "reason": "terms_required",
+ "version": "F-1.0.0",
+ "termsUrl": "https://www.firecrawl.dev/app/alexandria/apollo",
+ }
+ ],
+ "requiresAction": {
+ "type": "accept_terms",
+ "approvalId": approval_id,
+ "providers": [
+ {
+ "provider": "apollo",
+ "name": "Apollo",
+ "version": "F-1.0.0",
+ "url": "https://www.firecrawl.dev/app/alexandria/apollo",
+ "show": {
+ "provider": "firecrawl",
+ "capability": "terms/show",
+ "options": {"provider": "apollo"},
+ },
+ "accept": {
+ "provider": "firecrawl",
+ "capability": "terms/accept",
+ "options": {
+ "provider": "apollo",
+ "version": "F-1.0.0",
+ "digest": None,
+ "confirmed": True,
+ },
+ },
+ }
+ ],
+ },
+ },
+ "pendingApproval": {
+ "id": approval_id,
+ "kind": "terms",
+ "reason": "Apollo could add verified work emails.",
+ "calls": [],
+ "terms": [
+ {
+ "provider": "apollo",
+ "name": "Apollo",
+ "version": "F-1.0.0",
+ "url": "https://www.firecrawl.dev/app/alexandria/apollo",
+ }
+ ],
+ "resolution": None,
+ },
+ }
+ )
+
+ exchange = response.exchange
+ assert exchange.on_terms_required == "ask"
+ assert exchange.skipped_providers[0].terms_url.endswith("/apollo")
+ assert exchange.requires_action.approval_id == approval_id
+ accept = exchange.requires_action.providers[0].accept
+ assert accept.capability == "terms/accept"
+ assert accept.options["digest"] is None
+ assert response.pending_approval.kind == "terms"
+ assert response.pending_approval.is_terms
+ assert response.pending_approval.calls == []
+ assert response.pending_approval.terms[0].provider == "apollo"
+
+ def test_calls_approval_is_not_terms(self):
+ legacy = AgentResponse(
+ **{"pendingApproval": {"id": "a", "reason": "r", "calls": [], "resolution": None}}
+ )
+ assert legacy.pending_approval.kind is None
+ assert not legacy.pending_approval.is_terms
+
def test_status_payload_ignores_unknown_fields(self):
"""Old SDKs must survive server-side additions; new ones must too."""
response = AgentResponse(
diff --git a/apps/python-sdk/firecrawl/v2/types.py b/apps/python-sdk/firecrawl/v2/types.py
index 46d8aef7d..fda30a374 100644
--- a/apps/python-sdk/firecrawl/v2/types.py
+++ b/apps/python-sdk/firecrawl/v2/types.py
@@ -1554,9 +1554,86 @@ class AgentExchangeOptions(BaseModel):
toolkits: Optional[List[str]] = None
max_calls: Optional[int] = Field(default=None, alias="maxCalls")
require_approval: Optional[bool] = Field(default=None, alias="requireApproval")
- # Answers a pending_approval from the previous turn of the thread.
+ # Answers a pending_approval from the previous turn of the thread. A
+ # "terms" approval is accepted or declined as a whole: callIds and always
+ # are ignored on it.
approve: Optional[Dict[str, Any]] = None
decline: Optional[Dict[str, Any]] = None
+ # What to do when a provider the agent would use needs data terms the team
+ # has not accepted. Gated providers are never called in any mode:
+ # - "skip" (server default): answer with accepted providers only and list
+ # the gated ones in exchange.skipped_providers.
+ # - "ask": the same, plus exchange.requires_action and a "terms"
+ # pending_approval. Get your user's explicit consent, call terms/accept,
+ # then continue the thread with approve={"approvalId": ...}.
+ # There is no auto-accept mode. Omitted on a follow-up turn inherits the
+ # previous turn's value.
+ on_terms_required: Optional[Literal["skip", "ask"]] = Field(
+ default=None, alias="onTermsRequired"
+ )
+
+
+class AgentSkippedProvider(BaseModel):
+ """A gated provider the run would have used but did not."""
+
+ model_config = {"populate_by_name": True, "extra": "allow"}
+
+ provider: Optional[str] = None
+ name: Optional[str] = None
+ capability: Optional[str] = None
+ # What it would have added, in the agent's words.
+ adds: Optional[str] = None
+ # "terms_required".
+ reason: Optional[str] = None
+ # The gating terms version.
+ version: Optional[str] = None
+ # Where a person accepts the terms in the dashboard.
+ terms_url: Optional[str] = Field(default=None, alias="termsUrl")
+
+
+class AgentExchangeCall(BaseModel):
+ """An Exchange call spelled out for the caller to make (terms/show, terms/accept)."""
+
+ model_config = {"populate_by_name": True, "extra": "allow"}
+
+ provider: Optional[str] = None
+ capability: Optional[str] = None
+ options: Optional[Dict[str, Any]] = None
+
+
+class AgentTermsActionProvider(BaseModel):
+ """One provider whose terms the caller can view and accept."""
+
+ model_config = {"populate_by_name": True, "extra": "allow"}
+
+ provider: Optional[str] = None
+ name: Optional[str] = None
+ capability: Optional[str] = None
+ adds: Optional[str] = None
+ version: Optional[str] = None
+ # None when the catalog published no digest; terms/show returns it.
+ digest: Optional[str] = None
+ url: Optional[str] = None
+ show: Optional[AgentExchangeCall] = None
+ # Only call this after the user has explicitly agreed to the terms. Its
+ # options.digest is None when the catalog published none; terms/show
+ # returns it.
+ accept: Optional[AgentExchangeCall] = None
+
+
+class AgentTermsRequiredAction(BaseModel):
+ """The exact calls to view and accept gated providers' terms. Never run for you."""
+
+ model_config = {"populate_by_name": True, "extra": "allow"}
+
+ # "accept_terms".
+ type: Optional[str] = None
+ # Always set by the server: the "terms" pending_approval that answers this.
+ # After the user agrees and terms/accept succeeds, continue the thread with
+ # approve={"approvalId": ...}, or refuse with decline. Optional here only so a
+ # malformed payload cannot break status polling.
+ approval_id: Optional[str] = Field(default=None, alias="approvalId")
+ providers: Optional[List[AgentTermsActionProvider]] = None
class AgentExchangeSummary(BaseModel):
@@ -1568,8 +1645,17 @@ class AgentExchangeSummary(BaseModel):
# What the run resolved to after thread inheritance, not what it requested.
toolkits: Optional[List[str]] = None
require_approval: Optional[bool] = Field(default=None, alias="requireApproval")
+ on_terms_required: Optional[str] = Field(default=None, alias="onTermsRequired")
paid_calls: Optional[int] = Field(default=None, alias="paidCalls")
credits_used: Optional[int] = Field(default=None, alias="creditsUsed")
+ # Gated providers that would have helped and were not used. Any mode.
+ skipped_providers: Optional[List[AgentSkippedProvider]] = Field(
+ default=None, alias="skippedProviders"
+ )
+ # "ask" mode, when a terms offer ended the turn.
+ requires_action: Optional[AgentTermsRequiredAction] = Field(
+ default=None, alias="requiresAction"
+ )
class AgentSuggestion(BaseModel):
@@ -1605,16 +1691,48 @@ class PendingApprovalResolution(BaseModel):
by_run_id: Optional[str] = Field(default=None, alias="byRunId")
+class PendingApprovalTerms(BaseModel):
+ """A provider in a "terms" pending approval."""
+
+ model_config = {"populate_by_name": True, "extra": "allow"}
+
+ provider: Optional[str] = None
+ name: Optional[str] = None
+ logo: Optional[str] = None
+ capability: Optional[str] = None
+ adds: Optional[str] = None
+ version: Optional[str] = None
+ # None when the catalog published no digest; terms/show returns it.
+ digest: Optional[str] = None
+ url: Optional[str] = None
+
+
class PendingApproval(BaseModel):
- """A turn that ended waiting for the caller to allow or refuse paid calls."""
+ """A turn that ended waiting for the caller.
+
+ Two shapes, told apart by ``kind``:
+
+ - calls (``kind`` "calls", or None on items written before terms offers):
+ allow or refuse the paid ``calls``.
+ - terms (``kind`` "terms"): accept the listed providers' data ``terms``;
+ ``calls`` is always empty. Use ``is_terms`` to branch.
+
+ One model rather than a pydantic discriminated union, so an item with an
+ unknown ``kind`` still parses and status polling keeps working.
+ """
model_config = {"populate_by_name": True, "extra": "allow"}
id: Optional[str] = None
+ kind: Optional[str] = None
reason: Optional[str] = None
calls: Optional[List[PendingApprovalCall]] = None
+ terms: Optional[List[PendingApprovalTerms]] = None
resolution: Optional[PendingApprovalResolution] = None
+ @property
+ def is_terms(self) -> bool:
+ return self.kind == "terms"
class AgentResponse(BaseModel):
"""Response for agent operations (start/status/final)."""