import { z } from "zod"; import { normalizeFileMemoryStoreName } from "@/lib/file-memory-core"; import { FILEMEM_DEFAULT_RUN_ID, STORAGE_MODE_VALUES, } from "@/lib/memory-storage-mode"; export const chatRoleSchema = z.enum(["user", "assistant", "system"]); export const chatMessageWireSchema = z.object({ role: chatRoleSchema, content: z.string(), }); export const chatRagKbSchema = z.object({ knowledgeBaseName: z.string().min(1), subspace: z.array(z.string()).optional(), retrievalConfiguration: z.record(z.unknown()).optional(), topK: z.number().int().min(0).max(100).optional(), }); export const chatRagSchema = z.object({ knowledgeBases: z.array(chatRagKbSchema).min(1), topK: z.number().int().min(1).max(200).optional(), }); // 写 scope 的四个字段必须为非空、非通配符字符串。 // 客户端不允许显式发 `*`——通配符仅由服务端在 SearchMemories 调用前注入。 const nonWildcardId = z .string() .trim() .min(1) .refine((v) => v !== "*", { message: "wildcard '*' is not allowed on the wire; the server applies it", }); const memoryFilesCacheSchema = z.object({ ok: z.boolean(), listed: z.number().int().nonnegative(), loaded: z.number().int().nonnegative(), reused: z.number().int().nonnegative(), totalBytes: z.number().int().nonnegative(), truncated: z.boolean(), error: z.string().max(4_000).optional(), }); const browserFileContextSchema = z.object({ files: z .array( z.object({ rel: z.string().min(1).max(512), size: z.number().int().nonnegative(), sha256: z.string().min(1).max(256).optional(), }), ) .max(300), hits: z .array( z.object({ text: z.string().min(1).max(4_000), source: z.string().min(1).max(512), score: z.number().min(0).max(1), }), ) .max(50), cache: memoryFilesCacheSchema, }); const chatMemoryWireSchema = z .object({ memoryStoreName: z.string().min(1), storageMode: z.enum(STORAGE_MODE_VALUES).optional(), scope: z.object({ appId: nonWildcardId, tenantId: nonWildcardId, agentId: nonWildcardId, runId: nonWildcardId, }), topK: z.number().int().min(1).max(50).optional(), autoSave: z.boolean().optional(), turnId: z.string().min(1).optional(), // 缺省 "search"(语义检索);"local" 由 Chat BFF 走 Item API + 有界 SHA cache。 retrievalMode: z.enum(["search", "local"]).optional(), fileContext: browserFileContextSchema.optional(), }) .superRefine((memory, ctx) => { if (memory.storageMode === "filemem" && !memory.memoryStoreName.trim()) { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["memoryStoreName"], message: "File Memory store name cannot be blank", }); } }); type ChatMemoryWire = z.infer; function normalizeChatMemory(memory: ChatMemoryWire) { return memory.storageMode === "filemem" ? { ...memory, memoryStoreName: normalizeFileMemoryStoreName(memory.memoryStoreName), scope: { ...memory.scope, runId: FILEMEM_DEFAULT_RUN_ID }, retrievalMode: "local" as const, } : memory; } export const chatMemorySchema = chatMemoryWireSchema.transform(normalizeChatMemory); const chatWikiSchema = z .object({ memoryStoreName: z.string().trim().min(1), scope: z .object({ appId: nonWildcardId, tenantId: nonWildcardId, agentId: nonWildcardId, runId: nonWildcardId, }) .strict(), topK: z.number().int().min(1).max(10), }) .strict(); /** * Server-side validation for the chat endpoint payload. The last message must * be from the user; this rule is enforced in the route handler rather than * the schema so we can emit a friendlier SSE error frame. */ export const chatRequestSchema = z .object({ activeInstance: z.string().min(1).nullable().optional(), providerId: z.string().min(1), model: z.string().min(1), messages: z.array(chatMessageWireSchema).min(1), systemPrompt: z.string().max(8_000).optional(), temperature: z.number().min(0).max(2).optional(), rag: chatRagSchema.optional(), memory: chatMemoryWireSchema.optional(), wiki: chatWikiSchema.optional(), }) .strict() .superRefine((request, ctx) => { if (!request.wiki) return; if (!request.memory) { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["wiki"], message: "Wiki binding requires a Memory binding", }); return; } if (!request.memory.storageMode) { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["memory", "storageMode"], message: "Wiki binding requires an explicit Memory storage mode", }); return; } const isFileMemory = request.memory.storageMode === "filemem"; const memoryStoreName = isFileMemory ? request.memory.memoryStoreName.trim() : request.memory.memoryStoreName; const wikiStoreName = isFileMemory ? request.wiki.memoryStoreName.trim() : request.wiki.memoryStoreName; if (wikiStoreName !== memoryStoreName) { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["wiki", "memoryStoreName"], message: "Wiki and Memory stores must match", }); } const scopeFields = ["appId", "tenantId", "agentId"] as const; scopeFields.forEach((field) => { if (request.wiki?.scope[field] !== request.memory?.scope[field]) { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["wiki", "scope", field], message: `Wiki and Memory scope.${field} must match`, }); } }); }) .transform((request) => { if (request.memory?.storageMode !== "filemem") return request; const memory = normalizeChatMemory(request.memory); return { ...request, memory, ...(request.wiki ? { wiki: { ...request.wiki, memoryStoreName: memory.memoryStoreName, scope: memory.scope, }, } : {}), }; }); export type ChatRequestInput = z.infer;