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
feat(api): accept provider terms through the Exchange ledger (#4668)
Developers Digestf6774139f3d3
diff --git a/apps/api/src/controllers/v2/scrape.ts b/apps/api/src/controllers/v2/scrape.tsindex f11b2deb4..69dee92b6 100644--- a/apps/api/src/controllers/v2/scrape.ts+++ b/apps/api/src/controllers/v2/scrape.ts@@ -212,15 +212,10 @@ export async function scrapeController(getScrapeZDR(req.acuc?.flags) === "forced" ||(req.body.zeroDataRetention ?? false) ||(req.body.lockdown ?? false);- if (- req.body.domainTools &&- (!req.acuc?.flags?.exchangeRetrieve || zeroDataRetention)- )+ if (req.body.domainTools && zeroDataRetention)return res.status(403).json({success: false,- error: !req.acuc?.flags?.exchangeRetrieve- ? "The alexandria source is not enabled for this team."- : "Provider discovery requires access and does not support zero data retention.",+ error: "Provider discovery does not support zero data retention.",});const billing: BillingMetadata = req.body.__agentInterop? { endpoint: "agent" as const, jobId }diff --git a/apps/api/src/routes/exchange.ts b/apps/api/src/routes/exchange.tsindex 569333767..057eced57 100644--- a/apps/api/src/routes/exchange.ts+++ b/apps/api/src/routes/exchange.ts@@ -1,5 +1,10 @@import { bountyBlocklistMiddleware } from "./exchange-blocklist";import { providerScrapeController } from "../controllers/v2/scrape-alexandria";+import { orgIdFromAcuc } from "../lib/team-org";+import {+ acceptProviderTerms,+ acceptTermsSchema,+} from "../services/alexandria/terms";import express, { Request, Response } from "express";import { Agent, fetch } from "undici";import { config } from "../config";@@ -114,6 +119,37 @@ function exchangeProxy(};}+async function providerTermsAcceptController(req: Request, res: Response) {+ const authedReq = req as RequestWithAuth<any, any, any>;+ const orgId = orgIdFromAcuc(authedReq.acuc);+ if (orgId === null) {+ return exchangeError(+ res,+ 403,+ "This endpoint is not enabled for this team.",+ );+ }+ const body = acceptTermsSchema.safeParse(req.body);+ if (!body.success) {+ return exchangeError(+ res,+ 400,+ "Send { provider, version, digest, confirmed: true } for one provider.",+ );+ }+ const response = await acceptProviderTerms({+ teamId: authedReq.auth.team_id,+ orgId,+ apiKeyId:+ authedReq.acuc?.api_key_id_text ??+ (authedReq.acuc?.api_key_id == null+ ? null+ : String(authedReq.acuc.api_key_id)),+ body: body.data,+ });+ return res.status(response.status).json(response.body);+}+export const exchangeRouter = express.Router();exchangeRouter.get(@@ -142,6 +178,12 @@ exchangeRouter.get(wrap(exchangeProxy(DISCOVER_TIMEOUT_MS)),);+exchangeRouter.post(+ "/provider-terms/accept",+ authMiddleware(RateLimiterMode.Labs),+ wrap(providerTermsAcceptController),+);+exchangeRouter.post("/provider-terms/events",authMiddleware(RateLimiterMode.Labs),diff --git a/apps/api/src/services/alexandria/access.ts b/apps/api/src/services/alexandria/access.tsindex 4b20200fa..9b8ff71b6 100644--- a/apps/api/src/services/alexandria/access.ts+++ b/apps/api/src/services/alexandria/access.ts@@ -4,6 +4,7 @@ import type { TeamFlags } from "../../controllers/v2/types";import { getThirdPartyDataTermsRequiredResponse } from "../../lib/exchange";import { exchangeRequest } from "./client";import { refusal, type ExchangeResponse, type ProviderCall } from "./contracts";+import { acceptedProviders, type LedgerAcceptance } from "./terms";const requirementsSchema = z.object({providers: z.array(@@ -11,7 +12,11 @@ const requirementsSchema = z.object({provider: z.string(),required: z.boolean(),terms: z- .object({ key: z.string(), version: z.string() })+ .object({+ key: z.string(),+ version: z.string(),+ digest: z.string().optional(),+ }).passthrough().nullable(),}),@@ -22,6 +27,7 @@ export async function authorizeProviders(teamId: string,calls: ProviderCall[],flags: TeamFlags | null | undefined,+ orgId: string | null = null,): Promise<ExchangeResponse | undefined> {const providers = [...new Set(calls.map(call => call.provider))];const response = await exchangeRequest({@@ -52,6 +58,7 @@ export async function authorizeProviders();if (config.USE_DB_AUTHENTICATION !== true) return undefined;+ let ledger: Map<string, LedgerAcceptance> | undefined;for (const item of parsed.data.providers) {const access = flags?.organizationDataSourceAccess?.[item.provider];if (access && access.status !== "enabled")@@ -59,16 +66,26 @@ export async function authorizeProviders(403,`Access to ${item.provider} is disabled for this organization.`,);+ if (!item.required || !item.terms) continue;if (- item.required &&- item.terms &&- (access?.termsKey !== item.terms.key ||- access?.termsVersion !== item.terms.version)+ access?.termsKey === item.terms.key &&+ access?.termsVersion === item.terms.version)- return {- status: 403,- body: getThirdPartyDataTermsRequiredResponse(item.terms),- };+ continue;+ if (orgId !== null) {+ ledger ??= await acceptedProviders(teamId, orgId);+ const accepted = ledger.get(item.provider);+ if (+ item.terms.digest !== undefined &&+ accepted?.version === item.terms.version &&+ accepted.textHash === item.terms.digest+ )+ continue;+ }+ return {+ status: 403,+ body: getThirdPartyDataTermsRequiredResponse(item.terms),+ };}return undefined;}diff --git a/apps/api/src/services/alexandria/retrieve.ts b/apps/api/src/services/alexandria/retrieve.tsindex 041b47cc5..390d206ab 100644--- a/apps/api/src/services/alexandria/retrieve.ts+++ b/apps/api/src/services/alexandria/retrieve.ts@@ -182,6 +182,7 @@ export async function retrieveProviders(input: {input.teamId,input.calls,input.flags,+ input.orgId,);if (denied) return refuse(denied);diff --git a/apps/api/src/services/alexandria/terms.ts b/apps/api/src/services/alexandria/terms.tsnew file mode 100644index 000000000..a203666a7--- /dev/null+++ b/apps/api/src/services/alexandria/terms.ts@@ -0,0 +1,156 @@+import { z } from "zod";+import { exchangeRequest } from "./client";+import { refusal, type ExchangeResponse } from "./contracts";++const TIMEOUT_MS = 10_000;++export const acceptTermsSchema = z.strictObject({+ provider: z.string().min(1).max(200),+ version: z.string().min(1).max(200),+ digest: z.string().regex(/^[a-f0-9]{64}$/),+ confirmed: z.literal(true),+ agent: z+ .strictObject({+ name: z.string().min(1).max(200),+ vendor: z.string().max(200).optional(),+ runId: z.string().max(200).optional(),+ })+ .optional(),+});+type AcceptTerms = z.infer<typeof acceptTermsSchema>;++const requirementsSchema = z.object({+ providers: z.array(+ z.object({+ provider: z.string(),+ required: z.boolean(),+ terms: z+ .object({+ key: z.string(),+ version: z.string(),+ digest: z.string(),+ schedule: z.string().optional(),+ })+ .passthrough()+ .nullable(),+ }),+ ),+});++const statusSchema = z.object({+ providers: z.array(+ z+ .object({+ provider: z.string(),+ version: z.string().nullable(),+ textHash: z.string().nullable(),+ revoked: z.boolean(),+ })+ .passthrough(),+ ),+});++export type LedgerAcceptance = { version: string; textHash: string | null };++export async function acceptedProviders(+ teamId: string,+ orgId: string,+): Promise<Map<string, LedgerAcceptance>> {+ const response = await exchangeRequest({+ teamId,+ path: `/v1/provider-terms/status?organizationId=${encodeURIComponent(orgId)}`,+ timeoutMs: TIMEOUT_MS,+ }).catch(() => undefined);+ const parsed =+ response?.status === 200+ ? statusSchema.safeParse(response.body)+ : undefined;+ const accepted = new Map<string, LedgerAcceptance>();+ if (!parsed?.success) return accepted;+ for (const item of parsed.data.providers) {+ if (!item.revoked && item.version)+ accepted.set(item.provider, {+ version: item.version,+ textHash: item.textHash,+ });+ }+ return accepted;+}++export async function acceptProviderTerms(input: {+ teamId: string;+ orgId: string;+ apiKeyId: string | null;+ body: AcceptTerms;+}): Promise<ExchangeResponse> {+ const { provider, version, digest, agent } = input.body;+ const requirements = await exchangeRequest({+ teamId: input.teamId,+ path: "/v1/provider-terms/requirements",+ body: { providers: [provider] },+ timeoutMs: TIMEOUT_MS,+ }).catch(() => undefined);+ if (requirements?.status === 404)+ return refusal(404, "Unknown provider.", { code: "unknown_provider" });+ const parsed =+ requirements?.status === 200+ ? requirementsSchema.safeParse(requirements.body)+ : undefined;+ const item = parsed?.success+ ? parsed.data.providers.find(entry => entry.provider === provider)+ : undefined;+ if (!item)+ return refusal(+ 503,+ "Provider agreements are unavailable. Nothing was accepted.",+ );+ if (!item.required || !item.terms)+ return refusal(400, `${provider} requires no agreement.`);+ if (item.terms.version !== version || item.terms.digest !== digest)+ return refusal(+ 409,+ "Terms changed. Review the current version before accepting.",+ {+ code: "terms_changed",+ provider,+ version: item.terms.version,+ digest: item.terms.digest,+ },+ );++ const event = await exchangeRequest({+ teamId: input.teamId,+ path: "/v1/provider-terms/events",+ body: {+ organization_id: input.orgId,+ data_source_id: provider,+ event_type: "accepted",+ schedule: item.terms.schedule ?? null,+ version,+ text_hash: digest,+ actor_type: "agent",+ credential_id: input.apiKeyId,+ agent_descriptor: agent ?? null,+ surface: "api",+ },+ timeoutMs: TIMEOUT_MS,+ }).catch(() => undefined);+ const recorded = z+ .object({ id: z.string(), occurred_at: z.string() })+ .safeParse(event?.status === 201 ? event.body : undefined);+ if (!recorded.success)+ return refusal(+ 503,+ "Provider terms acceptance is unavailable. Nothing was accepted.",+ );+ return {+ status: 200,+ body: {+ success: true,+ provider,+ version,+ digest,+ acceptedAt: recorded.data.occurred_at,+ },+ };+}