Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

feat(inspector): add types, contextKey, kindDetector (F1)

diegosouzapw411a6d85d187
diff --git a/src/lib/inspector/secretMask.ts b/src/lib/inspector/secretMask.ts
new file mode 100644
index 0000000000..5d7ee151f7
--- /dev/null
+++ b/src/lib/inspector/secretMask.ts
@@ -0,0 +1,6 @@
+/**
+ * Re-export of maskSecret from src/mitm/maskSecrets.ts.
+ * Preserves the module name used in plano 12 (Traffic Inspector).
+ * The single implementation lives in src/mitm/maskSecrets.ts (D8).
+ */
+export { maskSecret } from "@/mitm/maskSecrets";
diff --git a/src/mitm/inspector/contextKey.ts b/src/mitm/inspector/contextKey.ts
new file mode 100644
index 0000000000..9a88ad5418
--- /dev/null
+++ b/src/mitm/inspector/contextKey.ts
@@ -0,0 +1,98 @@
+import { createHash } from "node:crypto";
+import type { InterceptedRequest } from "./types";
+
+/**
+ * Extract the system prompt string from an intercepted LLM request body.
+ * Supports OpenAI/Anthropic chat (messages[0] role=system),
+ * Anthropic messages API (top-level `system` field),
+ * and Gemini (systemInstruction.parts[].text).
+ *
+ * @returns Concatenated system prompt string, or null if not found.
+ */
+export function extractSystemPrompt(req: InterceptedRequest): string | null {
+ if (!req.requestBody) return null;
+
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(req.requestBody);
+ } catch {
+ return null;
+ }
+
+ if (!parsed || typeof parsed !== "object") return null;
+
+ const body = parsed as Record<string, unknown>;
+
+ // 1. Anthropic messages API — top-level `system` field (string or array)
+ if (typeof body.system === "string" && body.system.length > 0) {
+ return body.system;
+ }
+ if (Array.isArray(body.system)) {
+ const parts = body.system
+ .map((p: unknown) => {
+ if (typeof p === "object" && p !== null && "text" in p) {
+ return String((p as Record<string, unknown>).text);
+ }
+ return null;
+ })
+ .filter(Boolean);
+ if (parts.length > 0) return parts.join("\n");
+ }
+
+ // 2. OpenAI/Anthropic chat — messages[0] with role=system
+ if (Array.isArray(body.messages)) {
+ const first = body.messages[0];
+ if (
+ first &&
+ typeof first === "object" &&
+ "role" in first &&
+ (first as Record<string, unknown>).role === "system"
+ ) {
+ const content = (first as Record<string, unknown>).content;
+ if (typeof content === "string") return content;
+ if (Array.isArray(content)) {
+ const texts = content
+ .map((c: unknown) => {
+ if (typeof c === "object" && c !== null && "text" in c) {
+ return String((c as Record<string, unknown>).text);
+ }
+ return null;
+ })
+ .filter(Boolean);
+ if (texts.length > 0) return texts.join("\n");
+ }
+ }
+ }
+
+ // 3. Gemini — systemInstruction.parts[].text
+ if (
+ body.systemInstruction &&
+ typeof body.systemInstruction === "object" &&
+ "parts" in body.systemInstruction
+ ) {
+ const parts = (body.systemInstruction as Record<string, unknown>).parts;
+ if (Array.isArray(parts)) {
+ const texts = parts
+ .map((p: unknown) => {
+ if (typeof p === "object" && p !== null && "text" in p) {
+ return String((p as Record<string, unknown>).text);
+ }
+ return null;
+ })
+ .filter(Boolean);
+ if (texts.length > 0) return texts.join("\n");
+ }
+ }
+
+ return null;
+}
+
+/**
+ * Compute a 12-hex SHA-256 fingerprint of the system prompt.
+ * Returns null if no system prompt is found.
+ */
+export function computeContextKey(req: InterceptedRequest): string | null {
+ const sys = extractSystemPrompt(req);
+ if (!sys) return null;
+ return createHash("sha256").update(sys).digest("hex").slice(0, 12);
+}
diff --git a/src/mitm/inspector/kindDetector.ts b/src/mitm/inspector/kindDetector.ts
new file mode 100644
index 0000000000..7b7c04a4be
--- /dev/null
+++ b/src/mitm/inspector/kindDetector.ts
@@ -0,0 +1,88 @@
+import type { InterceptedRequest, LlmMetadata } from "./types";
+
+/**
+ * LLM host patterns — 18+ known LLM API hostnames.
+ */
+const LLM_HOST_PATTERNS: RegExp[] = [
+ /^api\.openai\.com$/i,
+ /^api\.anthropic\.com$/i,
+ /^generativelanguage\.googleapis\.com$/i,
+ /^.*\.openai\.azure\.com$/i,
+ /^api\.mistral\.ai$/i,
+ /^api\.deepseek\.com$/i,
+ /^api\.groq\.com$/i,
+ /^api\.together\.xyz$/i,
+ /^api\.fireworks\.ai$/i,
+ /^api\.cohere\.com$/i,
+ /^api\.perplexity\.ai$/i,
+ /^.*\.huggingface\.co$/i,
+ /^openrouter\.ai$/i,
+ /^api\.x\.ai$/i,
+ /^api\.moonshot\.ai$/i,
+ /^bigmodel\.cn$/i,
+ /^.*\.bytedance\.com$/i,
+ /^.*\.aliyun\.com$/i,
+];
+
+const LLM_PATH_PATTERNS: RegExp[] = [
+ /\/(v1|v1beta)\/(chat\/)?completions/i,
+ /\/messages/i,
+ /\/embeddings/i,
+ /\/responses/i,
+ /\/models/i,
+ /\/generateContent/i,
+ /\/streamGenerateContent/i,
+];
+
+interface BodyShape {
+ key: string;
+ arrayItem?: boolean;
+}
+
+const LLM_BODY_SHAPES: BodyShape[] = [
+ { key: "messages", arrayItem: true },
+ { key: "contents", arrayItem: true },
+ { key: "prompt" },
+ { key: "input" },
+ { key: "model" },
+];
+
+function matchesShape(json: Record<string, unknown>, shape: BodyShape): boolean {
+ if (!(shape.key in json)) return false;
+ if (shape.arrayItem) {
+ return Array.isArray(json[shape.key]);
+ }
+ return true;
+}
+
+const LLM_UA_PATTERN = /codex|claude|gemini|antigravity|kiro|copilot|cursor/i;
+
+export function detectKind(req: InterceptedRequest): "llm" | "app" | "unknown" {
+ if (LLM_HOST_PATTERNS.some((re) => re.test(req.host))) return "llm";
+ if (LLM_PATH_PATTERNS.some((re) => re.test(req.path))) return "llm";
+
+ if (req.requestBody) {
+ try {
+ const parsed = JSON.parse(req.requestBody) as unknown;
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
+ const body = parsed as Record<string, unknown>;
+ if (LLM_BODY_SHAPES.some((shape) => matchesShape(body, shape))) return "llm";
+ }
+ } catch {
+ // Non-JSON body — cannot detect from body
+ }
+ }
+
+ const ua = req.requestHeaders["user-agent"] ?? req.requestHeaders["User-Agent"] ?? "";
+ if (LLM_UA_PATTERN.test(ua)) return "llm";
+
+ return "app";
+}
+
+/**
+ * Skeleton LLM metadata extractor. Full implementation in F4.
+ */
+export function extractLlmMetadata(req: InterceptedRequest): LlmMetadata | null {
+ if (detectKind(req) !== "llm") return null;
+ return null; // stub — F4 will implement
+}
diff --git a/src/mitm/inspector/types.ts b/src/mitm/inspector/types.ts
new file mode 100644
index 0000000000..5079d836b7
--- /dev/null
+++ b/src/mitm/inspector/types.ts
@@ -0,0 +1,103 @@
+import { z } from "zod";
+
+export type CaptureSource = "agent-bridge" | "custom-host" | "http-proxy" | "system-proxy";
+export type DetectedKind = "llm" | "app" | "unknown";
+
+export interface InterceptedRequest {
+ id: string; // uuid
+ source: CaptureSource;
+ agent?: import("../types").AgentId; // only when source === "agent-bridge"
+ timestamp: string; // ISO 8601
+ method: string;
+ host: string;
+ path: string;
+ requestHeaders: Record<string, string>;
+ requestBody: string | null; // masked
+ requestSize: number;
+ responseHeaders: Record<string, string>;
+ responseBody: string | null;
+ responseSize: number;
+ status: number | "in-flight" | "error";
+ proxyLatencyMs?: number;
+ upstreamLatencyMs?: number;
+ totalLatencyMs?: number;
+ error?: string; // sanitized
+ sourceModel?: string | null;
+ mappedModel?: string | null;
+ detectedKind?: DetectedKind;
+ contextKey?: string; // 12-hex SHA-256 of system prompt
+ annotation?: string;
+ sessionId?: string;
+ note?: string;
+}
+
+export const InterceptedRequestSchema = z.object({
+ id: z.string().uuid(),
+ source: z.enum(["agent-bridge", "custom-host", "http-proxy", "system-proxy"]),
+ agent: z.string().optional(),
+ timestamp: z.string().datetime(),
+ method: z.string(),
+ host: z.string(),
+ path: z.string(),
+ requestHeaders: z.record(z.string()),
+ requestBody: z.string().nullable(),
+ requestSize: z.number().int().nonnegative(),
+ responseHeaders: z.record(z.string()),
+ responseBody: z.string().nullable(),
+ responseSize: z.number().int().nonnegative(),
+ status: z.union([z.number().int(), z.literal("in-flight"), z.literal("error")]),
+ proxyLatencyMs: z.number().nonnegative().optional(),
+ upstreamLatencyMs: z.number().nonnegative().optional(),
+ totalLatencyMs: z.number().nonnegative().optional(),
+ error: z.string().optional(),
+ sourceModel: z.string().nullable().optional(),
+ mappedModel: z.string().nullable().optional(),
+ detectedKind: z.enum(["llm", "app", "unknown"]).optional(),
+ contextKey: z.string().optional(),
+ annotation: z.string().optional(),
+ sessionId: z.string().uuid().optional(),
+ note: z.string().optional(),
+});
+
+export type NormalizedBlock =
+ | { type: "text"; text: string }
+ | { type: "tool_use"; id: string; name: string; input: unknown }
+ | { type: "tool_result"; tool_use_id: string; content: unknown };
+
+export interface NormalizedTurn {
+ role: "system" | "user" | "assistant" | "tool";
+ blocks: NormalizedBlock[];
+}
+
+export interface NormalizedConversation {
+ request: NormalizedTurn[];
+ response: NormalizedTurn[];
+ contextKey: string | null;
+}
+
+export interface LlmMetadata {
+ provider: string | null;
+ apiKind: string | null;
+ model: string | null;
+ messages: number;
+ tokensIn: number | null;
+ tokensOut: number | null;
+ streamed: boolean;
+ mappedTo: string | null;
+ costEstimateUsd: number | null;
+}
+
+export type WsEvent =
+ | { type: "snapshot"; data: InterceptedRequest[] }
+ | { type: "new"; data: InterceptedRequest }
+ | { type: "update"; data: InterceptedRequest }
+ | { type: "clear" };
+
+export type ListFilters = {
+ profile?: "llm" | "custom" | "all";
+ host?: string;
+ agent?: import("../types").AgentId;
+ status?: "2xx" | "3xx" | "4xx" | "5xx" | "error";
+ source?: CaptureSource;
+ sessionId?: string;
+};