import type { PaginatedData } from "@/types/api"; import { hasPreciseScope } from "@/lib/memory"; import type { AddMemoryRequest, CreateDreamTaskRequest, CreateMemoryStoreRequest, DeleteMemoryUnitRequest, DreamActionFilter, DreamActionRecord, DreamApplyActionResult, DreamDepositResult, DreamTask, DreamTaskSummary, GetMemoryUnitRequest, MemoryRequestLog, MemoryScope, ScopeDirectoryRequest, ScopeDirectoryResponse, ScopeDirectoryFilter, SearchMemoryResponse, MemoryStore, MemoryTask, MemoryUnit, SearchMemoryRequest, SessionMessage, UpdateMemoryStoreRequest, UpdateMemoryUnitRequest, } from "@/types/memory"; import { apiDelete, apiGet, apiPost, apiPut } from "./api-client"; export type ScopedPaginatedData = PaginatedData & { scope: MemoryScope; memoryStoreName?: string; }; function buildScopeQuery( scope: MemoryScope | undefined, extra?: Record, ): string { const params = new URLSearchParams(); if (scope?.appId) params.set("appId", scope.appId); if (scope?.tenantId) params.set("tenantId", scope.tenantId); if (scope?.agentId) params.set("agentId", scope.agentId); if (scope?.runId) params.set("runId", scope.runId); Object.entries(extra ?? {}).forEach(([key, value]) => { if (value !== undefined && value !== "") { params.set(key, String(value)); } }); return params.toString(); } export async function listMemoryStores(): Promise> { return apiGet>("/api/v1/memory/stores"); } export async function describeMemoryStore( memoryStoreName: string, ): Promise { return apiGet( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}`, ); } export async function createMemoryStore( request: CreateMemoryStoreRequest, ): Promise { await apiPost>("/api/v1/memory/stores", request); } export async function updateMemoryStore( request: UpdateMemoryStoreRequest, ): Promise { const { memoryStoreName, ...body } = request; await apiPut>( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}`, body, ); } export async function deleteMemoryStore( memoryStoreName: string, ): Promise { await apiDelete>( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}`, ); } export async function listMemoryUnits( memoryStoreName: string, scope: MemoryScope, options?: { limit?: number; nextToken?: string; filter?: ScopeDirectoryFilter; }, ): Promise> { const query = buildScopeQuery(scope, { limit: options?.limit, nextToken: options?.nextToken, ...(options?.filter ? { filter: JSON.stringify(options.filter) } : {}), }); return apiGet>( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}/units?${query}`, ); } export async function addMemory(request: AddMemoryRequest): Promise { const { memoryStoreName, ...body } = request; return apiPost( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}/units`, body, ); } export async function getMemoryUnit( request: GetMemoryUnitRequest, ): Promise<{ memory: MemoryUnit; memoryStoreName: string }> { const query = buildScopeQuery( request.scope && hasPreciseScope(request.scope) ? request.scope : undefined, ); return apiGet( `/api/v1/memory/stores/${encodeURIComponent(request.memoryStoreName)}/units/${encodeURIComponent(request.memoryId)}${query ? `?${query}` : ""}`, ); } export async function updateMemoryUnit( request: UpdateMemoryUnitRequest, ): Promise<{ memory: MemoryUnit; updated: boolean; memoryStoreName: string }> { const { memoryStoreName, memoryId, ...body } = request; return apiPut( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}/units/${encodeURIComponent(memoryId)}`, body, ); } export async function deleteMemoryUnit( request: DeleteMemoryUnitRequest, ): Promise { const { memoryStoreName, memoryId, ...body } = request; await apiDelete>( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}/units/${encodeURIComponent(memoryId)}`, body, ); } export async function searchMemory( request: SearchMemoryRequest, ): Promise { const { memoryStoreName, ...body } = request; return apiPost( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}/search`, body, ); } export async function queryMemoryStoreScopes( memoryStoreName: string, request: ScopeDirectoryRequest, ): Promise { return apiPost( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}/scopes`, request, ); } export async function listMemoryMessages( memoryStoreName: string, scope: MemoryScope, options?: { limit?: number; nextToken?: string; minTimestamp?: string; maxTimestamp?: string; }, ): Promise> { const query = buildScopeQuery(scope, options); return apiGet>( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}/messages?${query}`, ); } export async function listMemoryRequests( memoryStoreName: string, scope: MemoryScope, options?: { limit?: number; nextToken?: string; operation?: string; minTimestamp?: string; maxTimestamp?: string; }, ): Promise> { const query = buildScopeQuery(scope, options); return apiGet>( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}/requests?${query}`, ); } export async function listMemoryStoreScopesUnfiltered( memoryStoreName: string, ): Promise<{ items: MemoryScope[]; totalCount: number; }> { return apiGet( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}/scopes?limit=100`, ); } // --------------------------------------------------------------------------- // Memory store scopes / ingest tasks (SDK 0.0.3+) // --------------------------------------------------------------------------- export async function listMemoryStoreScopes( memoryStoreName: string, scope: MemoryScope, options?: { limit?: number; nextToken?: string }, ): Promise<{ items: MemoryScope[]; totalCount: number; nextToken?: string; scope: MemoryScope; memoryStoreName: string; }> { const query = buildScopeQuery(scope, options); return apiGet( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}/scopes?${query}`, ); } /** * Server-side `ListMemoryStoreScopes` dedups conversation_key in-memory per * call but loses that state across pages, so the same scope can come back on * the next nextToken page. The dashboard suggestion popover wants a complete, * deduped picture, so we walk every page client-side and dedup with a Set. * * Capped at MAX_PAGES to bound worst-case fetch budget on stores with very * fragmented data — far past that, the suggestion list stops being useful UX. * * `pageSize` is 100 because that is the engine's own ceiling: asking for 200, * 500 or 1000 all come back with exactly 100 items and a byte-identical * nextToken. Raising it buys nothing. * * That matters because nextToken carries the engine's already-seen scope set * (base64 JSON, ~74 bytes per scope) and we hand it back in the query string, * so deep paging eventually blows Node's 16KB `maxHeaderSize` and the request * 431s at somewhere past ~200 scopes. We can't page around it from here — the * real fix is moving the token off the URL — so we degrade instead of * exploding: a page that fails after we already have results returns those * results marked `truncated`, which the UI renders as "first N only" rather * than an error that throws the whole list away. */ export async function listAllMemoryStoreScopes( memoryStoreName: string, scope: MemoryScope, options?: { pageSize?: number; maxPages?: number }, ): Promise<{ items: MemoryScope[]; totalCount: number; truncated: boolean }> { const pageSize = options?.pageSize ?? 100; const maxPages = options?.maxPages ?? 20; const seen = new Set(); const items: MemoryScope[] = []; let nextToken: string | undefined; let truncated = false; for (let page = 0; page < maxPages; page++) { let data: Awaited>; try { data = await listMemoryStoreScopes(memoryStoreName, scope, { limit: pageSize, nextToken, }); } catch (error) { // Nothing to show yet — let the caller surface a real error state. if (items.length === 0) throw error; truncated = true; break; } for (const s of data.items) { const key = `${s.appId ?? ""}|${s.tenantId ?? ""}|${s.agentId ?? ""}|${s.runId ?? ""}`; if (seen.has(key)) continue; seen.add(key); items.push(s); } nextToken = data.nextToken; if (!nextToken) break; if (page === maxPages - 1) truncated = true; } return { items, totalCount: items.length, truncated }; } export async function listMemoryTasks( memoryStoreName: string, scope: MemoryScope, options?: { limit?: number; nextToken?: string; status?: string; minTimestamp?: string; maxTimestamp?: string; }, ): Promise<{ items: MemoryTask[]; totalCount: number; nextToken?: string; scope: MemoryScope; memoryStoreName: string; }> { const query = buildScopeQuery(scope, options); return apiGet( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}/tasks?${query}`, ); } export async function getMemoryTask( memoryStoreName: string, requestId: string, scope?: MemoryScope, ): Promise<{ task: MemoryTask; memoryStoreName: string }> { const query = scope ? buildScopeQuery(scope) : ""; const path = `/api/v1/memory/stores/${encodeURIComponent( memoryStoreName, )}/tasks/${encodeURIComponent(requestId)}${query ? `?${query}` : ""}`; return apiGet(path); } // --------------------------------------------------------------------------- // Dreaming (SDK 0.0.3+) // --------------------------------------------------------------------------- export async function listDreamTasks( memoryStoreName: string, scope: MemoryScope, options?: { limit?: number; nextToken?: string; status?: string; minTimestamp?: string; maxTimestamp?: string; }, ): Promise<{ items: DreamTask[]; totalCount: number; scope: MemoryScope; memoryStoreName: string; nextToken?: string; }> { const query = buildScopeQuery(scope, options); return apiGet( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}/dream-tasks?${query}`, ); } export async function createDreamTask( memoryStoreName: string, request: CreateDreamTaskRequest, ): Promise<{ memoryStoreName: string; dreamId: string; status: string; createdAt: string; }> { return apiPost( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}/dream-tasks`, request, ); } export async function getDreamTask( memoryStoreName: string, dreamId: string, ): Promise { return apiGet( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}/dream-tasks/${encodeURIComponent(dreamId)}`, ); } export async function cancelDreamTask( memoryStoreName: string, dreamId: string, ): Promise<{ memoryStoreName: string; dreamId: string; status: string }> { return apiPost( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}/dream-tasks/${encodeURIComponent(dreamId)}/cancel`, {}, ); } export async function listDreamActions( memoryStoreName: string, dreamId: string, filter?: DreamActionFilter, pagination?: { limit?: number; nextToken?: string }, ): Promise<{ memoryStoreName: string; dreamId: string; items: DreamActionRecord[]; totalCount: number; nextToken?: string; }> { const params = new URLSearchParams(); if (filter?.status) params.set("status", filter.status); if (filter?.action) params.set("action", filter.action); if (filter?.sourceMemoryId) params.set("sourceMemoryId", filter.sourceMemoryId); if (filter?.orderBy) params.set("orderBy", filter.orderBy); if (filter?.minConfidence !== undefined) params.set("minConfidence", String(filter.minConfidence)); if (filter?.maxConfidence !== undefined) params.set("maxConfidence", String(filter.maxConfidence)); if (filter?.targetScope) { if (filter.targetScope.appId) params.set("targetAppId", filter.targetScope.appId); if (filter.targetScope.tenantId) params.set("targetTenantId", filter.targetScope.tenantId); if (filter.targetScope.agentId) params.set("targetAgentId", filter.targetScope.agentId); if (filter.targetScope.runId) params.set("targetRunId", filter.targetScope.runId); } if (pagination?.limit !== undefined) params.set("limit", String(pagination.limit)); if (pagination?.nextToken) params.set("nextToken", pagination.nextToken); const qs = params.toString(); const path = `/api/v1/memory/stores/${encodeURIComponent( memoryStoreName, )}/dream-tasks/${encodeURIComponent(dreamId)}/actions${qs ? `?${qs}` : ""}`; return apiGet(path); } export async function applyDreamActions( memoryStoreName: string, dreamId: string, actionIds: string[], applier?: string, ): Promise<{ memoryStoreName: string; dreamId: string; applied: number; failed: number; notFound?: number; results: DreamApplyActionResult[]; }> { return apiPost( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}/dream-tasks/${encodeURIComponent(dreamId)}/actions/apply`, applier ? { mode: "actions", actionIds, applier } : { mode: "actions", actionIds }, ); } export async function approveDreamPlan( memoryStoreName: string, dreamId: string, approver: string, ): Promise<{ memoryStoreName: string; dreamId: string; status: string; approvedAt?: string; executionExpiresAt?: string; }> { return apiPost( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}/dream-tasks/${encodeURIComponent(dreamId)}/actions/apply`, { mode: "plan", approver }, ); } // --------------------------------------------------------------------------- // dream-kb-sync(Phase 4) // --------------------------------------------------------------------------- /** 会话内沉淀:把某个 dream 抽取任务(dreamId)的产出落到目标知识库。 */ export async function depositDreamToKb( memoryStoreName: string, body: { dreamId: string; knowledgeBaseName: string; kinds?: Array<"skill" | "profile">; }, ): Promise { return apiPost( `/api/v1/memory/stores/${encodeURIComponent(memoryStoreName)}/dream-kb-sync`, body, ); }