Skip to content

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

feat(alexandria): attribute feedback to provider calls and forward ratings to Exchange (#5596)

Nicolas5a9b1a551e3e
diff --git a/.github/workflows/test-server.yml b/.github/workflows/test-server.yml
index 102de5b1f..e986006be 100644
--- a/.github/workflows/test-server.yml
+++ b/.github/workflows/test-server.yml
@@ -234,6 +234,18 @@ jobs:
--maxWorkers=1 --reporter=default
working-directory: apps/api
+ - name: Run Alexandria feedback regression tests
+ if: matrix.engine == 'fetch' && matrix.proxy == 'no-proxy' && matrix.nuq == 'postgres'
+ run: >-
+ pnpm exec vitest run
+ src/controllers/v2/feedback/alexandria.test.ts
+ src/controllers/v2/feedback/feedback-window.test.ts
+ src/controllers/v2/scrape-alexandria.test.ts
+ src/lib/alexandria-activity.test.ts
+ src/lib/alexandria-feedback-token.test.ts
+ --maxWorkers=1 --reporter=default
+ working-directory: apps/api
+
- name: Run monitor finalization regression tests
if: matrix.engine == 'fetch' && matrix.proxy == 'no-proxy' && matrix.nuq == 'postgres'
run: >-
diff --git a/apps/api/src/controllers/v2/feedback/alexandria-schema.ts b/apps/api/src/controllers/v2/feedback/alexandria-schema.ts
index d77953ca6..429e43706 100644
--- a/apps/api/src/controllers/v2/feedback/alexandria-schema.ts
+++ b/apps/api/src/controllers/v2/feedback/alexandria-schema.ts
@@ -1,8 +1,11 @@
import { z } from "zod";
import { integrationSchema } from "../../../utils/integration";
+import { MAX_FEEDBACK_TOKEN_LENGTH } from "../../../lib/alexandria-feedback-token";
const detail = z.string().trim().min(1).max(2000);
const name = z.string().trim().min(1).max(200);
+const rating = z.enum(["good", "partial", "bad"]);
+const feedbackToken = z.string().min(1).max(MAX_FEEDBACK_TOKEN_LENGTH);
const providerFeedback = z.strictObject({
name,
issue: z.enum([
@@ -41,7 +44,7 @@ const capabilityFeedback = z
export const alexandriaFeedbackSchema = z
.strictObject({
endpoint: z.literal("alexandria"),
- rating: z.enum(["good", "partial", "bad"]),
+ rating,
requestedWebsite: z.strictObject({
url: z.url({ protocol: /^https?$/ }).max(2048),
requestedFunctionality: detail,
@@ -49,6 +52,12 @@ export const alexandriaFeedbackSchema = z
rationale: detail,
// Optional so clients released before the field keep working.
objective: detail.optional(),
+ // feedbackToken values of the provider calls the rating covers.
+ tokens: z.array(feedbackToken).max(20).optional(),
+ callRatings: z
+ .array(z.strictObject({ token: feedbackToken, rating }))
+ .max(20)
+ .optional(),
providerFeedback: z.array(providerFeedback).max(20).optional(),
capabilityFeedback: z.array(capabilityFeedback).max(20).optional(),
origin: z.string().trim().min(1).max(100).default("api"),
@@ -62,8 +71,10 @@ export const alexandriaFeedbackSchema = z
.optional(),
})
.refine(
- // Bound normalized feedback after trimming and applying defaults.
- value => new TextEncoder().encode(JSON.stringify(value)).length <= 8 * 1024,
+ // Bound normalized feedback after trimming and applying defaults. Tokens
+ // are bounded by their own limits.
+ ({ tokens: _tokens, callRatings: _callRatings, ...value }) =>
+ new TextEncoder().encode(JSON.stringify(value)).length <= 8 * 1024,
"Normalized feedback payload must be 8 KiB or smaller",
);
diff --git a/apps/api/src/controllers/v2/feedback/alexandria.integration.test.ts b/apps/api/src/controllers/v2/feedback/alexandria.integration.test.ts
index 1cae15329..a1b61e9cf 100644
--- a/apps/api/src/controllers/v2/feedback/alexandria.integration.test.ts
+++ b/apps/api/src/controllers/v2/feedback/alexandria.integration.test.ts
@@ -15,6 +15,7 @@ vi.mock("./record", () => ({
}));
vi.mock("../../../lib/alexandria-activity", () => ({
hasRecentAlexandriaActivity: async () => true,
+ getRecentAlexandriaCalls: async () => [],
}));
vi.mock("../../../services/autumn/autumn.service", () => ({
CREDITS_FEATURE_ID: "CREDITS",
diff --git a/apps/api/src/controllers/v2/feedback/alexandria.test.ts b/apps/api/src/controllers/v2/feedback/alexandria.test.ts
index 6ea07d407..d359de9cd 100644
--- a/apps/api/src/controllers/v2/feedback/alexandria.test.ts
+++ b/apps/api/src/controllers/v2/feedback/alexandria.test.ts
@@ -11,6 +11,8 @@ const mocks = vi.hoisted(() => ({
recordEndpointFeedback: vi.fn(),
refundAlexandriaFeedback: vi.fn(),
hasRecentAlexandriaActivity: vi.fn(),
+ getRecentAlexandriaCalls: vi.fn(),
+ forwardExchangeToolFeedback: vi.fn(),
logError: vi.fn(),
}));
vi.mock("./alexandria-refund", () => ({
@@ -18,6 +20,10 @@ vi.mock("./alexandria-refund", () => ({
}));
vi.mock("../../../lib/alexandria-activity", () => ({
hasRecentAlexandriaActivity: mocks.hasRecentAlexandriaActivity,
+ getRecentAlexandriaCalls: mocks.getRecentAlexandriaCalls,
+}));
+vi.mock("../../../lib/exchange", () => ({
+ forwardExchangeToolFeedback: mocks.forwardExchangeToolFeedback,
}));
vi.mock("../../../db/connection", () => ({
db: { transaction: mocks.transaction },
@@ -35,6 +41,7 @@ const inserted = (table: string) =>
const parentRows = () => inserted("alexandria_feedback");
const providerRows = () => inserted("alexandria_feedback_providers");
const capabilityRows = () => inserted("alexandria_feedback_capabilities");
+const callRows = () => inserted("alexandria_feedback_calls");
vi.mock("../../../lib/logger", () => ({ logger: { error: mocks.logError } }));
vi.mock("./record", () => ({
recordEndpointFeedback: mocks.recordEndpointFeedback,
@@ -45,6 +52,7 @@ vi.mock("./record-options", () => ({
import { config } from "../../../config";
import { feedbackController } from "./controller";
+import { issueFeedbackToken } from "../../../lib/alexandria-feedback-token";
const minimal = {
endpoint: "alexandria",
@@ -83,6 +91,7 @@ beforeEach(() => {
);
mocks.insert.mockResolvedValue(undefined);
mocks.hasRecentAlexandriaActivity.mockResolvedValue(true);
+ mocks.getRecentAlexandriaCalls.mockResolvedValue([]);
mocks.refundAlexandriaFeedback.mockResolvedValue({
creditsRefunded: 1,
creditsRefundedToday: 1,
@@ -133,6 +142,7 @@ it.each(["good", "partial", "bad"])(
]);
expect(providerRows()).toEqual([]);
expect(capabilityRows()).toEqual([]);
+ expect(callRows()).toEqual([]);
},
);
@@ -611,6 +621,8 @@ it.each([
expect(response.body.creditsRefunded).toBe(0);
expect(mocks.transaction).not.toHaveBeenCalled();
expect(mocks.refundAlexandriaFeedback).not.toHaveBeenCalled();
+ expect(mocks.getRecentAlexandriaCalls).not.toHaveBeenCalled();
+ expect(mocks.forwardExchangeToolFeedback).not.toHaveBeenCalled();
});
it("returns the refund outcome, including cap and duplicate warnings", async () => {
@@ -638,11 +650,12 @@ it("rejects feedback outside the window after the team's last Alexandria call",
expect(response.body).toEqual({
success: false,
feedbackErrorCode: "FEEDBACK_WINDOW_EXPIRED",
- error: `Alexandria feedback must be submitted within ${config.ALEXANDRIA_FEEDBACK_WINDOW_SEC} seconds of an Alexandria search, discovery, or execution.`,
+ error: `Alexandria feedback must be submitted within ${config.ALEXANDRIA_FEEDBACK_WINDOW_SEC} seconds of an Alexandria search, discovery, or execution, or name its calls with valid feedback tokens.`,
});
expect(mocks.hasRecentAlexandriaActivity).toHaveBeenCalledWith(teamId);
expect(mocks.transaction).not.toHaveBeenCalled();
expect(mocks.refundAlexandriaFeedback).not.toHaveBeenCalled();
+ expect(mocks.forwardExchangeToolFeedback).not.toHaveBeenCalled();
});
it("fails closed when the feedback window cannot be checked", async () => {
@@ -724,6 +737,7 @@ it.each([
expect(JSON.stringify(mocks.logError.mock.calls)).not.toContain("sensitive");
expect(mocks.recordEndpointFeedback).not.toHaveBeenCalled();
expect(mocks.refundAlexandriaFeedback).not.toHaveBeenCalled();
+ expect(mocks.forwardExchangeToolFeedback).not.toHaveBeenCalled();
});
it.each(["search", "scrape", "parse", "map"])(
@@ -749,3 +763,245 @@ it.each(["search", "scrape", "parse", "map"])(
expect(mocks.transaction).not.toHaveBeenCalled();
},
);
+
+describe("call attribution", () => {
+ const now = 1_800_000_000_000;
+ const originalSecret = config.EXCHANGE_INTERNAL_SECRET;
+ const recent = (requestId: string, provider: string, ageSec: number) => ({
+ requestId,
+ provider,
+ capability: "lookup",
+ at: now - ageSec * 1000,
+ });
+ const token = (
+ requestId: string,
+ provider: string,
+ options: { team?: string; at?: number } = {},
+ ) =>
+ issueFeedbackToken(
+ {
+ requestId,
+ teamId: options.team ?? teamId,
+ provider,
+ capability: "lookup",
+ },
+ options.at ?? now - 60_000,
+ )!;
+ const callRow = (
+ position: number,
+ request_id: string,
+ provider: string,
+ attribution: string,
+ rating: string | null = null,
+ ) => ({
+ feedback_id: expect.any(String),
+ team_id: teamId,
+ position,
+ request_id,
+ provider,
+ capability: "lookup",
+ rating,
+ attribution,
+ });
+ let originalWindow: number;
+ let clock: { mockRestore: () => void };
+ beforeEach(() => {
+ originalWindow = config.ALEXANDRIA_FEEDBACK_WINDOW_SEC;
+ config.ALEXANDRIA_FEEDBACK_WINDOW_SEC = 1200;
+ config.EXCHANGE_INTERNAL_SECRET = "internal-secret";
+ clock = vi.spyOn(Date, "now").mockReturnValue(now);
+ mocks.getRecentAlexandriaCalls.mockResolvedValue([
+ recent("req-3", "sec", 10),
+ recent("req-2", "fred", 60),
+ recent("req-2", "bls", 60),
+ recent("req-3", "sec", 120),
+ recent("req-1", "census", 1500),
+ ]);
+ });
+ afterEach(() => {
+ config.ALEXANDRIA_FEEDBACK_WINDOW_SEC = originalWindow;
+ config.EXCHANGE_INTERNAL_SECRET = originalSecret;
+ clock.mockRestore();
+ });
+
+ it("attributes to the calls named by valid tokens, with per-call ratings", async () => {
+ const fred = token("req-2", "fred");
+ const sec = token("req-3", "sec");
+ const response = await submit({
+ ...minimal,
+ tokens: [fred, sec, fred],
+ callRatings: [{ token: sec, rating: "bad" }],
+ });
+ expect(response.status).toBe(200);
+ expect(response.body.rejectedTokens).toBeUndefined();
+ expect(mocks.getRecentAlexandriaCalls).not.toHaveBeenCalled();
+ expect(callRows()).toEqual([
+ callRow(0, "req-2", "fred", "token"),
+ callRow(1, "req-3", "sec", "token", "bad"),
+ ]);
+ expect(
+ callRows().every(row => row.feedback_id === response.body.feedbackId),
+ ).toBe(true);
+ });
+
+ it("accepts a token-attributed rating after the window has closed", async () => {
+ mocks.hasRecentAlexandriaActivity.mockResolvedValue(false);
+ const response = await submit({
+ ...minimal,
+ callRatings: [{ token: token("req-1", "census"), rating: "good" }],
+ });
+ expect(response.status).toBe(200);
+ expect(mocks.hasRecentAlexandriaActivity).not.toHaveBeenCalled();
+ expect(mocks.refundAlexandriaFeedback).toHaveBeenCalledOnce();
+ expect(callRows()).toEqual([
+ callRow(0, "req-1", "census", "token", "good"),
+ ]);
+ });
+
+ it("rejects tokens that are forged, expired, from another team or unsigned", async () => {
+ const valid = token("req-2", "fred");
+ const [version, payload, signature] = valid.split(".");
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString());
+ const forged = [
+ version,
+ Buffer.from(
+ JSON.stringify([claims[0], "bls", ...claims.slice(2)]),
+ ).toString("base64url"),
+ signature,
+ ].join(".");
+ const response = await submit({
+ ...minimal,
+ tokens: [
+ valid,
+ forged,
+ token("req-2", "bls", { at: now - 25 * 3600_000 }),
+ token("req-2", "bls", { team: "01933161-0000-7000-8000-00000000000f" }),
+ "v1.not-a-token",
+ ],
+ });
+ expect(response.status).toBe(200);
+ expect(response.body.rejectedTokens).toBe(4);
+ expect(callRows()).toEqual([callRow(0, "req-2", "fred", "token")]);
+ });
+
+ it("falls back to the window when no token verifies, and closes when the window has", async () => {
+ const stale = token("req-2", "fred", { at: now - 25 * 3600_000 });
+ mocks.hasRecentAlexandriaActivity.mockResolvedValue(false);
+ const closed = await submit({ ...minimal, tokens: [stale] });
+ expect(closed.status).toBe(409);
+ expect(closed.body.feedbackErrorCode).toBe("FEEDBACK_WINDOW_EXPIRED");
+ mocks.hasRecentAlexandriaActivity.mockResolvedValue(true);
+ const open = await submit({ ...minimal, tokens: [stale] });
+ expect(open.status).toBe(200);
+ expect(open.body.rejectedTokens).toBe(1);
+ expect(callRows()[0]).toEqual(callRow(0, "req-3", "sec", "window"));
+ });
+
+ it("does not verify tokens without a signing key", async () => {
+ const valid = token("req-2", "fred");
+ config.EXCHANGE_INTERNAL_SECRET = undefined as never;
+ const response = await submit({ ...minimal, tokens: [valid] });
+ expect(response.status).toBe(200);
+ expect(response.body.rejectedTokens).toBe(1);
+ expect(callRows().every(row => row.attribution === "window")).toBe(true);
+ });
+
+ it("falls back to the distinct calls inside the window", async () => {
+ expect((await submit(minimal)).status).toBe(200);
+ expect(callRows()).toEqual([
+ callRow(0, "req-3", "sec", "window"),
+ callRow(1, "req-2", "fred", "window"),
+ callRow(2, "req-2", "bls", "window"),
+ ]);
+ });
+
+ it("records feedback without calls when none are remembered", async () => {
+ mocks.getRecentAlexandriaCalls.mockResolvedValue([]);
+ expect((await submit(minimal)).status).toBe(200);
+ expect(callRows()).toEqual([]);
+ expect(parentRows()).toHaveLength(1);
+ });
+
+ it.each([
+ { tokens: [""] },
+ { tokens: ["x".repeat(1025)] },
+ { tokens: Array.from({ length: 21 }, (_, i) => `t${i}`) },
+ { callRatings: [{ token: "t", rating: "great" }] },
+ { callRatings: [{ token: "t" }] },
+ {
+ callRatings: Array.from({ length: 21 }, (_, i) => ({
+ token: `t${i}`,
+ rating: "good",
+ })),
+ },
+ { requestId: "req-2" },
+ ])("rejects invalid token fields %j", async extra => {
+ expect((await submit({ ...minimal, ...extra })).status).toBe(400);
+ expect(mocks.transaction).not.toHaveBeenCalled();
+ });
+
+ it("keeps tokens out of the 8 KiB payload bound", async () => {
+ const tokens = Array.from({ length: 20 }, (_, i) =>
+ token(`${i}`.padStart(64, "a"), "x".repeat(200)),
+ );
+ expect(JSON.stringify(tokens).length).toBeGreaterThan(8 * 1024);
+ expect((await submit({ ...minimal, tokens })).status).toBe(200);
+ });
+
+ it("forwards the rating and its token calls to the Exchange after the refund", async () => {
+ const fred = token("req-2", "fred");
+ const response = await submit({
+ ...minimal,
+ rating: "bad",
+ origin: "mcp",
+ tokens: [fred],
+ callRatings: [{ token: token("req-3", "sec"), rating: "good" }],
+ });
+ expect(mocks.forwardExchangeToolFeedback).toHaveBeenCalledExactlyOnceWith({
+ teamId,
+ feedbackId: response.body.feedbackId,
+ occurredAt: new Date(now).toISOString(),
+ rating: "bad",
+ origin: "mcp",
+ attribution: "token",
+ calls: [
+ {
+ requestId: "req-2",
+ provider: "fred",
+ capability: "lookup",
+ rating: null,
+ },
+ {
+ requestId: "req-3",
+ provider: "sec",
+ capability: "lookup",
+ rating: "good",
+ },
+ ],
+ });
+ expect(
+ mocks.refundAlexandriaFeedback.mock.invocationCallOrder[0],
+ ).toBeLessThan(
+ mocks.forwardExchangeToolFeedback.mock.invocationCallOrder[0],
+ );
+ });
+
+ it("forwards window ratings even when no calls are attributed", async () => {
+ mocks.getRecentAlexandriaCalls.mockResolvedValue([]);
+ await submit(minimal);
+ expect(mocks.forwardExchangeToolFeedback).toHaveBeenCalledWith(
+ expect.objectContaining({
+ attribution: "window",
+ calls: [],
+ origin: "api",
+ }),
+ );
+ });
+
+ it("does not let a failing forward affect the response", async () => {
+ mocks.forwardExchangeToolFeedback.mockReturnValue(new Promise(() => {}));
+ const response = await submit(minimal);
+ expect(response.status).toBe(200);
+ expect(response.body.success).toBe(true);
+ });
+});
diff --git a/apps/api/src/controllers/v2/feedback/alexandria.ts b/apps/api/src/controllers/v2/feedback/alexandria.ts
index 7a9b22e33..4893ee5c3 100644
--- a/apps/api/src/controllers/v2/feedback/alexandria.ts
+++ b/apps/api/src/controllers/v2/feedback/alexandria.ts
@@ -3,7 +3,12 @@ import { DrizzleQueryError } from "drizzle-orm/errors";
import { config } from "../../../config";
import { db } from "../../../db/connection";
import * as schema from "../../../db/schema";
-import { hasRecentAlexandriaActivity } from "../../../lib/alexandria-activity";
+import {
+ getRecentAlexandriaCalls,
+ hasRecentAlexandriaActivity,
+} from "../../../lib/alexandria-activity";
+import { verifyFeedbackToken } from "../../../lib/alexandria-feedback-token";
+import { forwardExchangeToolFeedback } from "../../../lib/exchange";
import { logger } from "../../../lib/logger";
import { getScrapeZDR, getSearchZDR } from "../../../lib/zdr-helpers";
import type { RequestWithAuth, EndpointFeedbackErrorCode } from "../types";
@@ -20,6 +25,13 @@ const failure = (
body: { success: false, feedbackErrorCode, error },
});
+type FeedbackCall = {
+ requestId: string;
+ provider: string;
+ capability: string;
+ rating: AlexandriaFeedbackRequest["rating"] | null;
+};
+
export async function recordAlexandriaFeedback(
req: RequestWithAuth<any, any, any>,
body: AlexandriaFeedbackRequest,
@@ -67,25 +79,69 @@ export async function recordAlexandriaFeedback(
};
}
- let withinWindow: boolean;
- try {
- withinWindow = await hasRecentAlexandriaActivity(teamId);
- } catch (error) {
- logger.error("Failed to check the Alexandria feedback window", {
- error,
- teamId,
+ const now = Date.now();
+ const callRatings = new Map(
+ (body.callRatings ?? []).map(entry => [entry.token, entry.rating]),
+ );
+ const submittedTokens = [
+ ...new Set([...(body.tokens ?? []), ...callRatings.keys()]),
+ ];
+ const calls = new Map<string, FeedbackCall>();
+ let rejectedTokens = 0;
+ for (const token of submittedTokens) {
+ const claims = verifyFeedbackToken(token, teamId, now);
+ if (!claims) {
+ rejectedTokens++;
+ continue;
+ }
+ const key = JSON.stringify([
+ claims.requestId,
+ claims.provider,
+ claims.capability,
+ ]);
+ const rating = callRatings.get(token) ?? calls.get(key)?.rating ?? null;
+ calls.set(key, {
+ requestId: claims.requestId,
+ provider: claims.provider,
+ capability: claims.capability,
+ rating,
});
- return failure(500, "INTERNAL", "Failed to check the feedback window.");
}
- if (!withinWindow) {
- return failure(
- 409,
- "FEEDBACK_WINDOW_EXPIRED",
- `Alexandria feedback must be submitted within ${config.ALEXANDRIA_FEEDBACK_WINDOW_SEC} seconds of an Alexandria search, discovery, or execution.`,
- );
+ const attribution = calls.size > 0 ? "token" : "window";
+
+ if (attribution === "window") {
+ let withinWindow: boolean;
+ try {
+ withinWindow = await hasRecentAlexandriaActivity(teamId);
+ } catch (error) {
+ logger.error("Failed to check the Alexandria feedback window", {
+ error,
+ teamId,
+ });
+ return failure(500, "INTERNAL", "Failed to check the feedback window.");
+ }
+ if (!withinWindow) {
+ return failure(
+ 409,
+ "FEEDBACK_WINDOW_EXPIRED",
+ `Alexandria feedback must be submitted within ${config.ALEXANDRIA_FEEDBACK_WINDOW_SEC} seconds of an Alexandria search, discovery, or execution, or name its calls with valid feedback tokens.`,
+ );
+ }
+ const windowStart = now - config.ALEXANDRIA_FEEDBACK_WINDOW_SEC * 1000;
+ for (const call of await getRecentAlexandriaCalls(teamId)) {
+ if (call.at < windowStart) continue;
+ const { requestId, provider, capability } = call;
+ calls.set(JSON.stringify([requestId, provider, capability]), {
+ requestId,
+ provider,
+ capability,
+ rating: null,
+ });
+ }
}
const feedbackId = uuidv7();
+ const occurredAt = new Date(now).toISOString();
const providerRows = (body.providerFeedback ?? []).map((entry, position) => ({
feedback_id: feedbackId,
team_id: teamId,
@@ -132,6 +188,20 @@ export async function recordAlexandriaFeedback(
.insert(schema.alexandria_feedback_capabilities)
.values(capabilityRows);
}
+ if (calls.size > 0) {
+ await tx.insert(schema.alexandria_feedback_calls).values(
+ [...calls.values()].map((call, position) => ({
+ feedback_id: feedbackId,
+ team_id: teamId,
+ position,
+ request_id: call.requestId,
+ provider: call.provider,
+ capability: call.capability,
+ rating: call.rating,
+ attribution,
+ })),
+ );
+ }
});
} catch (error) {
// Database errors may embed the submitted payload. Keep feedback content
@@ -155,8 +225,22 @@ export async function recordAlexandriaFeedback(
rating: body.rating,
requestedUrl: body.requestedWebsite.url,
});
+ void forwardExchangeToolFeedback({
+ teamId,
+ feedbackId,
+ occurredAt,
+ rating: body.rating,
+ origin: body.origin,
+ attribution,
+ calls: [...calls.values()],
+ });
return {
status: 200,
- body: { success: true, feedbackId, ...refund },
+ body: {
+ success: true,
+ feedbackId,
+ ...refund,
+ ...(rejectedTokens > 0 ? { rejectedTokens } : {}),
+ },
};
}
diff --git a/apps/api/src/controllers/v2/feedback/feedback-window.test.ts b/apps/api/src/controllers/v2/feedback/feedback-window.test.ts
index c09349811..895d31179 100644
--- a/apps/api/src/controllers/v2/feedback/feedback-window.test.ts
+++ b/apps/api/src/controllers/v2/feedback/feedback-window.test.ts
@@ -31,6 +31,7 @@ vi.mock("./refund-totals", () => ({
}));
vi.mock("../../../lib/alexandria-activity", () => ({
hasRecentAlexandriaActivity: fixture.alexandriaActivity,
+ getRecentAlexandriaCalls: async () => [],
}));
vi.mock("./alexandria-refund", () => ({
refundAlexandriaFeedback: async () => ({
diff --git a/apps/api/src/controllers/v2/scrape-alexandria.test.ts b/apps/api/src/controllers/v2/scrape-alexandria.test.ts
index 3835243b5..cc744b011 100644
--- a/apps/api/src/controllers/v2/scrape-alexandria.test.ts
+++ b/apps/api/src/controllers/v2/scrape-alexandria.test.ts
@@ -10,6 +10,11 @@ const mocks = vi.hoisted(() => ({
scrapeLog: vi.fn(),
discovery: vi.fn(),
recordDiscovered: vi.fn(),
+ markCalls: vi.fn(),
+}));
+vi.mock("../../lib/alexandria-activity", () => ({
+ markAlexandriaActivity: vi.fn(),
+ markAlexandriaCalls: mocks.markCalls,
}));
vi.mock("../../lib/alexandria-discovery", () => ({
discoveryForCalls: mocks.discovery,
@@ -17,6 +22,8 @@ vi.mock("../../lib/alexandria-discovery", () => ({
}));
vi.mock("../../services/alexandria/retrieve", () => ({
REQUEST_ID_PATTERN: /^[A-Za-z0-9._:-]{1,128}$/,
+ exchangeRequestId: (teamId: string, requestId: string) =>
+ `hashed:${teamId}:${requestId}`,
retrieveProviders: mocks.retrieve,
}));
vi.mock("../../services/logging/log_job", () => ({
@@ -38,6 +45,8 @@ vi.mock("../../config", () => ({
},
}));
import { providerScrapeController } from "./scrape-alexandria";
+import { config } from "../../config";
+import { verifyFeedbackToken } from "../../lib/alexandria-feedback-token";
const call = {
provider: "fred",
@@ -621,3 +630,119 @@ it("neither reads nor records discovery under zero data retention", async () =>
expect(mocks.discovery).not.toHaveBeenCalled();
expect(mocks.recordDiscovered).not.toHaveBeenCalled();
});
+
+it("remembers each provider call under its request id for feedback attribution", async () => {
+ const second = { provider: "sec", capability: "filings", options: {} };
+ await request(app)
+ .post("/v2/scrape")
+ .set("x-request-id", "req-1")
+ .send({ alexandria: [call, second] });
+ expect(mocks.markCalls).toHaveBeenCalledExactlyOnceWith("team", [
+ {
+ requestId: "hashed:team:req-1",
+ provider: "fred",
+ capability: "categories/category",
+ },
+ { requestId: "hashed:team:req-1", provider: "sec", capability: "filings" },
+ ]);
+});
+
+it("does not remember calls the Exchange did not execute", async () => {
+ mocks.retrieve.mockResolvedValue(
+ result([{ ...call, creditsCost: 0, data: {} }], false),
+ );
+ await request(app).post("/v2/scrape").send({ alexandria: call });
+ expect(mocks.markCalls).not.toHaveBeenCalled();
+});
+
+it.each([
+ [{ alexandria: call, zeroDataRetention: true }, {}],
+ [{ alexandria: call }, { forceZDR: true }],
+])(
+ "does not remember provider calls under zero data retention %#",
+ async (body, teamFlags) => {
+ flags = { exchangeRetrieve: true, ...teamFlags };
+ await request(app).post("/v2/scrape").send(body);
+ expect(mocks.markCalls).not.toHaveBeenCalled();
+ },
+);
+
+describe("feedback tokens", () => {
+ afterEach(() => {
+ (config as { EXCHANGE_INTERNAL_SECRET?: string }).EXCHANGE_INTERNAL_SECRET =
+ undefined;
+ });
+ beforeEach(() => {
+ (config as { EXCHANGE_INTERNAL_SECRET?: string }).EXCHANGE_INTERNAL_SECRET =
+ "internal-secret";
+ });
+
+ it("returns a team-bound token per provider call, failed calls included", async () => {
+ const second = { provider: "sec", capability: "filings", options: {} };
+ mocks.retrieve.mockResolvedValue(
+ result([
+ { ...call, creditsCost: 0, data: {} },
+ { error: { code: "provider_error", message: "down" } },
+ ]),
+ );
+ const response = await request(app)
+ .post("/v2/scrape")
+ .set("x-request-id", "req-1")
+ .send({ alexandria: [call, second] });
+ const [first, failed] = response.body.data.alexandria;
+ expect(verifyFeedbackToken(first.feedbackToken, "team")).toMatchObject({
+ requestId: "hashed:team:req-1",
+ provider: "fred",
+ capability: "categories/category",
+ });
+ expect(verifyFeedbackToken(failed.feedbackToken, "team")).toMatchObject({
+ requestId: "hashed:team:req-1",
+ provider: "sec",
+ capability: "filings",
+ });
+ expect(verifyFeedbackToken(first.feedbackToken, "other-team")).toBeNull();
+ });
+
+ it("returns the token on the legacy single-call route, errors included", async () => {
+ const response = await request(app).post("/exchange/retrieve").send(call);
+ expect(response.body.feedbackToken).toEqual(expect.any(String));
+ mocks.retrieve.mockResolvedValue(
+ result([
+ { error: { code: "provider_error", message: "down", status: 502 } },
+ ]),
+ );
+ const failed = await request(app).post("/exchange/retrieve").send(call);
+ expect(failed.status).toBe(502);
+ expect(failed.body).toEqual({
+ success: false,
+ code: "provider_error",
+ error: "down",
+ feedbackToken: expect.any(String),
+ });
+ expect(
+ verifyFeedbackToken(failed.body.feedbackToken, "team"),
+ ).toMatchObject({ provider: "fred", capability: "categories/category" });
+ });
+
+ it.each([
+ [{ alexandria: call, zeroDataRetention: true }, {}],
+ [{ alexandria: call }, { forceZDR: true }],
+ ])(
+ "issues no token under zero data retention %#",
+ async (body, teamFlags) => {
+ flags = { exchangeRetrieve: true, ...teamFlags };
+ const response = await request(app).post("/v2/scrape").send(body);
+ expect(response.status).toBe(200);
+ expect(response.body.data.alexandria[0].feedbackToken).toBeUndefined();
+ },
+ );
+
+ it("issues no token without a signing key", async () => {
+ (config as { EXCHANGE_INTERNAL_SECRET?: string }).EXCHANGE_INTERNAL_SECRET =
+ undefined;
+ const response = await request(app)
+ .post("/v2/scrape")
+ .send({ alexandria: call });
+ expect(response.body.data.alexandria[0].feedbackToken).toBeUndefined();
+ });
+});
diff --git a/apps/api/src/controllers/v2/scrape-alexandria.ts b/apps/api/src/controllers/v2/scrape-alexandria.ts
index 35b075f3c..fa26123d9 100644
--- a/apps/api/src/controllers/v2/scrape-alexandria.ts
+++ b/apps/api/src/controllers/v2/scrape-alexandria.ts
@@ -10,8 +10,12 @@ import { getScrapeZDR } from "../../lib/zdr-helpers";
import { billingCountryForTeam } from "../../lib/billing-country";
import { checkKeyFormatRestriction } from "../../lib/key-restriction";
import { orgIdFromAcuc } from "../../lib/team-org";
+import { issueFeedbackToken } from "../../lib/alexandria-feedback-token";
import { logProviderScrape, logRequest } from "../../services/logging/log_job";
-import { markAlexandriaActivity } from "../../lib/alexandria-activity";
+import {
+ markAlexandriaActivity,
+ markAlexandriaCalls,
+} from "../../lib/alexandria-activity";
import {
discoveryForCalls,
recordDiscoveredTools,
@@ -23,6 +27,7 @@ import {
} from "../../services/alexandria/contracts";
import {
REQUEST_ID_PATTERN,
+ exchangeRequestId,
retrieveProviders,
} from "../../services/alexandria/retrieve";
import type { RequestWithAuth } from "./types";
@@ -195,6 +200,16 @@ export async function providerScrapeController(
}
const timeTaken = (Date.now() - startedAt) / 1000;
markAlexandriaActivity(req.auth.team_id);
+ const usageRequestId = exchangeRequestId(req.auth.team_id, requestId);
+ if (result.executed && !zeroDataRetention)
+ markAlexandriaCalls(
+ req.auth.team_id,
+ body.alexandria.map(({ provider, capability }) => ({
+ requestId: usageRequestId,
+ provider,
+ capability,
+ })),
+ );
if (result.executed && !body.__agentInterop) {
const apiKeyId = req.acuc.api_key_id ?? null;
const served = answerSchema.safeParse(result.body);
@@ -332,7 +347,26 @@ export async function providerScrapeController(
res.setHeader("Retry-After", String(refused.retryAfterSeconds));
return res.status(result.status).json(result.body);
}
- const answer = answerSchema.parse(result.body);
+ const parsed = answerSchema.parse(result.body);
+ const answer = zeroDataRetention
+ ? parsed
+ : {
+ ...parsed,
+ results: parsed.results.map((item, i) => {
+ const provider = item.provider ?? body.alexandria[i]?.provider;
+ const capability = item.capability ?? body.alexandria[i]?.capability;
+ const feedbackToken =
+ provider && capability
+ ? issueFeedbackToken({
+ requestId: usageRequestId,
+ teamId: req.auth.team_id,
+ provider,
+ capability,
+ })
+ : undefined;
+ return feedbackToken ? { ...item, feedbackToken } : item;
+ }),
+ };
if (legacy) {
if (legacyBody && "requests" in legacyBody) return res.json(answer);
const first = answer.results[0];
@@ -342,6 +376,7 @@ export async function providerScrapeController(
success: false,
code: first.error.code,
error: first.error.message,
+ ...(first.feedbackToken ? { feedbackToken: first.feedbackToken } : {}),
});
}
return res.json({ success: true, ...first });
diff --git a/apps/api/src/db/schema/public.ts b/apps/api/src/db/schema/public.ts
index e5040d016..fb8c9be85 100644
--- a/apps/api/src/db/schema/public.ts
+++ b/apps/api/src/db/schema/public.ts
@@ -606,6 +606,35 @@ export const alexandria_feedback_capabilities = pgTable(
],
);
+export const alexandria_feedback_calls = pgTable(
+ "alexandria_feedback_calls",
+ {
+ feedback_id: uuid("feedback_id")
+ .notNull()
+ .references(() => alexandria_feedback.id, { onDelete: "cascade" }),
+ team_id: uuid("team_id").notNull(),
+ position: smallint("position").notNull(),
+ request_id: text("request_id").notNull(),
+ provider: text("provider"),
+ capability: text("capability"),
+ rating: text("rating"),
+ attribution: text("attribution").notNull(),
+ created_at: ts("created_at").notNull().defaultNow(),
+ },
+ table => [
+ primaryKey({ columns: [table.feedback_id, table.position] }),
+ index("alexandria_feedback_calls_request_id_idx").on(table.request_id),
+ check(
+ "alexandria_feedback_calls_attribution_check",
+ sql`${table.attribution} IN ('token', 'window')`,
+ ),
+ check(
+ "alexandria_feedback_calls_rating_check",
+ sql`${table.rating} IN ('good', 'partial', 'bad')`,
+ ),
+ ],
+);
+
export const subscriptions = pgTable("subscriptions", {
id: text("id").notNull(),
user_id: uuid("user_id").notNull(),
diff --git a/apps/api/src/lib/alexandria-activity.test.ts b/apps/api/src/lib/alexandria-activity.test.ts
index dafc19c21..c939266f0 100644
--- a/apps/api/src/lib/alexandria-activity.test.ts
+++ b/apps/api/src/lib/alexandria-activity.test.ts
@@ -1,18 +1,37 @@
-const mocks = vi.hoisted(() => ({
- set: vi.fn(),
- exists: vi.fn(),
- warn: vi.fn(),
-}));
+const mocks = vi.hoisted(() => {
+ const pipeline = {
+ lpush: vi.fn(),
+ ltrim: vi.fn(),
+ expire: vi.fn(),
+ exec: vi.fn(),
+ };
+ return {
+ set: vi.fn(),
+ exists: vi.fn(),
+ lrange: vi.fn(),
+ warn: vi.fn(),
+ pipeline,
+ multi: vi.fn(() => pipeline),
+ };
+});
vi.mock("../services/rate-limiter", () => ({
- redisRateLimitClient: { set: mocks.set, exists: mocks.exists },
+ redisRateLimitClient: {
+ set: mocks.set,
+ exists: mocks.exists,
+ lrange: mocks.lrange,
+ multi: mocks.multi,
+ },
}));
vi.mock("./logger", () => ({ logger: { warn: mocks.warn } }));
import { config } from "../config";
import {
+ getRecentAlexandriaCalls,
hasRecentAlexandriaActivity,
markAlexandriaActivity,
+ markAlexandriaCalls,
recordAlexandriaActivity,
+ recordAlexandriaCalls,
} from "./alexandria-activity";
const teamId = "01933161-0000-7000-8000-000000000001";
@@ -20,6 +39,9 @@ const teamId = "01933161-0000-7000-8000-000000000001";
beforeEach(() => {
vi.clearAllMocks();
mocks.set.mockResolvedValue("OK");
+ for (const step of ["lpush", "ltrim", "expire"] as const)
+ mocks.pipeline[step].mockReturnValue(mocks.pipeline);
+ mocks.pipeline.exec.mockResolvedValue([]);
});
it("opens the Alexandria window, independent of the search feedback window", async () => {
@@ -75,3 +97,88 @@ it("rejects when the window lookup fails", async () => {
mocks.exists.mockRejectedValue(error);
await expect(hasRecentAlexandriaActivity(teamId)).rejects.toBe(error);
});
+
+const calls = [
+ { requestId: "req-1", provider: "fred", capability: "series" },
+ { requestId: "req-1", provider: "sec", capability: "filings" },
+];
+
+it("keeps the last 20 provider calls for the feedback window's lifetime", async () => {
+ const original = config.ALEXANDRIA_FEEDBACK_WINDOW_SEC;
+ config.ALEXANDRIA_FEEDBACK_WINDOW_SEC = 1500;
+ const clock = vi.spyOn(Date, "now").mockReturnValue(1_700_000_000_000);
+ try {
+ await recordAlexandriaCalls(teamId, calls);
+ } finally {
+ config.ALEXANDRIA_FEEDBACK_WINDOW_SEC = original;
+ clock.mockRestore();
+ }
+ const key = `alexandria:calls:${teamId}`;
+ expect(mocks.pipeline.lpush).toHaveBeenCalledExactlyOnceWith(
+ key,
+ ...calls.map(call => JSON.stringify({ ...call, at: 1_700_000_000_000 })),
+ );
+ expect(mocks.pipeline.ltrim).toHaveBeenCalledExactlyOnceWith(key, 0, 19);
+ expect(mocks.pipeline.expire).toHaveBeenCalledExactlyOnceWith(key, 1500);
+ expect(mocks.pipeline.exec).toHaveBeenCalledOnce();
+});
+
+it("logs a command error the transaction resolves with", async () => {
+ const error = new Error("WRONGTYPE");
+ mocks.pipeline.exec.mockResolvedValue([
+ [null, 1],
+ [error, null],
+ [null, 1],
+ ]);
+ await expect(recordAlexandriaCalls(teamId, calls)).resolves.toBeUndefined();
+ expect(mocks.warn).toHaveBeenCalledWith("Failed to record Alexandria calls", {
+ error,
+ teamId,
+ });
+});
+
+it("skips the write when there are no calls", async () => {
+ await recordAlexandriaCalls(teamId, []);
+ expect(mocks.multi).not.toHaveBeenCalled();
+});
+
+it("resolves and logs when recording calls fails, also in the fire-and-forget form", async () => {
+ const error = new Error("redis down");
+ mocks.pipeline.exec.mockRejectedValue(error);
+ await expect(recordAlexandriaCalls(teamId, calls)).resolves.toBeUndefined();
+ expect(mocks.warn).toHaveBeenCalledWith("Failed to record Alexandria calls", {
+ error,
+ teamId,
+ });
+ mocks.warn.mockClear();
+ expect(markAlexandriaCalls(teamId, calls)).toBeUndefined();
+ await vi.waitFor(() => expect(mocks.warn).toHaveBeenCalled());
+});
+
+it("reads recent calls newest first and drops malformed entries", async () => {
+ mocks.lrange.mockResolvedValue([
+ JSON.stringify({ ...calls[1], at: 2 }),
+ "not json",
+ JSON.stringify({ requestId: "req-0", provider: "fred", at: 1 }),
+ JSON.stringify({ ...calls[0], at: 1, extra: true }),
+ ]);
+ await expect(getRecentAlexandriaCalls(teamId)).resolves.toEqual([
+ { ...calls[1], at: 2 },
+ { ...calls[0], at: 1 },
+ ]);
+ expect(mocks.lrange).toHaveBeenCalledWith(
+ `alexandria:calls:${teamId}`,
+ 0,
+ 19,
+ );
+});
+
+it("returns no recent calls when the read fails", async () => {
+ const error = new Error("redis down");
+ mocks.lrange.mockRejectedValue(error);
+ await expect(getRecentAlexandriaCalls(teamId)).resolves.toEqual([]);
+ expect(mocks.warn).toHaveBeenCalledWith(
+ "Failed to read recent Alexandria calls",
+ { error, teamId },
+ );
+});
diff --git a/apps/api/src/lib/alexandria-activity.ts b/apps/api/src/lib/alexandria-activity.ts
index 592bd9c96..1471f3059 100644
--- a/apps/api/src/lib/alexandria-activity.ts
+++ b/apps/api/src/lib/alexandria-activity.ts
@@ -3,6 +3,15 @@ import { redisRateLimitClient } from "../services/rate-limiter";
import { logger } from "./logger";
const activityKey = (teamId: string) => `alexandria:activity:${teamId}`;
+const recentCallsKey = (teamId: string) => `alexandria:calls:${teamId}`;
+const RECENT_CALLS_LIMIT = 20;
+
+export type AlexandriaCall = {
+ requestId: string;
+ provider: string;
+ capability: string;
+};
+export type RecentAlexandriaCall = AlexandriaCall & { at: number };
/**
* Opens (or extends) the team's Alexandria feedback window for
@@ -32,3 +41,79 @@ export async function hasRecentAlexandriaActivity(
): Promise<boolean> {
return (await redisRateLimitClient.exists(activityKey(teamId))) === 1;
}
+
+/**
+ * Prepends provider calls to the team's recent-call list (newest first, capped
+ * at RECENT_CALLS_LIMIT, same TTL as the feedback window). Never rejects.
+ * Callers must skip this under zero data retention.
+ */
+export async function recordAlexandriaCalls(
+ teamId: string,
+ calls: AlexandriaCall[],
+): Promise<void> {
+ if (calls.length === 0) return;
+ const at = Date.now();
+ const key = recentCallsKey(teamId);
+ try {
+ const results = await redisRateLimitClient
+ .multi()
+ .lpush(
+ key,
+ ...calls.map(({ requestId, provider, capability }) =>
+ JSON.stringify({ requestId, provider, capability, at }),
+ ),
+ )
+ .ltrim(key, 0, RECENT_CALLS_LIMIT - 1)
+ .expire(key, config.ALEXANDRIA_FEEDBACK_WINDOW_SEC)
+ .exec();
+ const commandError = results?.find(([error]) => error)?.[0];
+ if (commandError) throw commandError;
+ } catch (error) {
+ logger.warn("Failed to record Alexandria calls", { error, teamId });
+ }
+}
+
+/** Fire-and-forget form of recordAlexandriaCalls. */
+export function markAlexandriaCalls(
+ teamId: string,
+ calls: AlexandriaCall[],
+): void {
+ void recordAlexandriaCalls(teamId, calls);
+}
+
+/** The team's recent provider calls, newest first. Never rejects; returns [] on failure. */
+export async function getRecentAlexandriaCalls(
+ teamId: string,
+): Promise<RecentAlexandriaCall[]> {
+ let raw: string[];
+ try {
+ raw = await redisRateLimitClient.lrange(
+ recentCallsKey(teamId),
+ 0,
+ RECENT_CALLS_LIMIT - 1,
+ );
+ } catch (error) {
+ logger.warn("Failed to read recent Alexandria calls", { error, teamId });
+ return [];
+ }
+ return raw.flatMap(entry => {
+ try {
+ const value = JSON.parse(entry);
+ return typeof value?.requestId === "string" &&
+ typeof value.provider === "string" &&
+ typeof value.capability === "string" &&
+ typeof value.at === "number"
+ ? [
+ {
+ requestId: value.requestId,
+ provider: value.provider,
+ capability: value.capability,
+ at: value.at,
+ },
+ ]
+ : [];
+ } catch {
+ return [];
+ }
+ });
+}
diff --git a/apps/api/src/lib/alexandria-feedback-token.test.ts b/apps/api/src/lib/alexandria-feedback-token.test.ts
new file mode 100644
index 000000000..66740115f
--- /dev/null
+++ b/apps/api/src/lib/alexandria-feedback-token.test.ts
@@ -0,0 +1,115 @@
+vi.mock("../config", () => ({
+ config: { EXCHANGE_INTERNAL_SECRET: "internal-secret" },
+}));
+
+import { createHmac } from "node:crypto";
+import { config } from "../config";
+import {
+ MAX_FEEDBACK_TOKEN_LENGTH,
+ issueFeedbackToken,
+ verifyFeedbackToken,
+} from "./alexandria-feedback-token";
+
+const teamId = "01933161-0000-7000-8000-000000000001";
+const now = 1_800_000_000_000;
+const claims = {
+ requestId: "req-1",
+ teamId,
+ provider: "fred",
+ capability: "series/observations",
+};
+
+afterEach(() => {
+ config.EXCHANGE_INTERNAL_SECRET = "internal-secret";
+});
+
+it("round-trips the call it names for the issuing team", () => {
+ const token = issueFeedbackToken(claims, now)!;
+ expect(token).toMatch(/^v1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{22}$/);
+ expect(token.length).toBeLessThan(200);
+ expect(verifyFeedbackToken(token, teamId, now + 1000)).toEqual({
+ requestId: "req-1",
+ provider: "fred",
+ capability: "series/observations",
+ issuedAt: now / 1000,
+ });
+});
+
+it("issues no token that feedback would refuse as too long", () => {
+ const long = {
+ ...claims,
+ provider: "é".repeat(200),
+ capability: "能".repeat(200),
+ };
+ expect(issueFeedbackToken(long, now)).toBeUndefined();
+ expect(issueFeedbackToken(claims, now)!.length).toBeLessThanOrEqual(
+ MAX_FEEDBACK_TOKEN_LENGTH,
+ );
+});
+
+it("rejects the token for any other team", () => {
+ const token = issueFeedbackToken(claims, now)!;
+ expect(
+ verifyFeedbackToken(token, "01933161-0000-7000-8000-000000000002", now),
+ ).toBeNull();
+});
+
+it("expires after 24 hours and refuses tokens from the future", () => {
+ const token = issueFeedbackToken(claims, now)!;
+ expect(
+ verifyFeedbackToken(token, teamId, now + 24 * 3600_000),
+ ).not.toBeNull();
+ expect(
+ verifyFeedbackToken(token, teamId, now + 24 * 3600_000 + 1000),
+ ).toBeNull();
+ expect(verifyFeedbackToken(token, teamId, now - 120_000)).toBeNull();
+});
+
+it("rejects a changed payload, a changed signature and malformed tokens", () => {
+ const token = issueFeedbackToken(claims, now)!;
+ const [version, payload, signature] = token.split(".");
+ const other = Buffer.from(
+ JSON.stringify(["req-1", "sec", "series/observations", now / 1000]),
+ ).toString("base64url");
+ const flipped = Buffer.from(signature, "base64url");
+ flipped[0] ^= 1;
+ for (const bad of [
+ `${version}.${other}.${signature}`,
+ `${version}.${payload}.${flipped.toString("base64url")}`,
+ `v2.${payload}.${signature}`,
+ `${token}.extra`,
+ "v1..",
+ "",
+ ])
+ expect(verifyFeedbackToken(bad, teamId, now)).toBeNull();
+});
+
+it("rejects a validly signed payload of the wrong shape", () => {
+ const key = createHmac("sha256", "internal-secret")
+ .update("alexandria-feedback-token:v1")
+ .digest();
+ const payload = Buffer.from(
+ JSON.stringify(["req-1", "fred", 1, now / 1000]),
+ ).toString("base64url");
+ const signature = createHmac("sha256", key)
+ .update(`v1.${payload}.${teamId}`)
+ .digest()
+ .subarray(0, 16)
+ .toString("base64url");
+ expect(
+ verifyFeedbackToken(`v1.${payload}.${signature}`, teamId, now),
+ ).toBeNull();
+});
+
+it("neither issues nor verifies without a signing key", () => {
+ const token = issueFeedbackToken(claims, now)!;
+ config.EXCHANGE_INTERNAL_SECRET = undefined as never;
+ expect(issueFeedbackToken(claims, now)).toBeUndefined();
+ expect(verifyFeedbackToken(token, teamId, now)).toBeNull();
+});
+
+it("changes every token when the key rotates", () => {
+ const token = issueFeedbackToken(claims, now)!;
+ config.EXCHANGE_INTERNAL_SECRET = "rotated";
+ expect(verifyFeedbackToken(token, teamId, now)).toBeNull();
+});
diff --git a/apps/api/src/lib/alexandria-feedback-token.ts b/apps/api/src/lib/alexandria-feedback-token.ts
new file mode 100644
index 000000000..c0d99966b
--- /dev/null
+++ b/apps/api/src/lib/alexandria-feedback-token.ts
@@ -0,0 +1,92 @@
+import { createHmac, timingSafeEqual } from "node:crypto";
+import { config } from "../config";
+
+const VERSION = "v1";
+const MAX_AGE_SEC = 24 * 60 * 60;
+const CLOCK_SKEW_SEC = 60;
+const SIGNATURE_BYTES = 16;
+/** The longest token feedback accepts; a call whose token would be longer gets none. */
+export const MAX_FEEDBACK_TOKEN_LENGTH = 1024;
+
+export type FeedbackTokenClaims = {
+ requestId: string;
+ provider: string;
+ capability: string;
+ issuedAt: number;
+};
+
+/** Domain-separated so the token key never equals the Exchange caller secret. */
+function signingKey(): Buffer | null {
+ const secret = config.EXCHANGE_INTERNAL_SECRET;
+ if (!secret) return null;
+ return createHmac("sha256", secret)
+ .update("alexandria-feedback-token:v1")
+ .digest();
+}
+
+// The team is signed but not carried, so a token only verifies for its own team.
+const sign = (key: Buffer, payload: string, teamId: string) =>
+ createHmac("sha256", key)
+ .update(`${VERSION}.${payload}.${teamId}`)
+ .digest()
+ .subarray(0, SIGNATURE_BYTES);
+
+/**
+ * A token naming one Alexandria provider call, so feedback can prove which
+ * calls it rates. Returns undefined without a signing key or when the token
+ * would exceed MAX_FEEDBACK_TOKEN_LENGTH.
+ * Callers must not issue tokens under zero data retention.
+ */
+export function issueFeedbackToken(
+ claims: Omit<FeedbackTokenClaims, "issuedAt"> & { teamId: string },
+ now = Date.now(),
+): string | undefined {
+ const key = signingKey();
+ if (!key) return undefined;
+ const payload = Buffer.from(
+ JSON.stringify([
+ claims.requestId,
+ claims.provider,
+ claims.capability,
+ Math.floor(now / 1000),
+ ]),
+ ).toString("base64url");
+ const token = `${VERSION}.${payload}.${sign(key, payload, claims.teamId).toString("base64url")}`;
+ return token.length <= MAX_FEEDBACK_TOKEN_LENGTH ? token : undefined;
+}
+
+/** The token's claims if it was issued to teamId, its signature holds and it is under 24 hours old; otherwise null. */
+export function verifyFeedbackToken(
+ token: string,
+ teamId: string,
+ now = Date.now(),
+): FeedbackTokenClaims | null {
+ const key = signingKey();
+ if (!key) return null;
+ const [version, payload, signature, ...rest] = token.split(".");
+ if (version !== VERSION || !payload || !signature || rest.length > 0)
+ return null;
+ const expected = sign(key, payload, teamId);
+ const given = Buffer.from(signature, "base64url");
+ if (given.length !== expected.length || !timingSafeEqual(given, expected))
+ return null;
+ let fields: unknown;
+ try {
+ fields = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
+ } catch {
+ return null;
+ }
+ if (!Array.isArray(fields) || fields.length !== 4) return null;
+ const [requestId, provider, capability, issuedAt] = fields;
+ if (
+ typeof requestId !== "string" ||
+ typeof provider !== "string" ||
+ typeof capability !== "string" ||
+ typeof issuedAt !== "number" ||
+ !Number.isInteger(issuedAt)
+ )
+ return null;
+ const age = now / 1000 - issuedAt;
+ if (age > MAX_AGE_SEC || age < -CLOCK_SKEW_SEC) return null;
+ return { requestId, provider, capability, issuedAt };
+}
diff --git a/apps/api/src/lib/exchange.test.ts b/apps/api/src/lib/exchange.test.ts
index 8557bd6e5..148f354a5 100644
--- a/apps/api/src/lib/exchange.test.ts
+++ b/apps/api/src/lib/exchange.test.ts
@@ -10,6 +10,7 @@ import {
import {
canUseExchangeForRequest,
clearExchangeProvidersForTest,
+ forwardExchangeToolFeedback,
reportExchangeBilling,
getExchangeAccessForRequest,
getExchangeRequestLogContext,
@@ -1027,3 +1028,91 @@ describe("Exchange terms acceptance", () => {
);
});
});
+
+describe("Exchange tool feedback forward", () => {
+ const original = {
+ url: config.FIRE_EXCHANGE_URL,
+ secret: config.EXCHANGE_INTERNAL_SECRET,
+ };
+ const feedback = {
+ teamId: "01933161-0000-7000-8000-000000000001",
+ feedbackId: "01933161-0000-7000-8000-000000000009",
+ occurredAt: "2026-11-05T12:00:00.000Z",
+ rating: "bad" as const,
+ origin: "mcp",
+ attribution: "token" as const,
+ calls: [
+ {
+ requestId: "req-1",
+ provider: "fred",
+ capability: "series",
+ rating: "good" as const,
+ },
+ ],
+ };
+
+ beforeEach(() => {
+ vi.mocked(fetch).mockReset();
+ config.FIRE_EXCHANGE_URL = "https://exchange.example/";
+ config.EXCHANGE_INTERNAL_SECRET = "internal-secret";
+ });
+ afterEach(() => {
+ config.FIRE_EXCHANGE_URL = original.url;
+ config.EXCHANGE_INTERNAL_SECRET = original.secret;
+ });
+
+ it("posts the rating and its calls with the internal secret and team header", async () => {
+ vi.mocked(fetch).mockResolvedValue({ ok: true, status: 202 } as Awaited<
+ ReturnType<typeof fetch>
+ >);
+ await forwardExchangeToolFeedback(feedback);
+ expect(fetch).toHaveBeenCalledExactlyOnceWith(
+ "https://exchange.example/v1/tool-feedback",
+ expect.objectContaining({
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "x-exchange-secret": "internal-secret",
+ "x-exchange-team-id": feedback.teamId,
+ },
+ signal: expect.any(AbortSignal),
+ }),
+ );
+ expect(
+ JSON.parse(vi.mocked(fetch).mock.calls[0][1]!.body as string),
+ ).toEqual({
+ feedbackId: feedback.feedbackId,
+ occurredAt: feedback.occurredAt,
+ rating: "bad",
+ origin: "mcp",
+ attribution: "token",
+ calls: feedback.calls,
+ });
+ });
+
+ it.each(["FIRE_EXCHANGE_URL", "EXCHANGE_INTERNAL_SECRET"] as const)(
+ "skips the forward without %s",
+ async key => {
+ config[key] = undefined as never;
+ await forwardExchangeToolFeedback(feedback);
+ expect(fetch).not.toHaveBeenCalled();
+ },
+ );
+
+ it("resolves on rejected responses and network errors", async () => {
+ const cancel = vi.fn().mockResolvedValue(undefined);
+ vi.mocked(fetch).mockResolvedValueOnce({
+ ok: false,
+ status: 404,
+ body: { cancel },
+ } as unknown as Awaited<ReturnType<typeof fetch>>);
+ await expect(
+ forwardExchangeToolFeedback(feedback),
+ ).resolves.toBeUndefined();
+ expect(cancel).toHaveBeenCalledOnce();
+ vi.mocked(fetch).mockRejectedValueOnce(new Error("timeout"));
+ await expect(
+ forwardExchangeToolFeedback(feedback),
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/api/src/lib/exchange.ts b/apps/api/src/lib/exchange.ts
index 04467a465..5b805f494 100644
--- a/apps/api/src/lib/exchange.ts
+++ b/apps/api/src/lib/exchange.ts
@@ -811,6 +811,7 @@ export function getExchangeSuccessCredits(input: {
}
const EXCHANGE_BILLING_TIMEOUT_MS = 5_000;
+const EXCHANGE_TOOL_FEEDBACK_TIMEOUT_MS = 3_000;
const EXCHANGE_BILLING_ATTEMPTS = 3;
const EXCHANGE_BILLING_RETRY_DELAY_MS = 2_000;
const EXCHANGE_BILLING_RETRY_MAX_DELAY_MS = 15_000;
@@ -905,6 +906,52 @@ export async function reportExchangeUsageBilling(input: {
});
}
+export type ExchangeToolFeedback = {
+ teamId: string;
+ feedbackId: string;
+ occurredAt: string;
+ rating: "good" | "partial" | "bad";
+ origin: string;
+ attribution: "token" | "window";
+ calls: {
+ requestId: string;
+ provider: string;
+ capability: string;
+ rating: "good" | "partial" | "bad" | null;
+ }[];
+};
+
+/** Forwards an Alexandria feedback rating to the Exchange. Never throws; failures are logged. */
+export async function forwardExchangeToolFeedback(
+ input: ExchangeToolFeedback,
+): Promise<void> {
+ const baseUrl = getExchangeBaseUrl();
+ if (!baseUrl || !config.EXCHANGE_INTERNAL_SECRET) return;
+ const { teamId, ...body } = input;
+ const context = { feedbackId: input.feedbackId, teamId };
+ try {
+ const response = await fetch(`${baseUrl}/v1/tool-feedback`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "x-exchange-secret": config.EXCHANGE_INTERNAL_SECRET,
+ "x-exchange-team-id": teamId,
+ },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(EXCHANGE_TOOL_FEEDBACK_TIMEOUT_MS),
+ });
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => {});
+ rootLogger.warn("Exchange tool feedback rejected", {
+ ...context,
+ statusCode: response.status,
+ });
+ }
+ } catch (error) {
+ rootLogger.warn("Exchange tool feedback errored", { ...context, error });
+ }
+}
+
async function deliverBillingReport(input: {
url: string;
headers: Record<string, string>;
diff --git a/apps/api/src/services/alexandria/contracts.ts b/apps/api/src/services/alexandria/contracts.ts
index 9a010c423..2f0770cc7 100644
--- a/apps/api/src/services/alexandria/contracts.ts
+++ b/apps/api/src/services/alexandria/contracts.ts
@@ -1,5 +1,7 @@
import { z } from "zod";
+export const REQUEST_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
+
export const callSchema = z.strictObject({
provider: z.string().min(1).max(200),
capability: z.string().min(1).max(200),
diff --git a/apps/api/src/services/alexandria/retrieve.ts b/apps/api/src/services/alexandria/retrieve.ts
index 70ee46159..b43e7b027 100644
--- a/apps/api/src/services/alexandria/retrieve.ts
+++ b/apps/api/src/services/alexandria/retrieve.ts
@@ -28,11 +28,12 @@ import { isUsOnly } from "../../lib/us-only";
import {
answerSchema,
refusal,
+ REQUEST_ID_PATTERN,
type ExchangeResponse,
type ProviderCall,
} from "./contracts";
-export const REQUEST_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
+export { REQUEST_ID_PATTERN };
const RETENTION_SECONDS = 7 * 86400;
const GRACE_MS = 30_000;
const HOLD_GRACE_MS = 15 * 60_000;
@@ -80,6 +81,10 @@ const hash = (value: unknown) =>
.update(JSON.stringify(canonical(value)))
.digest("hex");
+/** The request id Exchange records for a team's x-request-id (its usage_events.request_id). */
+export const exchangeRequestId = (teamId: string, requestId: string) =>
+ hash([teamId, requestId]);
+
const unresolved = (chargeId: string) =>
refusal(
503,
@@ -185,7 +190,7 @@ export async function retrieveProviders(input: {
? { organizationId: input.orgId, apiKeyId: input.apiKeyIdText }
: undefined;
const billable = !input.bypassBilling;
- const id = hash([input.teamId, input.requestId]);
+ const id = exchangeRequestId(input.teamId, input.requestId);
const key = `alexandria:retrieve:${id}`;
const zeroDataRetention = input.zeroDataRetention === true;
const usOnly = isUsOnly(input.flags);