import type { MemoryScope, ScopeDirectoryFilter } from "@/types/memory"; export const MEMORY_RANGE_FIELDS = [ "appId", "tenantId", "agentId", "runId", ] as const; /** The browser range is a set of independent filters, not an API Scope path. */ export function normalizeMemoryRange(range: MemoryScope): MemoryScope | null { if (!range.appId.trim()) return null; return { appId: range.appId.trim(), tenantId: range.tenantId?.trim() || "*", agentId: range.agentId?.trim() || "*", runId: range.runId?.trim() || "*", }; } /** Keep the API's concrete prefix and express selections after a wildcard as Filter. */ export function buildMemoryRangeQuery(range: MemoryScope): { scope: MemoryScope; filter?: ScopeDirectoryFilter; } { const normalized = normalizeMemoryRange(range) ?? range; const scope = { ...normalized }; const conditions: ScopeDirectoryFilter[] = []; let wildcardSeen = false; for (const field of MEMORY_RANGE_FIELDS) { const value = normalized[field]; if (value === "*") wildcardSeen = true; if (wildcardSeen) { scope[field] = "*"; if (value && value !== "*") conditions.push({ op: "eq", field, value }); } } return { scope, ...(conditions.length ? { filter: conditions.length === 1 ? conditions[0] : ({ op: "and", conditions } as ScopeDirectoryFilter), } : {}), }; } export function hasIndependentMemoryRange(range: MemoryScope): boolean { return buildMemoryRangeQuery(range).filter !== undefined; } /** A wildcard ancestor does not restrict the choices at a later level. */ export function memoryRangeOptions( scopes: readonly MemoryScope[], range: MemoryScope, field: keyof MemoryScope, ): string[] { const ancestors = MEMORY_RANGE_FIELDS.slice( 0, MEMORY_RANGE_FIELDS.indexOf(field), ); const values = new Set(); for (const scope of scopes) { const matches = ancestors.every( (ancestor) => !range[ancestor] || range[ancestor] === "*" || scope[ancestor] === range[ancestor], ); const value = scope[field]; if (matches && value && value !== "*") values.add(value); } return [...values].sort((left, right) => left.localeCompare(right)); } /** These list APIs accept hierarchical Scope only and have no Filter parameter. */ export function requiresHierarchicalMemoryRange(segment: string): boolean { return ["tasks", "requests", "dream"].includes(segment); }