Skip to content

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

feat: e3

Gergő Móricz3a84260a9180
diff --git a/apps/api/knip.config.ts b/apps/api/knip.config.ts
index 10a850f5e..ada00cb16 100644
--- a/apps/api/knip.config.ts
+++ b/apps/api/knip.config.ts
@@ -14,6 +14,7 @@ const config: KnipConfig = {
],
ignoreDependencies: [
"openai",
+ "undici-types",
"@pinecone-database/pinecone", // WIP
],
};
diff --git a/apps/api/package.json b/apps/api/package.json
index 2829c63d8..3ea89056e 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -66,7 +66,8 @@
"ts-node": "^10.9.1",
"tsc-watch": "^7.1.1",
"tsx": "^4.20.3",
- "typescript": "^5.8.3"
+ "typescript": "^5.8.3",
+ "undici-types": "^7.16.0"
},
"dependencies": {
"@ai-sdk/anthropic": "^2.0.41",
diff --git a/apps/api/pnpm-lock.yaml b/apps/api/pnpm-lock.yaml
index f205008d1..59dcd1979 100644
--- a/apps/api/pnpm-lock.yaml
+++ b/apps/api/pnpm-lock.yaml
@@ -304,6 +304,9 @@ importers:
typescript:
specifier: ^5.8.3
version: 5.8.3
+ undici-types:
+ specifier: ^7.16.0
+ version: 7.16.0
native:
devDependencies:
@@ -6919,7 +6922,7 @@ snapshots:
idb-keyval: 6.2.1
preact: 10.24.2
transitivePeerDependencies:
- '@types/react'
@@ -6993,7 +6996,7 @@ snapshots:
idb-keyval: 6.2.1
preact: 10.24.2
transitivePeerDependencies:
- '@types/react'
@@ -7196,11 +7199,11 @@ snapshots:
ethereum-cryptography: 2.2.1
micro-ftch: 0.3.1
dependencies:
'@metamask/rpc-errors': 7.0.2
eventemitter3: 5.0.1
transitivePeerDependencies:
- supports-color
@@ -8526,7 +8529,7 @@ snapshots:
dependencies:
big.js: 6.2.2
dayjs: 1.11.13
transitivePeerDependencies:
- bufferutil
- typescript
@@ -8539,7 +8542,7 @@ snapshots:
'@reown/appkit-wallet': 1.7.8([email protected])([email protected])([email protected])
valtio: 1.13.2([email protected])
transitivePeerDependencies:
- '@azure/app-configuration'
- '@azure/cosmos'
@@ -8685,7 +8688,7 @@ snapshots:
'@walletconnect/logger': 2.1.2
valtio: 1.13.2([email protected])
transitivePeerDependencies:
- '@azure/app-configuration'
- '@azure/cosmos'
@@ -8738,7 +8741,7 @@ snapshots:
bs58: 6.0.0
valtio: 1.13.2([email protected])
transitivePeerDependencies:
- '@azure/app-configuration'
- '@azure/cosmos'
@@ -8779,7 +8782,7 @@ snapshots:
dependencies:
'@safe-global/safe-gateway-typescript-sdk': 3.23.1
transitivePeerDependencies:
- bufferutil
- typescript
@@ -9784,19 +9787,19 @@ snapshots:
'@vercel/[email protected]': {}
dependencies:
'@safe-global/safe-apps-provider': 0.18.6([email protected])([email protected])([email protected])([email protected])
cbw-sdk: '@coinbase/[email protected]'
optionalDependencies:
typescript: 5.8.3
transitivePeerDependencies:
@@ -9830,11 +9833,11 @@ snapshots:
- wagmi
- zod
dependencies:
eventemitter3: 5.0.1
mipd: 0.0.7([email protected])
optionalDependencies:
'@tanstack/query-core': 5.83.1
@@ -10387,6 +10390,11 @@ snapshots:
typescript: 5.8.3
zod: 3.25.76
+ optionalDependencies:
+ typescript: 5.8.3
+ zod: 4.1.12
+
optionalDependencies:
typescript: 5.8.3
@@ -12875,6 +12883,21 @@ snapshots:
transitivePeerDependencies:
- zod
+ dependencies:
+ '@adraffy/ens-normalize': 1.11.1
+ '@noble/ciphers': 1.3.0
+ '@noble/curves': 1.9.6
+ '@noble/hashes': 1.8.0
+ '@scure/bip32': 1.7.0
+ '@scure/bip39': 1.6.0
+ eventemitter3: 5.0.1
+ optionalDependencies:
+ typescript: 5.8.3
+ transitivePeerDependencies:
+ - zod
+
dependencies:
'@adraffy/ens-normalize': 1.11.1
@@ -13085,21 +13108,21 @@ snapshots:
dependencies:
hono: 4.9.10
idb-keyval: 6.2.2
mipd: 0.0.7([email protected])
zod: 4.1.12
optionalDependencies:
'@tanstack/react-query': 5.84.1([email protected])
react: 18.3.1
typescript: 5.8.3
transitivePeerDependencies:
- '@types/react'
- immer
@@ -14029,18 +14052,35 @@ snapshots:
- utf-8-validate
- zod
+ dependencies:
+ '@noble/curves': 1.9.2
+ '@noble/hashes': 1.8.0
+ '@scure/bip32': 1.7.0
+ '@scure/bip39': 1.6.0
+ optionalDependencies:
+ typescript: 5.8.3
+ transitivePeerDependencies:
+ - bufferutil
+ - utf-8-validate
+ - zod
+
dependencies:
xml-name-validator: 5.0.0
dependencies:
'@tanstack/react-query': 5.84.1([email protected])
react: 18.3.1
use-sync-external-store: 1.4.0([email protected])
optionalDependencies:
typescript: 5.8.3
transitivePeerDependencies:
@@ -14249,8 +14289,8 @@ snapshots:
zod: 3.25.76
transitivePeerDependencies:
- '@azure/app-configuration'
diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts
index 1a408e5cb..504967514 100644
--- a/apps/api/src/config.ts
+++ b/apps/api/src/config.ts
@@ -189,6 +189,8 @@ const configSchema = z.object({
GITHUB_REF_NAME: z.string().optional(),
RESTRICTED_COUNTRIES: delimitedList(",").optional(),
DISABLE_ENGPICKER: z.stringbool().optional(),
+
+ EXTRACT_V3_BETA_URL: z.string().optional(),
});
export const config = configSchema.parse(process.env);
diff --git a/apps/api/src/controllers/v1/types.ts b/apps/api/src/controllers/v1/types.ts
index ff1efb7cc..013b54901 100644
--- a/apps/api/src/controllers/v1/types.ts
+++ b/apps/api/src/controllers/v1/types.ts
@@ -1254,6 +1254,7 @@ export type TeamFlags = {
crawlTtlHours?: number;
ipWhitelist?: boolean;
skipCountryCheck?: boolean;
+ extractV3Beta?: boolean;
} | null;
export type AuthCreditUsageChunkFromTeam = Omit<
diff --git a/apps/api/src/controllers/v2/extract-status.ts b/apps/api/src/controllers/v2/extract-status.ts
index b7c061f8f..0fbfc583f 100644
--- a/apps/api/src/controllers/v2/extract-status.ts
+++ b/apps/api/src/controllers/v2/extract-status.ts
@@ -4,9 +4,13 @@ import { RequestWithAuth } from "./types";
import { getExtract, getExtractExpiry } from "../../lib/extract/extract-redis";
import { getExtractQueue } from "../../services/queue-service";
import { ExtractResult } from "../../lib/extract/extraction-service";
-import { supabaseGetExtractByIdDirect } from "../../lib/supabase-jobs";
+import {
+ supabaseGetExtractByIdDirect,
+ supabaseGetExtractRequestByIdDirect,
+} from "../../lib/supabase-jobs";
import { JobState } from "bullmq";
import { logger as _logger } from "../../lib/logger";
+import { getJobFromGCS } from "../../lib/gcs-jobs";
type DBExtract = {
id: string;
@@ -32,17 +36,26 @@ type ExtractPseudoJob<T> = {
async function getExtractJob(
id: string,
): Promise<ExtractPseudoJob<ExtractResult> | null> {
- const [bullJob, dbExtract] = await Promise.all([
+ const [bullJob, gcsJob, dbExtract] = await Promise.all([
getExtractQueue().getJob(id),
+ (config.GCS_BUCKET_NAME ? getJobFromGCS(id) : null) as Promise<any | null>,
(config.USE_DB_AUTHENTICATION
? supabaseGetExtractByIdDirect(id)
: null) as Promise<DBExtract | null>,
]);
+ console.log("JOBS", [bullJob, gcsJob, dbExtract]);
+
if (!bullJob && !dbExtract) return null;
// Extract results are stored in GCS, not in the DB
- const data = bullJob?.returnvalue?.data;
+ let data = gcsJob ?? bullJob?.returnvalue?.data;
+ if (gcsJob === null && data) {
+ _logger.warn("GCS Job not found", {
+ jobId: id,
+ });
+ }
+ if (Array.isArray(data)) data = data[0];
const job: ExtractPseudoJob<any> = {
id,
@@ -68,18 +81,11 @@ export async function extractStatusController(
req: RequestWithAuth<{ jobId: string }, any, any>,
res: Response,
) {
- const logger = _logger.child({
- module: "v1/extract-status",
- method: "extractStatusController",
- teamId: req.auth.team_id,
- extractId: req.params.jobId,
- });
-
- const extract = await getExtract(req.params.jobId);
-
- let status = extract?.status;
+ const extractRequest = await supabaseGetExtractRequestByIdDirect(
+ req.params.jobId,
+ );
- if (extract && extract.team_id !== req.auth.team_id) {
+ if (!extractRequest || extractRequest.team_id !== req.auth.team_id) {
return res.status(404).json({
success: false,
error: "Extract job not found",
@@ -87,63 +93,56 @@ export async function extractStatusController(
}
let data: ExtractResult | [] = [];
+ let status: string = "processing";
- if (!extract || extract.status === "completed") {
- const jobData = await getExtractJob(req.params.jobId);
- if (
- (!jobData && !extract) ||
- (jobData && jobData.data.teamId !== req.auth.team_id)
- ) {
- logger.warn("Extract job was not found");
- return res.status(404).json({
- success: false,
- error: "Extract job not found",
- });
- }
+ const redisExtract = await getExtract(req.params.jobId);
+ const jobData = await getExtractJob(req.params.jobId);
- if (jobData) {
- const jobStatus = await jobData.getState();
+ console.log("jobData", jobData);
- if (jobStatus === "completed") {
- status = "completed";
- } else if (jobStatus === "failed") {
- status = "failed";
- } else {
- status = "processing";
- }
- }
+ if (jobData) {
+ const jobStatus = await jobData.getState();
- if (!jobData?.returnvalue) {
- // if we got in the split-second where the redis is updated but the bull isn't
- // just pretend it's still processing - MG
- status = "processing";
+ if (jobStatus === "completed") {
+ status = "completed";
+ } else if (jobStatus === "failed") {
+ status = "failed";
} else {
- data = jobData.returnvalue ?? [];
+ status = "processing";
}
}
+ if (!jobData?.returnvalue) {
+ // if we got in the split-second where the redis is updated but the bull isn't
+ // just pretend it's still processing - MG
+ status = "processing";
+ } else {
+ data = jobData.returnvalue ?? [];
+ }
+
return res.status(200).json({
success: status === "failed" ? false : true,
data,
status,
- error: (() => {
- if (typeof extract?.error === "string") return extract.error;
- if (extract?.error && typeof extract.error === "object") {
- return (
- extract.error.message ||
- extract.error.error ||
- JSON.stringify(extract.error)
- );
- }
- return undefined;
- })(),
- expiresAt: (await getExtractExpiry(req.params.jobId)).toISOString(),
- steps: extract?.showSteps ? extract.steps : undefined,
- llmUsage: extract?.showLLMUsage ? extract.llmUsage : undefined,
- sources: extract?.showSources ? extract.sources : undefined,
- costTracking: extract?.showCostTracking ? extract.costTracking : undefined,
- sessionIds: extract?.sessionIds ? extract.sessionIds : undefined,
- tokensUsed: extract?.tokensBilled ? extract.tokensBilled : undefined,
- creditsUsed: extract?.creditsBilled ? extract.creditsBilled : undefined,
+ error: jobData?.failedReason,
+ expiresAt: redisExtract
+ ? (await getExtractExpiry(req.params.jobId)).toISOString()
+ : new Date(
+ new Date(jobData?.timestamp ?? extractRequest.created_at).getTime() +
+ 1000 * 60 * 60 * 24,
+ ).toISOString(),
+ steps: redisExtract?.showSteps ? redisExtract.steps : undefined,
+ llmUsage: redisExtract?.showLLMUsage ? redisExtract.llmUsage : undefined,
+ sources: redisExtract?.showSources ? redisExtract.sources : undefined,
+ costTracking: redisExtract?.showCostTracking
+ ? redisExtract.costTracking
+ : undefined,
+ sessionIds: redisExtract?.sessionIds ? redisExtract.sessionIds : undefined,
+ tokensUsed: redisExtract?.tokensBilled
+ ? redisExtract.tokensBilled
+ : undefined,
+ creditsUsed: redisExtract?.creditsBilled
+ ? redisExtract.creditsBilled
+ : undefined,
});
}
diff --git a/apps/api/src/controllers/v2/extract.ts b/apps/api/src/controllers/v2/extract.ts
index 36a2cc71f..28ddf100b 100644
--- a/apps/api/src/controllers/v2/extract.ts
+++ b/apps/api/src/controllers/v2/extract.ts
@@ -12,6 +12,7 @@ import { BLOCKLISTED_URL_MESSAGE } from "../../lib/strings";
import { isUrlBlocked } from "../../scraper/WebScraper/utils/blocklist";
import { logger as _logger } from "../../lib/logger";
import { logRequest } from "../../services/logging/log_job";
+import { config } from "../../config";
/**
* Extracts data from the provided URLs based on the request parameters.
@@ -35,6 +36,91 @@ export async function extractController(
});
}
+ const extractId = uuidv7();
+ const createdAt = Date.now();
+ _logger.info("Extract starting...", {
+ request: req.body,
+ originalRequest,
+ teamId: req.auth.team_id,
+ team_id: req.auth.team_id,
+ subId: req.acuc?.sub_id,
+ extractId,
+ zeroDataRetention: req.acuc?.flags?.forceZDR,
+ });
+
+ if (req.body.agent?.model === "v3-beta") {
+ if (!config.EXTRACT_V3_BETA_URL) {
+ return res.status(400).json({
+ success: false,
+ error: "Extract v3 beta is not enabled.",
+ });
+ }
+
+ if (!req.acuc?.flags?.extractV3Beta) {
+ return res.status(400).json({
+ success: false,
+ error:
+ "Extract v3 beta is not enabled for your team. Please contact [email protected] to join the beta.",
+ });
+ }
+
+ if (!req.body.prompt) {
+ return res.status(400).json({
+ success: false,
+ error: "Prompt is required for extract v3 beta.",
+ });
+ }
+
+ await logRequest({
+ id: extractId,
+ kind: "extract",
+ api_version: "v2",
+ team_id: req.auth.team_id,
+ origin: req.body.origin ?? "api",
+ integration: req.body.integration,
+ target_hint: req.body.urls?.[0] ?? "",
+ zeroDataRetention: false, // not supported for extract
+ api_key_id: req.acuc?.api_key_id ?? null,
+ });
+
+ const passthrough = await fetch(
+ config.EXTRACT_V3_BETA_URL + "/internal/extracts",
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ id: extractId,
+ urls: req.body.urls,
+ schema: req.body.schema,
+ prompt: req.body.prompt,
+ }),
+ },
+ );
+
+ if (passthrough.status !== 200) {
+ const text = await passthrough.text();
+
+ _logger.error("Failed to passthrough extract v3 beta request.", {
+ status: passthrough.status,
+ text,
+ teamId: req.auth.team_id,
+ team_id: req.auth.team_id,
+ extractId,
+ });
+ return res.status(500).json({
+ success: false,
+ error: "Failed to passthrough extract v3 beta request.",
+ });
+ }
+
+ return res.status(200).json({
+ success: true,
+ id: extractId,
+ });
+ }
+
const invalidURLs: string[] =
req.body.urls?.filter((url: string) =>
isUrlBlocked(url, req.acuc?.flags ?? null),
@@ -49,18 +135,6 @@ export async function extractController(
}
}
- const extractId = uuidv7();
- const createdAt = Date.now();
- _logger.info("Extract starting...", {
- request: req.body,
- originalRequest,
- teamId: req.auth.team_id,
- team_id: req.auth.team_id,
- subId: req.acuc?.sub_id,
- extractId,
- zeroDataRetention: req.acuc?.flags?.forceZDR,
- });
-
await logRequest({
id: extractId,
kind: "extract",
diff --git a/apps/api/src/lib/extract/document-scraper.ts b/apps/api/src/lib/extract/document-scraper.ts
index c91765748..0beae14a9 100644
--- a/apps/api/src/lib/extract/document-scraper.ts
+++ b/apps/api/src/lib/extract/document-scraper.ts
@@ -46,7 +46,6 @@ export async function scrapeDocument(
const jobPriority = await getJobPriority({
team_id: options.teamId,
basePriority: 10,
- from_extract: true,
});
await addScrapeJob(
diff --git a/apps/api/src/lib/extract/fire-0/document-scraper-f0.ts b/apps/api/src/lib/extract/fire-0/document-scraper-f0.ts
index f6713bf0d..85d525f3b 100644
--- a/apps/api/src/lib/extract/fire-0/document-scraper-f0.ts
+++ b/apps/api/src/lib/extract/fire-0/document-scraper-f0.ts
@@ -45,7 +45,6 @@ export async function scrapeDocument_F0(
const jobPriority = await getJobPriority({
team_id: options.teamId,
basePriority: 10,
- from_extract: true,
});
const scrapeOptions = scrapeOptionsSchema.parse({
diff --git a/apps/api/src/lib/job-priority.ts b/apps/api/src/lib/job-priority.ts
index 9c1d22b8a..78ad5290c 100644
--- a/apps/api/src/lib/job-priority.ts
+++ b/apps/api/src/lib/job-priority.ts
@@ -32,7 +32,6 @@ export async function deleteJobPriority(team_id, job_id) {
export async function getJobPriority({
team_id,
basePriority = 10,
- from_extract = false,
}: {
team_id: string;
basePriority?: number;
@@ -47,7 +46,7 @@ export async function getJobPriority({
team_id,
false,
true,
- from_extract ? RateLimiterMode.Extract : RateLimiterMode.Crawl,
+ RateLimiterMode.Scrape,
);
const setKey = SET_KEY_PREFIX + team_id;
diff --git a/apps/api/src/lib/supabase-jobs.ts b/apps/api/src/lib/supabase-jobs.ts
index db7071cbe..fe22329f5 100644
--- a/apps/api/src/lib/supabase-jobs.ts
+++ b/apps/api/src/lib/supabase-jobs.ts
@@ -125,3 +125,24 @@ export const supabaseGetExtractByIdDirect = async (extractId: string) => {
return data;
};
+
+export const supabaseGetExtractRequestByIdDirect = async (
+ extractId: string,
+) => {
+ const { data, error } = await supabase_service
+ .from("requests")
+ .select("*")
+ .eq("id", extractId)
+ .eq("kind", "extract")
+ .single();
+
+ if (error) {
+ return null;
+ }
+
+ if (!data) {
+ return null;
+ }
+
+ return data;
+};
diff --git a/apps/api/src/services/queue-jobs.ts b/apps/api/src/services/queue-jobs.ts
index c0ae0280b..54de69cb9 100644
--- a/apps/api/src/services/queue-jobs.ts
+++ b/apps/api/src/services/queue-jobs.ts
@@ -251,10 +251,7 @@ async function addScrapeJobRaw(
webScraperOptions.team_id,
false,
true,
- webScraperOptions.mode === "single_urls" &&
- webScraperOptions.from_extract
- ? RateLimiterMode.Extract
- : RateLimiterMode.Crawl,
+ RateLimiterMode.Crawl,
)
)?.concurrency ?? 2;
await cleanOldConcurrencyLimitEntries(webScraperOptions.team_id, now);
@@ -459,16 +456,8 @@ export async function addScrapeJobs(
} else {
const now = Date.now();
maxConcurrency =
- (
- await getACUCTeam(
- teamId,
- false,
- true,
- jobs[0].data.mode === "single_urls" && jobs[0].data.from_extract
- ? RateLimiterMode.Extract
- : RateLimiterMode.Crawl,
- )
- )?.concurrency ?? 2;
+ (await getACUCTeam(teamId, false, true, RateLimiterMode.Scrape))
+ ?.concurrency ?? 2;
await cleanOldConcurrencyLimitEntries(teamId, now);
const currentActiveConcurrency = (