"use client"; import type { ChatMemoryWriteScope } from "@/components/chat/chat-config-context"; import { getItem as getItemService, listItems as listItemsService, } from "@/services/file-memory"; import { FileMemoryCache, fileMemoryCacheKey, MAX_FILE_MEMORY_BYTES, MAX_FILE_MEMORY_FILES, MAX_FILE_MEMORY_SNAPSHOTS, type FileMemoryCacheSummary, type FileMemoryEntry, type FileMemoryHit, type FileMemoryTransport, normalizeFileMemoryScope, normalizeFileMemoryStoreName, } from "@/lib/file-memory-core"; export const BROWSER_FILE_MEMORY_LABEL = "标签页内容缓存 · 通过 Item API 按 SHA 复用"; export const MAX_BROWSER_FILE_MEMORY_FILES = MAX_FILE_MEMORY_FILES; export const MAX_BROWSER_FILE_MEMORY_BYTES = MAX_FILE_MEMORY_BYTES; export const MAX_BROWSER_FILE_MEMORY_SNAPSHOTS = MAX_FILE_MEMORY_SNAPSHOTS; export type BrowserFileMemoryEntry = FileMemoryEntry; export type BrowserFileMemoryHit = FileMemoryHit; export type BrowserFileMemoryCacheSummary = FileMemoryCacheSummary; type ListItems = typeof listItemsService; type GetItem = typeof getItemService; export interface LoadBrowserFileMemoryOptions { dataScopeKey: string; memoryStoreName: string; scope: ChatMemoryWriteScope; listItems?: ListItems; getItem?: GetItem; } export interface LoadBrowserFileMemoryResult { key: string; files: BrowserFileMemoryEntry[]; cache: BrowserFileMemoryCacheSummary; } const cache = new FileMemoryCache(); export function browserFileMemoryKey(opts: { dataScopeKey: string; memoryStoreName: string; scope: ChatMemoryWriteScope; }): string { return fileMemoryCacheKey( opts.dataScopeKey, opts.memoryStoreName, normalizeFileMemoryScope(opts.scope), ); } export function loadBrowserFileMemory( opts: LoadBrowserFileMemoryOptions, ): Promise { const scope = normalizeFileMemoryScope(opts.scope); const memoryStoreName = normalizeFileMemoryStoreName(opts.memoryStoreName); const key = browserFileMemoryKey({ ...opts, memoryStoreName, scope }); const list = opts.listItems ?? listItemsService; const get = opts.getItem ?? getItemService; const transport: FileMemoryTransport = { async listItems(request) { const { memoryStoreName, ...input } = request; return list(memoryStoreName, input); }, async getItem(request) { const { memoryStoreName, ...input } = request; return get(memoryStoreName, input); }, }; return cache.load({ key, memoryStoreName, scope, transport, }); } export function readBrowserFileMemoryFile(key: string, rel: string): string { return cache.readFile(key, rel); } export function searchBrowserFileMemory(opts: { key: string; query: string; topK: number; }): { results: BrowserFileMemoryHit[]; skipped?: boolean } { return cache.search(opts); } export function clearBrowserFileMemoryForTests(): void { cache.clear(); }