Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(ai-gateway): wire Sentry capture to model error paths + PII scrubber

Louis Beaumonteff9b61f1c3d
diff --git a/packages/ai-gateway/src/handlers/chat.ts b/packages/ai-gateway/src/handlers/chat.ts
index 13809d8b4..da8533eee 100644
--- a/packages/ai-gateway/src/handlers/chat.ts
+++ b/packages/ai-gateway/src/handlers/chat.ts
@@ -5,6 +5,7 @@ import { Env, RequestBody } from '../types';
import { createProvider } from '../providers';
import { addCorsHeaders } from '../utils/cors';
import { logModelOutcome } from '../services/model-health';
+import { captureException } from '@sentry/cloudflare';
// Auto model waterfall — ordered by quality/cost ratio (all free or near-free).
//
@@ -71,9 +72,25 @@ async function tryModel(model: string, body: RequestBody, env: Env): Promise<Res
if (status === 429 || status >= 500 || status === 408 || msg.includes('429') || msg.includes('Resource exhausted')) {
console.warn(`auto: ${model} failed (${status}), trying next`);
logModelOutcome(env, { model, outcome: status === 429 ? 'rate_limited' : 'error' }).catch(() => {});
+ // Rate limits are expected/noisy — skip Sentry for those. 5xx is a
+ // real upstream failure worth knowing about even though we retry.
+ if (status !== 429) {
+ try {
+ captureException(error, {
+ tags: { model, error_path: 'auto_waterfall', status: String(status) },
+ level: 'warning',
+ });
+ } catch {}
+ }
return null;
}
// Non-retriable (400, 401, 403) — bubble up
+ try {
+ captureException(error, {
+ tags: { model, error_path: 'auto_waterfall_fatal', status: String(status) },
+ level: 'error',
+ });
+ } catch {}
throw error;
}
}
diff --git a/packages/ai-gateway/src/index.ts b/packages/ai-gateway/src/index.ts
index 0c456f3f4..ede4527be 100644
--- a/packages/ai-gateway/src/index.ts
+++ b/packages/ai-gateway/src/index.ts
@@ -520,6 +520,65 @@ async function handleRequest(request: Request, env: Env, ctx: ExecutionContext):
}
}
+// Strip PII from a Sentry event before send. The default @sentry/cloudflare
+// integration attaches request headers, URL, and (for traces) query string —
+// all of which regularly contain Clerk JWTs (user_id + email inside the
+// token payload) and device fingerprints. Error messages can also include
+// full prompts. We keep enough context to debug (method, path, status,
+// model, provider tags) while redacting anything that identifies a user.
+function scrubSentryEvent(event: any): any {
+ const REDACTED = '[REDACTED]';
+ const cap = (s: unknown, n = 512): string => {
+ if (typeof s !== 'string') return typeof s === 'undefined' ? '' : String(s);
+ return s.length > n ? s.slice(0, n) + '…[truncated]' : s;
+ };
+ const redactQs = (qs: string): string =>
+ qs
+ .replace(/(^|&)(id|user_id|email|token)=[^&]*/gi, '$1$2=' + REDACTED)
+ .replace(/user_[A-Za-z0-9]+/g, 'user_' + REDACTED);
+ const redactUrl = (url: string): string => {
+ if (!url) return url;
+ const [base, qs] = url.split('?');
+ return qs ? `${base}?${redactQs(qs)}` : base;
+ };
+
+ try {
+ if (event.request) {
+ if (event.request.headers) {
+ // Headers often contain Authorization: Bearer <JWT>, Cookie, X-Device-Id
+ for (const k of Object.keys(event.request.headers)) {
+ const lk = k.toLowerCase();
+ if (
+ lk === 'authorization' ||
+ lk === 'cookie' ||
+ lk === 'x-device-id' ||
+ lk === 'x-forwarded-for' ||
+ lk === 'cf-connecting-ip'
+ ) {
+ event.request.headers[k] = REDACTED;
+ }
+ }
+ }
+ if (event.request.url) event.request.url = redactUrl(event.request.url);
+ if (event.request.query_string) event.request.query_string = redactQs(event.request.query_string);
+ // Request body can contain full prompt text — drop it. Error tags will
+ // carry the model/provider which is what we actually need to triage.
+ if (event.request.data) event.request.data = '[body redacted]';
+ }
+ // Truncate exception messages so a stack trace with leaked prompt text
+ // doesn't fill the event — stack frames themselves stay intact.
+ if (event.exception?.values) {
+ for (const v of event.exception.values) {
+ if (v.value) v.value = cap(v.value);
+ }
+ }
+ if (event.message) event.message = cap(event.message);
+ } catch {
+ // Never let the scrubber itself throw — it would mask the real error.
+ }
+ return event;
+}
+
// Wrap with Sentry for error tracking
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
@@ -528,6 +587,7 @@ export default {
options: {
dsn: env.SENTRY_DSN,
tracesSampleRate: 0.1,
+ beforeSend: scrubSentryEvent,
},
request: request as any,
context: ctx,
diff --git a/packages/ai-gateway/src/providers/openai.ts b/packages/ai-gateway/src/providers/openai.ts
index 4057a852a..cfe83373c 100644
--- a/packages/ai-gateway/src/providers/openai.ts
+++ b/packages/ai-gateway/src/providers/openai.ts
@@ -3,6 +3,7 @@ import { Message, RequestBody, ResponseFormat } from '../types';
import OpenAI from 'openai';
import type { ChatCompletionMessage, ChatCompletionCreateParams } from 'openai/resources/chat';
import type { ResponseFormatJSONSchema } from 'openai/resources';
+import { captureException } from '@sentry/cloudflare';
export class OpenAIProvider implements AIProvider {
supportsTools = true;
@@ -71,7 +72,12 @@ export class OpenAIProvider implements AIProvider {
response_format: this.formatResponseFormat(body.response_format),
tools: body.tools as ChatCompletionCreateParams['tools'],
});
-
+
+ // Capture scope fields for the error path below — `this` inside the
+ // ReadableStream start() refers to the controller, not the provider.
+ const modelForTags = body.model;
+ const baseURLForTags = this.client.baseURL || 'openai-default';
+
return new ReadableStream({
async start(controller) {
try {
@@ -105,6 +111,22 @@ export class OpenAIProvider implements AIProvider {
controller.close();
} catch (error: any) {
console.error('Streaming error:', error);
+ // Record the error in Sentry with model/provider tags. This
+ // path is normally swallowed into an SSE `data: {error:…}`
+ // event, so without this the client sees "random error"
+ // and we have no server-side trace. Tags let you filter
+ // by model (e.g. gemma4-31b) or provider (e.g. tinfoil).
+ try {
+ captureException(error, {
+ tags: {
+ model: modelForTags,
+ base_url: baseURLForTags,
+ error_path: 'openai_streaming',
+ status: String(error?.status ?? 'unknown'),
+ },
+ level: 'warning',
+ });
+ } catch {}
const errorMessage = error?.message || 'Unknown streaming error';
const errorStatus = error?.status || 500;
try {