import type { MemoryScopeDirectoryEntry, ScopeDirectoryFilter, } from "@/types/memory"; import { buildScopeWorkspaceHref } from "@/lib/scope-workspace"; export type ScopeDirectoryTypeFilter = "all" | "conversation" | "wiki"; export type ScopeDirectoryMatchOp = "eq" | "prefix" | "wildcard"; export interface ScopeDirectoryFilterInput { scopeType: ScopeDirectoryTypeFilter; field?: string; op?: ScopeDirectoryMatchOp; value?: string; } /** React state boundary for opaque pagination tokens. Tokens must never * survive a Store or runtime data-scope transition. */ export function buildScopeDirectoryStateKey( dataScopeKey: string, memoryStoreName: string, ): string { return JSON.stringify([dataScopeKey, memoryStoreName]); } function isNonEmptyString(value: unknown): value is string { return typeof value === "string" && value.length > 0; } /** Only an exact four-part conversation Scope can open the point-lookup * workspace. Directory entries with omitted dimensions remain browseable but * must not be turned into a different Scope by filling synthetic sentinels. */ export function buildScopeDirectoryWorkspaceHref( memoryStoreName: string, entry: MemoryScopeDirectoryEntry, ): string | null { if ( entry.scopeType !== "conversation" || !isNonEmptyString(entry.appId) || !isNonEmptyString(entry.tenantId) || !isNonEmptyString(entry.agentId) || !isNonEmptyString(entry.runId) ) { return null; } return buildScopeWorkspaceHref(memoryStoreName, { appId: entry.appId, tenantId: entry.tenantId, agentId: entry.agentId, runId: entry.runId, }); } /** Build the small visual filter form into the server's full Filter AST. */ export function buildScopeDirectoryFilter( input: ScopeDirectoryFilterInput, ): ScopeDirectoryFilter { const conditions: ScopeDirectoryFilter[] = []; if (input.scopeType !== "all") { conditions.push({ op: "eq", field: "scopeType", value: input.scopeType, }); } const field = input.field?.trim(); const value = input.value?.trim(); if (field && value) { conditions.push({ op: input.op ?? "eq", field, value, }); } // A filter-only query is how callers request the whole heterogeneous // directory. Omitting both scope and filter would mean the legacy default // conversation scope instead. if (conditions.length === 0) { return { op: "exists", field: "scopeType" }; } return conditions.length === 1 ? conditions[0] : { op: "and", conditions }; } /** Legacy stores may reject a Filter AST with a generic 400. Scope-only * requests must never be classified this way because they sent no Filter. */ export function isScopeDirectoryUnsupported( error: unknown, usedFilter: boolean, ): boolean { if (!usedFilter || !(error instanceof Error)) return false; const code = "code" in error && typeof error.code === "string" ? error.code : ""; return ( code === "INVALID_PARAMETER" || error.message.toLowerCase().includes("invalid parameter") ); }