Skip to content

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

feat(index): add a search endpoint (#4952)

Kris Oeia786560457b8
diff --git a/apps/api/pnpm-lock.yaml b/apps/api/pnpm-lock.yaml
index 98ccbca1a..ec6289b75 100644
--- a/apps/api/pnpm-lock.yaml
+++ b/apps/api/pnpm-lock.yaml
@@ -43,7 +43,7 @@ overrides:
follow-redirects@<1.16.0: '>=1.16.0 <2.0.0'
uuid@<11.1.1: 11.1.1
js-cookie@<3.0.7: 3.0.7
- shell-quote@<=1.8.4: 1.10.0
+ shell-quote@<1.11.0: 1.11.0
esbuild@>=0.17.0 <0.28.1: 0.28.1
query-string@>=9.0.0 <10.0.0: '>=9.5.0 <10.0.0'
'@ai-sdk/provider-utils@>=4.0.0 <4.0.33': 4.0.51
@@ -4174,8 +4174,8 @@ packages:
resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-w1aiOKwKuRgtwAReIIj89puqg+I7GvX4IbLrvmhXbzQsj1+Zwi4VO3+fa6ZF91TWSjIxoEkKnMeHcLEODK5ZXA==}
+ resolution: {integrity: sha512-JdxDPD0DBTyu08pq0kPC0xSNet/qsU07qT6IsX1AS8oO2ICNRY4ldNa8OAI6PuwAH8tG3lxEhbqmyp4Dw4036g==}
engines: {node: '>= 0.4'}
@@ -7775,7 +7775,7 @@ snapshots:
picomatch: 4.0.4
pidtree: 0.6.0
read-package-json-fast: 4.0.0
- shell-quote: 1.10.0
+ shell-quote: 1.11.0
which: 5.0.0
@@ -8269,7 +8269,7 @@ snapshots:
dependencies:
diff --git a/apps/api/pnpm-workspace.yaml b/apps/api/pnpm-workspace.yaml
index 4360bd30c..5194185d4 100644
--- a/apps/api/pnpm-workspace.yaml
+++ b/apps/api/pnpm-workspace.yaml
@@ -64,7 +64,8 @@ overrides:
"follow-redirects@<1.16.0": ">=1.16.0 <2.0.0"
"uuid@<11.1.1": "11.1.1"
"js-cookie@<3.0.7": "3.0.7"
- "shell-quote@<=1.8.4": "1.10.0"
+ # GHSA-pqg4-j6r4-53mv: fixed in 1.11.0.
+ "shell-quote@<1.11.0": "1.11.0"
"esbuild@>=0.17.0 <0.28.1": "0.28.1"
"query-string@>=9.0.0 <10.0.0": ">=9.5.0 <10.0.0"
# GHSA-866g-f22w-33x8: pin the 4.x line only. Exact 4.0.51 cannot
diff --git a/apps/api/src/__tests__/routes/search-research-category-notice.routes.test.ts b/apps/api/src/__tests__/routes/search-research-category-notice.routes.test.ts
index b85422969..9f57133b1 100644
--- a/apps/api/src/__tests__/routes/search-research-category-notice.routes.test.ts
+++ b/apps/api/src/__tests__/routes/search-research-category-notice.routes.test.ts
@@ -46,6 +46,7 @@ describe("research category notice", () => {
[["github"]],
[["pdf"]],
[["developer"]],
+ [["gov"]],
["research"],
[[null, 7]],
])("stays silent for %j", async categories => {
diff --git a/apps/api/src/__tests__/snips/v2/gov.test.ts b/apps/api/src/__tests__/snips/v2/gov.test.ts
new file mode 100644
index 000000000..f6e86479e
--- /dev/null
+++ b/apps/api/src/__tests__/snips/v2/gov.test.ts
@@ -0,0 +1,33 @@
+import { config } from "../../../config";
+import { describeIf } from "../lib";
+import { idmux, researchRaw } from "./lib";
+
+const HAS_GOV = !!config.SEARCH_PLATFORM_URL;
+const PATH = "/v2/search/gov";
+
+describeIf(HAS_GOV)("Government Index Search API", () => {
+ it("serves a search as web results", async () => {
+ const identity = await idmux({
+ name: "gov/get",
+ credits: 100,
+ });
+
+ const res = await researchRaw(
+ PATH,
+ { query: "food labeling requirements", k: 3 },
+ identity,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body.success).toBe(true);
+ expect(Array.isArray(res.body.data.web)).toBe(true);
+ expect(res.body.data.web.length).toBeGreaterThan(0);
+ expect(res.body.data.web.length).toBeLessThanOrEqual(3);
+ for (const result of res.body.data.web) {
+ expect(typeof result.url).toBe("string");
+ expect(typeof result.title).toBe("string");
+ expect(typeof result.description).toBe("string");
+ expect(typeof result.position).toBe("number");
+ }
+ }, 120000);
+});
diff --git a/apps/api/src/__tests__/snips/v2/key-restriction.test.ts b/apps/api/src/__tests__/snips/v2/key-restriction.test.ts
index 3e63502d2..794c8e749 100644
--- a/apps/api/src/__tests__/snips/v2/key-restriction.test.ts
+++ b/apps/api/src/__tests__/snips/v2/key-restriction.test.ts
@@ -163,6 +163,29 @@ describeIf(TEST_PRODUCTION)(
scrapeTimeout * 2,
);
+ it.concurrent(
+ "gates the gov search category on the research group",
+ async () => {
+ const identity = await idmux({
+ name: "key-restriction/gov-category",
+ credits: 10000,
+ flags: { keyRestriction: true },
+ });
+ await seedRestriction(identity, { allowedEndpoints: ["search"] });
+
+ const withGov = await searchRaw(
+ { query: "zoning variance", categories: ["gov"] },
+ identity,
+ );
+ expect(withGov.statusCode).toBe(403);
+ expect(withGov.body.success).toBe(false);
+ expect(withGov.body.error).toContain(
+ "restricted to the following endpoints",
+ );
+ },
+ scrapeTimeout * 2,
+ );
+
it.concurrent(
"does not restrict a flagged team before it configures a restriction",
async () => {
diff --git a/apps/api/src/__tests__/snips/v2/types-validation.test.ts b/apps/api/src/__tests__/snips/v2/types-validation.test.ts
index 48bc79bfe..19a30933a 100644
--- a/apps/api/src/__tests__/snips/v2/types-validation.test.ts
+++ b/apps/api/src/__tests__/snips/v2/types-validation.test.ts
@@ -1503,6 +1503,34 @@ describe("V2 Types Validation", () => {
).toThrow();
});
+ it("should accept the gov category on its own and reject params or mixing", () => {
+ expect(
+ searchRequestSchema.parse({ query: "test", categories: ["gov"] })
+ .categories,
+ ).toEqual([{ type: "gov" }]);
+
+ expect(
+ searchRequestSchema.parse({
+ query: "test",
+ categories: [{ type: "gov" }],
+ }).categories,
+ ).toEqual([{ type: "gov" }]);
+
+ expect(() =>
+ searchRequestSchema.parse({
+ query: "test",
+ categories: [{ type: "gov", sites: ["ecfr.gov"] }],
+ }),
+ ).toThrow();
+
+ expect(() =>
+ searchRequestSchema.parse({
+ query: "test",
+ categories: ["gov", "pdf"],
+ }),
+ ).toThrow();
+ });
+
it("should normalize every developer category alias to developer", () => {
const aliases = [
"repo",
diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts
index eca0463b6..ea99bc37d 100644
--- a/apps/api/src/config.ts
+++ b/apps/api/src/config.ts
@@ -112,6 +112,7 @@ const configSchema = z.object({
.positive()
.default(50),
RESEARCH_PROXY_URL: z.string().url().optional(),
+ SEARCH_PLATFORM_URL: z.string().url().optional(),
RESEARCH_KEYLESS_DISABLED: researchKeylessDisabled,
LABS_SEARCH_URL: z.string().url().optional(),
LABS_SEARCH_SECRET: z.string().optional(),
diff --git a/apps/api/src/controllers/auth.ts b/apps/api/src/controllers/auth.ts
index 8e6e6c3f9..940fe85b0 100644
--- a/apps/api/src/controllers/auth.ts
+++ b/apps/api/src/controllers/auth.ts
@@ -676,9 +676,11 @@ async function handleKeylessAuth(
? "research"
: mode === RateLimiterMode.DeveloperSearch
? "developer"
- : mode === RateLimiterMode.BrowserExecute
- ? "interact"
- : "scrape";
+ : mode === RateLimiterMode.GovSearch
+ ? "gov"
+ : mode === RateLimiterMode.BrowserExecute
+ ? "interact"
+ : "scrape";
let result: Awaited<ReturnType<typeof consumeKeylessRequest>>;
try {
diff --git a/apps/api/src/controllers/v2/__tests__/gov-search.test.ts b/apps/api/src/controllers/v2/__tests__/gov-search.test.ts
new file mode 100644
index 000000000..9cf4f69e8
--- /dev/null
+++ b/apps/api/src/controllers/v2/__tests__/gov-search.test.ts
@@ -0,0 +1,221 @@
+import { vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ logRequest: vi.fn(),
+ logResearchEndpoint: vi.fn(),
+ fetchGovUpstream: vi.fn(),
+ chargeKeylessCredits: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock("../../../services/logging/log_job", () => ({
+ logRequest: mocks.logRequest,
+ logResearchEndpoint: mocks.logResearchEndpoint,
+}));
+
+vi.mock("../../../lib/research-upstream", () => ({
+ fetchResearchUpstream: vi.fn(),
+ fetchGovUpstream: mocks.fetchGovUpstream,
+}));
+
+vi.mock("../../../services/billing/credit_billing", () => ({
+ billTeam: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock("../../../lib/keyless", async importOriginal => {
+ const actual = await importOriginal<typeof import("../../../lib/keyless")>();
+ return { ...actual, chargeKeylessCredits: mocks.chargeKeylessCredits };
+});
+
+vi.mock("../../../lib/logger", () => ({
+ logger: {
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ debug: vi.fn(),
+ child: vi.fn().mockReturnThis(),
+ },
+}));
+
+import { createGovRouter } from "../research-proxy";
+import { billTeam } from "../../../services/billing/credit_billing";
+import { keylessTeamId } from "../../../lib/keyless";
+
+const TEAM_ID = "11111111-1111-1111-1111-111111111111";
+const KEYLESS_TEAM_ID = keylessTeamId("203.0.113.7");
+
+const flush = () => new Promise(resolve => setImmediate(resolve));
+
+function handler(method: "get" | "post") {
+ const router: any = createGovRouter();
+ const layer = router.stack.find(
+ (l: any) => l.route?.path === "/" && l.route?.methods?.[method],
+ );
+ return layer.route.stack[0].handle;
+}
+
+function makeReq(
+ method: "GET" | "POST",
+ input: Record<string, unknown>,
+ teamId: string = TEAM_ID,
+ flags: Record<string, unknown> | null = {},
+) {
+ return {
+ method,
+ query: method === "GET" ? input : {},
+ body: method === "POST" ? input : {},
+ headers: {},
+ auth: { team_id: teamId },
+ acuc: { api_key_id: 7, flags },
+ } as any;
+}
+
+function makeRes() {
+ const res: any = {
+ status: vi.fn(),
+ json: vi.fn(),
+ send: vi.fn(),
+ end: vi.fn(),
+ setHeader: vi.fn(),
+ };
+ res.status.mockReturnValue(res);
+ res.json.mockReturnValue(res);
+ res.send.mockReturnValue(res);
+ return res;
+}
+
+function upstreamWith(web: unknown[]) {
+ return {
+ ok: true,
+ status: 200,
+ headers: new Headers(),
+ text: async () => JSON.stringify({ success: true, data: { web } }),
+ };
+}
+
+const WEB_RESULT = {
+ url: "https://www.ecfr.gov/current/title-21/part-101",
+ title: "21 CFR Part 101",
+ description: "Food labeling",
+ position: 1,
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.logRequest.mockResolvedValue(undefined);
+ mocks.logResearchEndpoint.mockResolvedValue(undefined);
+ mocks.fetchGovUpstream.mockResolvedValue(upstreamWith([WEB_RESULT]));
+});
+
+describe("/v2/search/gov", () => {
+ it.each(["GET", "POST"] as const)(
+ "serves a %s request for free",
+ async method => {
+ const res = makeRes();
+ await handler(method === "GET" ? "get" : "post")(
+ makeReq(method, { query: "food labeling rules", k: "5" }),
+ res,
+ );
+ await flush();
+
+ expect(mocks.fetchGovUpstream).toHaveBeenCalledWith(
+ expect.objectContaining({ query: "food labeling rules", k: 5 }),
+ );
+ expect(res.status).toHaveBeenCalledWith(200);
+ expect(res.json).toHaveBeenCalledWith({
+ success: true,
+ data: { web: [WEB_RESULT] },
+ });
+ expect(billTeam).not.toHaveBeenCalled();
+ expect(mocks.logResearchEndpoint).toHaveBeenCalledWith(
+ expect.objectContaining({
+ table: "gov_searches",
+ num_results: 1,
+ credits_cost: 0,
+ is_successful: true,
+ }),
+ );
+ },
+ );
+
+ it("stays free under zero data retention and marks the logs", async () => {
+ const res = makeRes();
+ await handler("get")(
+ makeReq("GET", { query: "food labeling rules" }, TEAM_ID, {
+ searchZDR: "forced-zdr",
+ }),
+ res,
+ );
+ await flush();
+
+ expect(billTeam).not.toHaveBeenCalled();
+ expect(mocks.logResearchEndpoint).toHaveBeenCalledWith(
+ expect.objectContaining({ credits_cost: 0, zeroDataRetention: true }),
+ );
+ });
+
+ it("passes an upstream error through without billing", async () => {
+ mocks.fetchGovUpstream.mockResolvedValue({
+ ok: false,
+ status: 500,
+ headers: new Headers(),
+ text: async () =>
+ JSON.stringify({ success: false, error: "index unavailable" }),
+ });
+ const res = makeRes();
+ await handler("get")(makeReq("GET", { query: "zoning variance" }), res);
+ await flush();
+
+ expect(res.status).toHaveBeenCalledWith(500);
+ expect(billTeam).not.toHaveBeenCalled();
+ expect(mocks.logResearchEndpoint).toHaveBeenCalledWith(
+ expect.objectContaining({
+ is_successful: false,
+ credits_cost: 0,
+ error: "index unavailable",
+ }),
+ );
+ });
+
+ it.each([
+ ["GET", { query: "" }],
+ ["GET", { query: "rules", k: "101" }],
+ ["GET", { query: "rules", magic: "true" }],
+ ["POST", { query: "rules", magic: "true" }],
+ ] as const)(
+ "rejects invalid %s input %j before the upstream call",
+ async (method, input) => {
+ const res = makeRes();
+ await handler(method === "GET" ? "get" : "post")(
+ makeReq(method, input),
+ res,
+ );
+ await flush();
+
+ expect(res.status).toHaveBeenCalledWith(400);
+ expect(mocks.fetchGovUpstream).not.toHaveBeenCalled();
+ },
+ );
+
+ it("maps an upstream timeout to 504", async () => {
+ mocks.fetchGovUpstream.mockRejectedValue(
+ new DOMException("timed out", "TimeoutError"),
+ );
+ const res = makeRes();
+ await handler("get")(makeReq("GET", { query: "zoning variance" }), res);
+ await flush();
+
+ expect(res.status).toHaveBeenCalledWith(504);
+ });
+
+ it("serves a keyless caller and records zero keyless credits", async () => {
+ const res = makeRes();
+ await handler("get")(
+ makeReq("GET", { query: "zoning variance" }, KEYLESS_TEAM_ID, null),
+ res,
+ );
+ await flush();
+
+ expect(res.status).toHaveBeenCalledWith(200);
+ expect(mocks.chargeKeylessCredits).toHaveBeenCalledWith(KEYLESS_TEAM_ID, 0);
+ });
+});
diff --git a/apps/api/src/controllers/v2/__tests__/search-developer-ledger.test.ts b/apps/api/src/controllers/v2/__tests__/search-developer-ledger.test.ts
index c08625173..6815abee2 100644
--- a/apps/api/src/controllers/v2/__tests__/search-developer-ledger.test.ts
+++ b/apps/api/src/controllers/v2/__tests__/search-developer-ledger.test.ts
@@ -86,7 +86,7 @@ function executeResult(overrides: Record<string, any> = {}) {
return {
response: { web: developerResults },
totalResultsCount: 2,
- developerResultsCount: 2,
+ indexResultsCount: 2,
searchCredits: 2,
scrapeCredits: 0,
totalCredits: 2,
@@ -273,7 +273,7 @@ describe("developer category code_searches ledger", () => {
executeResult({
response: { web: [] },
totalResultsCount: 0,
- developerResultsCount: 0,
+ indexResultsCount: 0,
}),
);
const req = makeReq({ query: "http client", categories: ["developer"] });
@@ -326,3 +326,34 @@ describe("developer category code_searches ledger", () => {
expect(res.status).not.toHaveBeenCalledWith(403);
});
});
+
+describe("gov category gov_searches ledger", () => {
+ it("writes exactly one gov_searches row for a gov category search", async () => {
+ const req = makeReq({ query: "zoning variance", categories: ["gov"] });
+ const res = makeRes();
+
+ await searchController(req, res);
+ await flushAsync();
+
+ expect(res.status).toHaveBeenCalledWith(200);
+ expect(mockLogResearchEndpoint).toHaveBeenCalledTimes(1);
+ const row = mockLogResearchEndpoint.mock.calls[0][0];
+ expect(row.table).toBe("gov_searches");
+ expect(row.target).toBe("zoning variance");
+ expect(row.num_results).toBe(2);
+ expect(row.options.categories).toEqual([{ type: "gov" }]);
+ expect(row.options.via).toBe("search_category");
+ });
+
+ it("reserves no keyless credits for a gov category search", async () => {
+ mockProjectSearchTotalCredits.mockReturnValue(2);
+ mockReserveKeylessCredits.mockResolvedValue({ ok: false });
+ const req = makeReq({ query: "zoning variance", categories: ["gov"] });
+ const res = makeRes();
+
+ await searchController(req, res);
+
+ expect(mockReserveKeylessCredits).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(200);
+ });
+});
diff --git a/apps/api/src/controllers/v2/research-proxy.ts b/apps/api/src/controllers/v2/research-proxy.ts
index cf8d9e363..372adace1 100644
--- a/apps/api/src/controllers/v2/research-proxy.ts
+++ b/apps/api/src/controllers/v2/research-proxy.ts
@@ -3,7 +3,10 @@ import { externalRequestId } from "../../lib/external-request-id";
import { z } from "zod";
import { v7 as uuidv7 } from "uuid";
import { logger as rootLogger } from "../../lib/logger";
-import { fetchResearchUpstream } from "../../lib/research-upstream";
+import {
+ fetchGovUpstream,
+ fetchResearchUpstream,
+} from "../../lib/research-upstream";
import { chargeKeylessCredits } from "../../lib/keyless";
import { billTeam } from "../../services/billing/credit_billing";
import { getEffectiveSearchForcedKind } from "../../lib/safe-mode";
@@ -25,6 +28,7 @@ const SEARCH_CREDITS_PER_TEN_RESULTS = 2;
const ZDR_SEARCH_CREDITS_PER_TEN_RESULTS = 10;
const DEVELOPER_SEARCH_TIMEOUT_MS = 15_000;
+const GOV_SEARCH_TIMEOUT_MS = 15_000;
const PAPER_SEARCH_TIMEOUT_MS = 30_000;
const PAPER_INSPECT_TIMEOUT_MS = 5_000;
const SIMILAR_PAPERS_TIMEOUT_MS = 10_000;
@@ -138,6 +142,12 @@ const DEVELOPER_SEARCH_QUERY_KEYS = [
"skills",
];
+const govSearchSchema = z.strictObject({
+ query: z.string().min(1),
+ k: kSchema(100),
+ ...commonQuery,
+});
+
type ResearchEndpointConfig = {
kind: ResearchRequestKind;
table: ResearchTableName;
@@ -146,13 +156,22 @@ type ResearchEndpointConfig = {
params: Record<string, any>,
req: RequestWithAuth<any, any, any>,
) => string;
- upstreamPath: (
- params: Record<string, any>,
- req: RequestWithAuth<any, any, any>,
- ) => string;
timeoutMs?: number;
billAs: "scrape" | "search";
-};
+} & (
+ | {
+ upstreamPath: (
+ params: Record<string, any>,
+ req: RequestWithAuth<any, any, any>,
+ ) => string;
+ }
+ | {
+ fetchUpstream: (
+ params: Record<string, any>,
+ headers: Record<string, string>,
+ ) => ReturnType<typeof fetchResearchUpstream>;
+ }
+);
type ResearchController = (req: Request, res: Response) => Promise<any>;
type ResearchQueryParams = Record<string, any> & {
@@ -203,7 +222,8 @@ function addLegacySnakeCaseAliases<T>(value: T): T {
}
function resultCount(body: any): number {
- return Array.isArray(body?.results) ? body.results.length : 0;
+ if (Array.isArray(body?.results)) return body.results.length;
+ return Array.isArray(body?.data?.web) ? body.data.web.length : 0;
}
function creditsFor(
@@ -211,14 +231,16 @@ function creditsFor(
body: any,
req: RequestWithAuth<any, any, any>,
) {
- // Make certain research index accesses free (AI/ML & life-sciences indices).
- // Research paper endpoints should have no credit cost. Explicit exceptions
- // remain billable: GitHub search and developer/code search.
+ // Make certain index accesses free (AI/ML & life-sciences indices and the
+ // gov index). Research paper and gov endpoints should have no credit cost.
+ // Explicit exceptions remain billable: GitHub search and developer/code
+ // search.
const freeResearchKinds = new Set([
"research_paper_search",
"research_related_papers",
"research_paper_read",
"research_paper_inspect",
+ "gov_search",
]);
if (freeResearchKinds.has(config.kind)) return 0;
@@ -256,10 +278,9 @@ function isResearchTimeoutError(error: unknown): boolean {
async function fetchForRequest(
req: RequestWithAuth<any, any, any>,
- path: string,
- params: Record<string, unknown>,
+ endpoint: ResearchEndpointConfig,
+ params: Record<string, any>,
queryKeys: string[],
- timeoutMs?: number,
) {
const headers: Record<string, string> = {};
for (const h of FORWARDED_REQUEST_HEADERS) {
@@ -268,12 +289,16 @@ async function fetchForRequest(
}
headers["firecrawl-team-id"] = req.auth.team_id;
+ if ("fetchUpstream" in endpoint) {
+ return endpoint.fetchUpstream(params, headers);
+ }
+
return fetchResearchUpstream({
- path,
+ path: endpoint.upstreamPath(params, req),
params,
queryKeys,
headers,
- timeoutMs,
+ timeoutMs: endpoint.timeoutMs,
});
}
@@ -336,10 +361,9 @@ function createResearchController(
try {
const upstream = await fetchForRequest(
authedReq,
- endpoint.upstreamPath(params, authedReq),
+ endpoint,
params,
queryKeys,
- endpoint.timeoutMs,
);
if (!upstream) {
statusCode = 404;
@@ -577,3 +601,29 @@ export function createDeveloperRouter(options: { root?: boolean } = {}) {
return router;
}
+
+export function createGovRouter() {
+ const router = express.Router();
+
+ const controller = wrap(
+ createResearchController(govSearchSchema, [], {
+ kind: "gov_search",
+ table: "gov_searches",
+ action: "searchGov",
+ targetHint: params => String(params.query),
+ billAs: "search",
+ fetchUpstream: (params, headers) =>
+ fetchGovUpstream({
+ query: params.query,
+ k: params.k,
+ headers,
+ timeoutMs: GOV_SEARCH_TIMEOUT_MS,
+ }),
+ }),
+ );
+
+ router.get("/", controller);
+ router.post("/", controller);
+
+ return router;
+}
diff --git a/apps/api/src/controllers/v2/search.ts b/apps/api/src/controllers/v2/search.ts
index 22e385d5e..16cc36351 100644
--- a/apps/api/src/controllers/v2/search.ts
+++ b/apps/api/src/controllers/v2/search.ts
@@ -51,6 +51,7 @@ import {
formatTypesOf,
} from "../../lib/key-restriction";
import { wantsDeveloperCategory } from "../../search/developer";
+import { wantsGovCategory } from "../../search/gov";
import { requestOrigin } from "../../lib/request-origin";
import { isAgentInteropSecretValid } from "../../lib/agent-interop";
import { applyNotice, type Notice } from "../../lib/deprecations";
@@ -192,16 +193,28 @@ async function searchControllerInner(
});
}
- if (wantsDeveloperCategory(req.body.categories as CategoryOption[])) {
- const developerRestriction = await checkKeyEndpointRestriction(
- "/v2/developer/search",
+ const categories = req.body.categories as CategoryOption[];
+ // Index categories reach the same upstream as their dedicated endpoint, so
+ // they share its key restriction and its request ledger.
+ const indexCategory = wantsDeveloperCategory(categories)
+ ? { endpoint: "/v2/developer/search", table: "code_searches" as const }
+ : wantsGovCategory(categories)
+ ? {
+ endpoint: "/v2/search/gov",
+ table: "gov_searches" as const,
+ }
+ : null;
+
+ if (indexCategory) {
+ const indexRestriction = await checkKeyEndpointRestriction(
+ indexCategory.endpoint,
req.acuc?.api_key_id,
req.acuc?.flags ?? null,
);
- if (!developerRestriction.allowed) {
- return res.status(developerRestriction.status).json({
+ if (!indexRestriction.allowed) {
+ return res.status(indexRestriction.status).json({
success: false,
- error: developerRestriction.error,
+ error: indexRestriction.error,
});
}
}
@@ -354,7 +367,10 @@ async function searchControllerInner(
const toolsOnly = isToolsOnlySearch(req.body.sources, req.body.categories);
const projectedKeylessCredits =
- !isSearchPreview && shouldBill && !toolsOnly
+ !isSearchPreview &&
+ shouldBill &&
+ !toolsOnly &&
+ !wantsGovCategory(categories)
? projectSearchTotalCredits(
{
limit: req.body.limit,
@@ -485,9 +501,9 @@ async function searchControllerInner(
logger.error("Failed to log search", { error, jobId });
});
- if (wantsDeveloperCategory(req.body.categories as CategoryOption[])) {
+ if (indexCategory) {
logResearchEndpoint({
- table: "code_searches",
+ table: indexCategory.table,
id: uuidv7(),
request_id: agentRequestId ?? jobId,
team_id: req.auth.team_id,
@@ -500,7 +516,7 @@ async function searchControllerInner(
via: "search_category",
},
response: null,
- num_results: result.developerResultsCount,
+ num_results: result.indexResultsCount,
time_taken: timeTakenInSeconds,
// Ensure preview-mode searches don't get a non-zero credits_cost
// in the research ledger when preview tokens are used.
@@ -508,7 +524,7 @@ async function searchControllerInner(
is_successful: true,
zeroDataRetention,
}).catch(ledgerError => {
- logger.warn("Failed to log developer category usage", {
+ logger.warn("Failed to log index category usage", {
error: ledgerError,
});
});
diff --git a/apps/api/src/controllers/v2/types.ts b/apps/api/src/controllers/v2/types.ts
index 59cee1425..c4a202ef4 100644
--- a/apps/api/src/controllers/v2/types.ts
+++ b/apps/api/src/controllers/v2/types.ts
@@ -2444,6 +2444,10 @@ const developerCategoryOptions = z.strictObject({
type: z.literal("developer"),
});
+const govCategoryOptions = z.strictObject({
+ type: z.literal("gov"),
+});
+
const developerCategoryAliases = new Set([
"repo",
"code",
@@ -2529,13 +2533,14 @@ export const searchRequestSchema = z
.preprocess(
normalizeDeveloperCategoryAliases,
z.union([
- z.array(z.enum(["github", "research", "pdf", "developer"])),
+ z.array(z.enum(["github", "research", "pdf", "developer", "gov"])),
z.array(
z.union([
githubCategoryOptions,
researchCategoryOptions,
pdfCategoryOptions,
developerCategoryOptions,
+ govCategoryOptions,
]),
),
]),
@@ -2615,6 +2620,10 @@ export const searchRequestSchema = z
const categories = x.categories ?? [];
return !hasCategory(categories, "developer") || categories.length === 1;
}, "the developer category cannot be combined with other categories")
+ .refine(x => {
+ const categories = x.categories ?? [];
+ return !hasCategory(categories, "gov") || categories.length === 1;
+ }, "the gov category cannot be combined with other categories")
.refine(x => waitForRefine(x.scrapeOptions), waitForRefineOpts)
.transform(x => {
const country =
@@ -2682,6 +2691,10 @@ export const searchRequestSchema = z
return {
type: "developer" as const,
};
+ case "gov":
+ return {
+ type: "gov" as const,
+ };
default:
return { type: c as any };
}
diff --git a/apps/api/src/db/schema/public.ts b/apps/api/src/db/schema/public.ts
index aaf634b0c..5525ff708 100644
--- a/apps/api/src/db/schema/public.ts
+++ b/apps/api/src/db/schema/public.ts
@@ -227,6 +227,8 @@ export const research_github_searches = researchEndpointTable(
export const code_searches = researchEndpointTable("code_searches");
+export const gov_searches = researchEndpointTable("gov_searches");
+
export const deterministic_json_scripts = pgTable(
"deterministic_json_scripts",
{
diff --git a/apps/api/src/lib/key-restriction.test.ts b/apps/api/src/lib/key-restriction.test.ts
index 4c54873c0..48467650c 100644
--- a/apps/api/src/lib/key-restriction.test.ts
+++ b/apps/api/src/lib/key-restriction.test.ts
@@ -93,6 +93,12 @@ describe("classifyEndpoint", () => {
});
});
+ it("groups government search with research", () => {
+ expect(classifyEndpoint("/v2/search/gov")).toMatchObject({
+ group: "research",
+ });
+ });
+
it("marks account/metadata endpoints as always allowed", () => {
expect(classifyEndpoint("/v2/team/credit-usage")).toMatchObject({
alwaysAllowed: true,
diff --git a/apps/api/src/lib/key-restriction.ts b/apps/api/src/lib/key-restriction.ts
index 1de6f96e8..2532afcda 100644
--- a/apps/api/src/lib/key-restriction.ts
+++ b/apps/api/src/lib/key-restriction.ts
@@ -112,6 +112,7 @@ const ENDPOINT_GROUPS: [string[], string][] = [
[["map"], "map"],
[["search", "research"], "research"],
[["search", "developer"], "research"],
+ [["search", "gov"], "research"],
[["search"], "search"],
[["extract"], "extract"],
[["agent"], "agent"],
diff --git a/apps/api/src/lib/research-upstream.ts b/apps/api/src/lib/research-upstream.ts
index a3f01eade..243b15ef5 100644
--- a/apps/api/src/lib/research-upstream.ts
+++ b/apps/api/src/lib/research-upstream.ts
@@ -47,3 +47,21 @@ export async function fetchResearchUpstream(options: {
dispatcher,
});
}
+
+export async function fetchGovUpstream(options: {
+ query: string;
+ k?: number;
+ headers: Record<string, string>;
+ timeoutMs: number;
+}) {
+ const base = config.SEARCH_PLATFORM_URL;
+ if (!base) return null;
+
+ return fetch(base.replace(/\/+$/, "") + "/api/v1/gov-search", {
+ method: "POST",
+ headers: { ...options.headers, "content-type": "application/json" },
+ body: JSON.stringify({ query: options.query, top_k: options.k }),
+ signal: AbortSignal.timeout(options.timeoutMs),
+ dispatcher,
+ });
+}
diff --git a/apps/api/src/lib/search-query-builder.ts b/apps/api/src/lib/search-query-builder.ts
index bcbd6d5aa..7b3e531e1 100644
--- a/apps/api/src/lib/search-query-builder.ts
+++ b/apps/api/src/lib/search-query-builder.ts
@@ -4,7 +4,7 @@
*/
interface CategoryInput {
- type: "github" | "research" | "pdf" | "developer";
+ type: "github" | "research" | "pdf" | "developer" | "gov";
sites?: string[];
}
diff --git a/apps/api/src/routes/v2.ts b/apps/api/src/routes/v2.ts
index 349f57cb6..c5bb5ae1e 100644
--- a/apps/api/src/routes/v2.ts
+++ b/apps/api/src/routes/v2.ts
@@ -93,6 +93,7 @@ import {
import { supportProxyController } from "../controllers/v2/support-proxy";
import {
createDeveloperRouter,
+ createGovRouter,
createResearchRouter,
} from "../controllers/v2/research-proxy";
import {
@@ -740,3 +741,13 @@ if (config.RESEARCH_PROXY_URL) {
createDeveloperRouter(),
);
}
+
+if (config.SEARCH_PLATFORM_URL) {
+ v2Router.use(
+ "/search/gov",
+ authMiddleware(RateLimiterMode.GovSearch, {
+ allowKeyless: true,
+ }),
+ createGovRouter(),
+ );
+}
diff --git a/apps/api/src/search/alexandria.ts b/apps/api/src/search/alexandria.ts
index 40cbe6e26..af1968929 100644
--- a/apps/api/src/search/alexandria.ts
+++ b/apps/api/src/search/alexandria.ts
@@ -29,7 +29,10 @@ export function isToolsOnlySearch(
if (!sources.every(source => typeOf(source) === "alexandria")) return false;
if (
Array.isArray(categories) &&
- categories.some(category => typeOf(category) === "developer")
+ categories.some(category => {
+ const type = typeOf(category);
+ return type === "developer" || type === "gov";
+ })
)
return false;
return true;
diff --git a/apps/api/src/search/execute.test.ts b/apps/api/src/search/execute.test.ts
index 34def52eb..15b3a3ab6 100644
--- a/apps/api/src/search/execute.test.ts
+++ b/apps/api/src/search/execute.test.ts
@@ -1,6 +1,7 @@
const mocks = vi.hoisted(() => ({
search: vi.fn(),
searchDeveloperCategory: vi.fn(),
+ searchGovCategory: vi.fn(),
checkUrlsAgainstThreatPolicy: vi.fn(),
discoverTools: vi.fn(),
removeExplicitResults: vi.fn(),
@@ -22,6 +23,15 @@ vi.mock("./developer", () => ({
),
searchDeveloperCategory: mocks.searchDeveloperCategory,
}));
+vi.mock("./gov", () => ({
+ wantsGovCategory: (categories?: Array<string | { type: string }>) =>
+ (categories ?? []).some(category =>
+ typeof category === "string"
+ ? category === "gov"
+ : category.type === "gov",
+ ),
+ searchGovCategory: mocks.searchGovCategory,
+}));
vi.mock("./scrape", () => ({
getItemsToScrape: vi.fn(() => []),
scrapeSearchResults: vi.fn(),
@@ -192,7 +202,7 @@ describe("executeSearch developer category", () => {
expect(mocks.search).not.toHaveBeenCalled();
expect(result.response).toEqual({ web: [developerResult] });
expect(result.response).not.toHaveProperty("developer");
- expect(result.developerResultsCount).toBe(1);
+ expect(result.indexResultsCount).toBe(1);
});
it("filters blocked developer results via threat protection and renumbers", async () => {
@@ -258,3 +268,33 @@ describe("executeSearch developer category", () => {
expect(sole.success).toBe(true);
});
});
+
+describe("executeSearch gov category", () => {
+ const govResult = {
+ url: "https://www.ecfr.gov/current/title-21/part-101",
+ title: "21 CFR Part 101",
+ description: "Food labeling",
+ position: 1,
+ category: "gov",
+ };
+
+ it("returns sole gov-category results in web without running SERP", async () => {
+ mocks.searchGovCategory.mockResolvedValue([govResult]);
+
+ const result = await executeSearch(
+ options([{ type: "gov" }]),
+ context,
+ logger,
+ );
+
+ expect(mocks.search).not.toHaveBeenCalled();
+ expect(mocks.searchDeveloperCategory).not.toHaveBeenCalled();
+ expect(mocks.searchGovCategory).toHaveBeenCalledWith(
+ { query: "retries", limit: 10, teamId: "team-1", timeout: 1_000 },
+ logger,
+ );
+ expect(result.response).toEqual({ web: [govResult] });
+ expect(result.indexResultsCount).toBe(1);
+ expect(result.searchCredits).toBe(0);
+ });
+});
diff --git a/apps/api/src/search/execute.ts b/apps/api/src/search/execute.ts
index 7689026cd..d3e9aca04 100644
--- a/apps/api/src/search/execute.ts
+++ b/apps/api/src/search/execute.ts
@@ -15,6 +15,7 @@ import {
calculateScrapeCredits,
} from "./scrape";
import { searchDeveloperCategory, wantsDeveloperCategory } from "./developer";
+import { searchGovCategory, wantsGovCategory } from "./gov";
import { removeExplicitResults } from "./safe-search";
import {
highlightsEnvReady,
@@ -75,22 +76,13 @@ interface SearchExecuteResult {
toolsWarning?: string;
response: SearchV2Response;
totalResultsCount: number;
- developerResultsCount: number;
+ indexResultsCount: number;
searchCredits: number;
scrapeCredits: number;
totalCredits: number;
shouldScrape: boolean;
}
-function hasOnlyDeveloperCategory(categories?: CategoryOption[]): boolean {
- if (!categories?.length) return false;
- return categories.every(category =>
- typeof category === "string"
- ? category === "developer"
- : category.type === "developer",
- );
-}
-
export async function executeSearch(
options: SearchOptions,
context: SearchContext,
@@ -130,16 +122,22 @@ export async function executeSearch(
},
);
- const wantsDeveloper = wantsDeveloperCategory(categories);
- const developerResultsPromise = wantsDeveloper
- ? searchDeveloperCategory(
+ // The developer and gov categories are each exclusive (schema-enforced) and
+ // are served from their own index instead of the web SERP.
+ const indexCategorySearch = wantsDeveloperCategory(categories)
+ ? searchDeveloperCategory
+ : wantsGovCategory(categories)
+ ? searchGovCategory
+ : null;
+ const indexResultsPromise = indexCategorySearch
+ ? indexCategorySearch(
{ query, limit, teamId, timeout: options.timeout },
logger,
)
: null;
const searchResponse =
- (wantsTools && !searchTypes.length) || hasOnlyDeveloperCategory(categories)
+ (wantsTools && !searchTypes.length) || indexResultsPromise !== null
? ({} as SearchV2Response)
: ((await search({
query: searchQuery,
@@ -158,9 +156,7 @@ export async function executeSearch(
includeDomains: options.includeDomains,
excludeDomains: options.excludeDomains,
})) as SearchV2Response);
- let developerResults = developerResultsPromise
- ? await developerResultsPromise
- : [];
+ let indexResults = indexResultsPromise ? await indexResultsPromise : [];
// Threat protection: remove blocked results entirely — before
// slicing/counting, before scraping, and before returning. Checks are
@@ -174,7 +170,7 @@ export async function executeSearch(
...(searchResponse.web ?? []).map(x => x.url),
...(searchResponse.news ?? []).map(x => x.url),
...(searchResponse.images ?? []).map(x => x.url),
- ...developerResults.map(x => x.url),
+ ...indexResults.map(x => x.url),
].filter((x): x is string => !!x);
if (urlsToCheck.length > 0) {
@@ -200,7 +196,7 @@ export async function executeSearch(
isAllowed(x.url),
);
}
- developerResults = developerResults.filter(x => isAllowed(x.url));
+ indexResults = indexResults.filter(x => isAllowed(x.url));
}
}
@@ -253,8 +249,8 @@ export async function executeSearch(
totalResultsCount += searchResponse.news.length;
}
- const developerResultsCount = developerResults.length;
- totalResultsCount += developerResultsCount;
+ const indexResultsCount = indexResults.length;
+ totalResultsCount += indexResultsCount;
let toolsWarning: string | undefined;
if (
@@ -274,7 +270,7 @@ export async function executeSearch(
: [
...(searchResponse.web ?? []),
...(searchResponse.news ?? []),
- ...developerResults,
+ ...indexResults,
].flatMap(item => (item.url ? [item.url] : [])),
timeoutMs: options.timeout,
},
@@ -286,12 +282,17 @@ export async function executeSearch(
const isZDR = options.enterprise?.includes("zdr");
const creditsPerTenResults = isZDR ? 10 : 2;
+ // Gov index results are free; developer index results bill like web results.
+ const billableResultsCount =
+ indexCategorySearch === searchGovCategory
+ ? totalResultsCount - indexResultsCount
+ : totalResultsCount;
// Threat protection scan fees ride on the search credits: they are part of
// serving the search itself (every result domain is scanned before
// filtering), so they bill against the same feature and show up in the
// request's creditsUsed.
const searchCredits =
- Math.ceil(totalResultsCount / 10) * creditsPerTenResults +
+ Math.ceil(billableResultsCount / 10) * creditsPerTenResults +
threatScanCredits;
let scrapeCredits = 0;
@@ -382,11 +383,11 @@ export async function executeSearch(
}
}
- if (wantsDeveloper) {
- // The developer category is exclusive (schema-enforced), so these are
- // the only results: they ARE the web group. Threat filtering above may
- // have removed entries, so renumber the survivors.
- searchResponse.web = developerResults.map((result, index) => ({
+ if (indexResultsPromise !== null) {
+ // An index category is exclusive, so these are the only results: they ARE
+ // the web group. Threat filtering above may have removed entries, so
+ // renumber the survivors.
+ searchResponse.web = indexResults.map((result, index) => ({
...result,
position: index + 1,
}));
@@ -434,7 +435,7 @@ export async function executeSearch(
response: searchResponse,
toolsWarning,
totalResultsCount,
- developerResultsCount,
+ indexResultsCount,
searchCredits,
scrapeCredits,
totalCredits: searchCredits + scrapeCredits,
diff --git a/apps/api/src/search/gov.test.ts b/apps/api/src/search/gov.test.ts
new file mode 100644
index 000000000..07482d81c
--- /dev/null
+++ b/apps/api/src/search/gov.test.ts
@@ -0,0 +1,124 @@
+vi.mock("undici", () => ({
+ Agent: class {},
+ fetch: vi.fn(),
+}));
+
+vi.mock("../config", () => ({
+ config: { SEARCH_PLATFORM_URL: "https://platform.test/" },
+}));
+
+import { fetch } from "undici";
+import { searchGovCategory } from "./gov";
+
+const fetchMock = vi.mocked(fetch);
+
+const logger = {
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+} as any;
+
+function upstreamOk(body: unknown) {
+ return { ok: true, status: 200, json: async () => body } as any;
+}
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("searchGovCategory", () => {
+ it("sends the query, the result count and the team", async () => {
+ fetchMock.mockResolvedValue(
+ upstreamOk({ success: true, data: { web: [] } }),
+ );
+
+ await searchGovCategory(
+ { query: "food labeling rules", limit: 7, teamId: "t1", timeout: 500 },
+ logger,
+ );
+
+ const [url, init] = fetchMock.mock.calls[0] as any[];
+ expect(url).toBe("https://platform.test/api/v1/gov-search");
+ expect(init.method).toBe("POST");
+ expect(JSON.parse(init.body)).toEqual({
+ query: "food labeling rules",
+ top_k: 7,
+ });
+ expect(init.headers["firecrawl-team-id"]).toBe("t1");
+ });
+
+ it("maps results to the exact web schema and tags the category", async () => {
+ fetchMock.mockResolvedValue(
+ upstreamOk({
+ success: true,
+ data: {
+ web: [
+ {
+ url: "https://www.ecfr.gov/current/title-21/part-101",
+ title: "21 CFR Part 101",
+ description: "Food labeling",
+ position: 42,
+ score: 0.9,
+ },
+ { url: "", title: "dropped", description: "", position: 43 },
+ {
+ url: "https://www.ecfr.gov/current/title-21/part-102",
+ title: " ",
+ position: 44,
+ },
+ ],
+ },
+ }),
+ );
+
+ const results = await searchGovCategory(
+ { query: "food labeling", limit: 5, teamId: "t1", timeout: 500 },
+ logger,
+ );
+
+ expect(results).toStrictEqual([
+ {
+ url: "https://www.ecfr.gov/current/title-21/part-101",
+ title: "21 CFR Part 101",
+ description: "Food labeling",
+ position: 1,
+ category: "gov",
+ },
+ {
+ url: "https://www.ecfr.gov/current/title-21/part-102",
+ title: "https://www.ecfr.gov/current/title-21/part-102",
+ description: "",
+ position: 3,
+ category: "gov",
+ },
+ ]);
+ });
+
+ it("returns no results and drains the body when the upstream fails", async () => {
+ const cancel = vi.fn(async () => {});
+ fetchMock.mockResolvedValue({
+ ok: false,
+ status: 503,
+ body: { cancel },
+ } as any);
+
+ await expect(
+ searchGovCategory(
+ { query: "zoning", limit: 5, teamId: "t1", timeout: 500 },
+ logger,
+ ),
+ ).resolves.toEqual([]);
+ expect(cancel).toHaveBeenCalledTimes(1);
+ });
+
+ it("returns no results when the upstream throws", async () => {
+ fetchMock.mockRejectedValue(new Error("connection reset"));
+
+ await expect(
+ searchGovCategory(
+ { query: "zoning", limit: 5, teamId: "t1", timeout: 500 },
+ logger,
+ ),
+ ).resolves.toEqual([]);
+ });
+});
diff --git a/apps/api/src/search/gov.ts b/apps/api/src/search/gov.ts
new file mode 100644
index 000000000..c22391792
--- /dev/null
+++ b/apps/api/src/search/gov.ts
@@ -0,0 +1,52 @@
+import type { Logger } from "winston";
+import type { WebSearchResult } from "../lib/entities";
+import { fetchGovUpstream } from "../lib/research-upstream";
+import { hasCategory, type CategoryOption } from "../lib/search-query-builder";
+
+export function wantsGovCategory(categories?: CategoryOption[]): boolean {
+ return hasCategory(categories, "gov");
+}
+
+export async function searchGovCategory(
+ options: { query: string; limit: number; teamId: string; timeout: number },
+ logger: Logger,
+): Promise<WebSearchResult[]> {
+ try {
+ const upstream = await fetchGovUpstream({
+ query: options.query,
+ k: options.limit,
+ headers: { "firecrawl-team-id": options.teamId },
+ timeoutMs: options.timeout,
+ });
+ if (upstream === null) {
+ return [];
+ }
+ if (!upstream.ok) {
+ await upstream.body?.cancel().catch(() => {});
+ logger.warn("Gov category upstream failed", { status: upstream.status });
+ return [];
+ }
+
+ const body: any = await upstream.json();
+ const results: any[] = Array.isArray(body?.data?.web) ? body.data.web : [];
+ return results
+ .slice(0, options.limit)
+ .map((result, index) => ({
+ url: typeof result?.url === "string" ? result.url : "",
+ title:
+ typeof result?.title === "string" && result.title.trim().length > 0
+ ? result.title
+ : typeof result?.url === "string"
+ ? result.url
+ : "",
+ description:
+ typeof result?.description === "string" ? result.description : "",
+ position: index + 1,
+ category: "gov",
+ }))
+ .filter(result => result.url.length > 0);
+ } catch (error) {
+ logger.warn("Gov category upstream error", { error });
+ return [];
+ }
+}
diff --git a/apps/api/src/services/logging/log_job.ts b/apps/api/src/services/logging/log_job.ts
index 9f741dc78..e95a29f50 100644
--- a/apps/api/src/services/logging/log_job.ts
+++ b/apps/api/src/services/logging/log_job.ts
@@ -131,6 +131,7 @@ const tableMap: Record<string, PgTable> = {
research_related_papers: schema.research_related_papers,
research_github_searches: schema.research_github_searches,
code_searches: schema.code_searches,
+ gov_searches: schema.gov_searches,
extracts: schema.extracts,
maps: schema.maps,
llmstxts: schema.llmstxts,
@@ -512,7 +513,8 @@ type LoggedRequest = {
| "research_paper_read"
| "research_related_papers"
| "research_github_search"
- | "code_search";
+ | "code_search"
+ | "gov_search";
api_version: string;
team_id: string;
origin?: string;
@@ -1193,7 +1195,8 @@ export type ResearchRequestKind =
| "research_paper_read"
| "research_related_papers"
| "research_github_search"
- | "code_search";
+ | "code_search"
+ | "gov_search";
export type ResearchTableName =
| "research_paper_searches"
@@ -1201,7 +1204,8 @@ export type ResearchTableName =
| "research_paper_reads"
| "research_related_papers"
| "research_github_searches"
- | "code_searches";
+ | "code_searches"
+ | "gov_searches";
type LoggedResearchEndpoint = {
table: ResearchTableName;
diff --git a/apps/api/src/services/rate-limiter.ts b/apps/api/src/services/rate-limiter.ts
index 65ef5d4f7..71a07010d 100644
--- a/apps/api/src/services/rate-limiter.ts
+++ b/apps/api/src/services/rate-limiter.ts
@@ -37,6 +37,7 @@ const fallbackRateLimits: Record<RateLimiterMode, number> = {
supportDocsSearch: 3,
research: 100,
developerSearch: 100,
+ govSearch: 100,
labs: 1000,
exchange: 100,
// Catalogue reads only; no paid tool runs behind them.
diff --git a/apps/api/src/types.ts b/apps/api/src/types.ts
index 4a72a6c68..85c4a81c7 100644
--- a/apps/api/src/types.ts
+++ b/apps/api/src/types.ts
@@ -159,6 +159,7 @@ export enum RateLimiterMode {
SupportDocsSearch = "supportDocsSearch",
Research = "research",
DeveloperSearch = "developerSearch",
+ GovSearch = "govSearch",
Labs = "labs",
Exchange = "exchange",
ExchangeDiscover = "exchangeDiscover",
diff --git a/apps/test-site/pnpm-lock.yaml b/apps/test-site/pnpm-lock.yaml
index e15be855e..52b1eff58 100644
--- a/apps/test-site/pnpm-lock.yaml
+++ b/apps/test-site/pnpm-lock.yaml
@@ -20,7 +20,7 @@ overrides:
nanoid@>=3.0.0 <3.3.18: 3.3.18
esbuild@>=0.17.0 <0.28.1: 0.28.1
svgo@>=4.0.0 <4.1.0: 4.1.0
- sharp@<0.35.4: 0.35.4
+ sharp@<0.35.5: 0.35.5
http-cache-semantics@>=4.0.0 <5.0.0: 4.3.0
importers:
@@ -40,8 +40,8 @@ importers:
specifier: ^7.3.2
version: 7.3.2(@emnapi/[email protected])(@emnapi/[email protected])(@types/[email protected])
sharp:
- specifier: ^0.35.4
- version: 0.35.4(@types/[email protected])
+ specifier: 0.35.5
+ version: 0.35.5(@types/[email protected])
devDependencies:
prettier:
specifier: ^3.8.1
@@ -406,160 +406,160 @@ packages:
resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA==}
+ resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==}
engines: {node: '>=20.9.0'}
cpu: [arm64]
os: [darwin]
- resolution: {integrity: sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw==}
+ resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==}
engines: {node: '>=20.9.0'}
cpu: [x64]
os: [darwin]
- resolution: {integrity: sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA==}
+ resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==}
engines: {node: '>=20.9.0'}
os: [freebsd]
- resolution: {integrity: sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg==}
+ resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==}
cpu: [arm64]
os: [darwin]
- resolution: {integrity: sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw==}
+ resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==}
cpu: [x64]
os: [darwin]
- resolution: {integrity: sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A==}
+ resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==}
cpu: [arm64]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA==}
+ resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==}
cpu: [arm]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w==}
+ resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==}
cpu: [ppc64]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ==}
+ resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==}
cpu: [riscv64]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q==}
+ resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==}
cpu: [s390x]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA==}
+ resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==}
cpu: [x64]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw==}
+ resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==}
cpu: [arm64]
os: [linux]
libc: [musl]
- resolution: {integrity: sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw==}
+ resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==}
cpu: [x64]
os: [linux]
libc: [musl]
- resolution: {integrity: sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ==}
+ resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==}
engines: {node: '>=20.9.0'}
cpu: [arm64]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A==}
+ resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==}
engines: {node: '>=20.9.0'}
cpu: [arm]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ==}
+ resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==}
engines: {node: '>=20.9.0'}
cpu: [ppc64]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA==}
+ resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==}
engines: {node: '>=20.9.0'}
cpu: [riscv64]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ==}
+ resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==}
engines: {node: '>=20.9.0'}
cpu: [s390x]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA==}
+ resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==}
engines: {node: '>=20.9.0'}
cpu: [x64]
os: [linux]
libc: [glibc]
- resolution: {integrity: sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA==}
+ resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==}
engines: {node: '>=20.9.0'}
cpu: [arm64]
os: [linux]
libc: [musl]
- resolution: {integrity: sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg==}
+ resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==}
engines: {node: '>=20.9.0'}
cpu: [x64]
os: [linux]
libc: [musl]
- resolution: {integrity: sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA==}
+ resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==}
engines: {node: '>=20.9.0'}
- resolution: {integrity: sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA==}
+ resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==}
engines: {node: '>=20.9.0'}
cpu: [wasm32]
- resolution: {integrity: sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw==}
+ resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==}
engines: {node: '>=20.9.0'}
cpu: [arm64]
os: [win32]
- resolution: {integrity: sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw==}
+ resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==}
engines: {node: ^20.9.0}
cpu: [ia32]
os: [win32]
- resolution: {integrity: sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg==}
+ resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==}
engines: {node: '>=20.9.0'}
cpu: [x64]
os: [win32]
@@ -1601,8 +1601,8 @@ packages:
engines: {node: '>=10'}
hasBin: true
- resolution: {integrity: sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA==}
+ resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==}
engines: {node: '>=20.9.0'}
peerDependencies:
'@types/node': '*'
@@ -2201,108 +2201,108 @@ snapshots:
'@img/[email protected]': {}
optionalDependencies:
- '@img/sharp-libvips-darwin-arm64': 1.3.3
+ '@img/sharp-libvips-darwin-arm64': 1.3.4
optional: true
optionalDependencies:
- '@img/sharp-libvips-darwin-x64': 1.3.3
+ '@img/sharp-libvips-darwin-x64': 1.3.4
optional: true
dependencies:
- '@img/sharp-wasm32': 0.35.4
+ '@img/sharp-wasm32': 0.35.5
optional: true
optional: true
optional: true
optional: true
optional: true
optional: true
optional: true
optional: true
optional: true
optional: true
optional: true
optionalDependencies:
- '@img/sharp-libvips-linux-arm64': 1.3.3
+ '@img/sharp-libvips-linux-arm64': 1.3.4
optional: true
optionalDependencies:
- '@img/sharp-libvips-linux-arm': 1.3.3
+ '@img/sharp-libvips-linux-arm': 1.3.4
optional: true
optionalDependencies:
- '@img/sharp-libvips-linux-ppc64': 1.3.3
+ '@img/sharp-libvips-linux-ppc64': 1.3.4
optional: true
optionalDependencies:
- '@img/sharp-libvips-linux-riscv64': 1.3.3
+ '@img/sharp-libvips-linux-riscv64': 1.3.4
optional: true
optionalDependencies:
- '@img/sharp-libvips-linux-s390x': 1.3.3
+ '@img/sharp-libvips-linux-s390x': 1.3.4
optional: true
optionalDependencies:
- '@img/sharp-libvips-linux-x64': 1.3.3
+ '@img/sharp-libvips-linux-x64': 1.3.4
optional: true
optionalDependencies:
- '@img/sharp-libvips-linuxmusl-arm64': 1.3.3
+ '@img/sharp-libvips-linuxmusl-arm64': 1.3.4
optional: true
optionalDependencies:
- '@img/sharp-libvips-linuxmusl-x64': 1.3.3
+ '@img/sharp-libvips-linuxmusl-x64': 1.3.4
optional: true
dependencies:
'@emnapi/runtime': 1.11.3
optional: true
dependencies:
- '@img/sharp-wasm32': 0.35.4
+ '@img/sharp-wasm32': 0.35.5
optional: true
optional: true
optional: true
optional: true
'@jridgewell/[email protected]': {}
@@ -2585,7 +2585,7 @@ snapshots:
yargs-parser: 22.0.0
zod: 4.5.4
optionalDependencies:
- sharp: 0.35.4(@types/[email protected])
+ sharp: 0.35.5(@types/[email protected])
transitivePeerDependencies:
- '@azure/app-configuration'
- '@azure/cosmos'
@@ -3832,37 +3832,37 @@ snapshots:
dependencies:
'@img/colour': 1.1.0
detect-libc: 2.1.2
semver: 7.8.5
optionalDependencies:
- '@img/sharp-darwin-arm64': 0.35.4
- '@img/sharp-darwin-x64': 0.35.4
- '@img/sharp-freebsd-wasm32': 0.35.4
- '@img/sharp-libvips-darwin-arm64': 1.3.3
- '@img/sharp-libvips-darwin-x64': 1.3.3
- '@img/sharp-libvips-linux-arm': 1.3.3
- '@img/sharp-libvips-linux-arm64': 1.3.3
- '@img/sharp-libvips-linux-ppc64': 1.3.3
- '@img/sharp-libvips-linux-riscv64': 1.3.3
- '@img/sharp-libvips-linux-s390x': 1.3.3
- '@img/sharp-libvips-linux-x64': 1.3.3
- '@img/sharp-libvips-linuxmusl-arm64': 1.3.3
- '@img/sharp-libvips-linuxmusl-x64': 1.3.3
- '@img/sharp-linux-arm': 0.35.4
- '@img/sharp-linux-arm64': 0.35.4
- '@img/sharp-linux-ppc64': 0.35.4
- '@img/sharp-linux-riscv64': 0.35.4
- '@img/sharp-linux-s390x': 0.35.4
- '@img/sharp-linux-x64': 0.35.4
- '@img/sharp-linuxmusl-arm64': 0.35.4
- '@img/sharp-linuxmusl-x64': 0.35.4
- '@img/sharp-webcontainers-wasm32': 0.35.4
- '@img/sharp-win32-arm64': 0.35.4
- '@img/sharp-win32-ia32': 0.35.4
- '@img/sharp-win32-x64': 0.35.4
+ '@img/sharp-darwin-arm64': 0.35.5
+ '@img/sharp-darwin-x64': 0.35.5
+ '@img/sharp-freebsd-wasm32': 0.35.5
+ '@img/sharp-libvips-darwin-arm64': 1.3.4
+ '@img/sharp-libvips-darwin-x64': 1.3.4
+ '@img/sharp-libvips-linux-arm': 1.3.4
+ '@img/sharp-libvips-linux-arm64': 1.3.4
+ '@img/sharp-libvips-linux-ppc64': 1.3.4
+ '@img/sharp-libvips-linux-riscv64': 1.3.4
+ '@img/sharp-libvips-linux-s390x': 1.3.4
+ '@img/sharp-libvips-linux-x64': 1.3.4
+ '@img/sharp-libvips-linuxmusl-arm64': 1.3.4
+ '@img/sharp-libvips-linuxmusl-x64': 1.3.4
+ '@img/sharp-linux-arm': 0.35.5
+ '@img/sharp-linux-arm64': 0.35.5
+ '@img/sharp-linux-ppc64': 0.35.5
+ '@img/sharp-linux-riscv64': 0.35.5
+ '@img/sharp-linux-s390x': 0.35.5
+ '@img/sharp-linux-x64': 0.35.5
+ '@img/sharp-linuxmusl-arm64': 0.35.5
+ '@img/sharp-linuxmusl-x64': 0.35.5
+ '@img/sharp-webcontainers-wasm32': 0.35.5
+ '@img/sharp-win32-arm64': 0.35.5
+ '@img/sharp-win32-ia32': 0.35.5
+ '@img/sharp-win32-x64': 0.35.5
'@types/node': 24.12.2
diff --git a/apps/test-site/pnpm-workspace.yaml b/apps/test-site/pnpm-workspace.yaml
index 977418531..d7e882247 100644
--- a/apps/test-site/pnpm-workspace.yaml
+++ b/apps/test-site/pnpm-workspace.yaml
@@ -25,7 +25,8 @@ overrides:
"nanoid@>=3.0.0 <3.3.18": "3.3.18"
"esbuild@>=0.17.0 <0.28.1": "0.28.1"
"svgo@>=4.0.0 <4.1.0": "4.1.0"
- "sharp@<0.35.4": "0.35.4"
+ # GHSA-wq5f-xc86-pv6w: fixed in 0.35.5.
+ "sharp@<0.35.5": "0.35.5"
# GHSA-ch52-4w7c-c8xp: pin the 4.x line only. Exact 4.3.0 cannot
# resolve to 5.x.
"http-cache-semantics@>=4.0.0 <5.0.0": "4.3.0"