import type { QueryClient } from '@tanstack/react-query'; import type { SuperagentAgent } from '../types'; export const AGENT_LIST_STALE_TIME_MS = 5 * 60 * 1000; export const AGENT_LIST_GC_TIME_MS = 30 * 60 * 1000; type AgentListScope = { baseUrl: string; cacheScope: string; userId: string; }; const normalizeBaseUrl = (baseUrl: string) => baseUrl.replace(/\/+$/, ''); export const superagentQueryKeys = { all: ['superagent-native'] as const, agents: ({ baseUrl, cacheScope, userId }: AgentListScope) => [ ...superagentQueryKeys.all, 'agents', normalizeBaseUrl(baseUrl), userId, cacheScope, ] as const, }; export type AgentListQueryKey = ReturnType; export const createAgentListQueryOptions = ({ enabled, listAgents, queryKey, }: { enabled?: boolean; listAgents: () => Promise; queryKey: AgentListQueryKey; }) => ({ enabled, gcTime: AGENT_LIST_GC_TIME_MS, queryFn: listAgents, queryKey, retry: false, staleTime: AGENT_LIST_STALE_TIME_MS, }); export const prependCachedAgent = ({ agent, queryClient, queryKey, }: { agent: SuperagentAgent; queryClient: QueryClient; queryKey: AgentListQueryKey; }) => { queryClient.setQueryData(queryKey, (current = []) => [ agent, ...current.filter((item) => item.id !== agent.id), ]); }; export const mergeCachedAgent = ({ agent, queryClient, queryKey, }: { agent: SuperagentAgent; queryClient: QueryClient; queryKey: AgentListQueryKey; }) => { queryClient.setQueryData(queryKey, (current = []) => { const hasAgent = current.some((item) => item.id === agent.id); return hasAgent ? current.map((item) => (item.id === agent.id ? { ...item, ...agent } : item)) : [agent, ...current]; }); }; export const removeCachedAgent = ({ agentId, queryClient, queryKey, }: { agentId: string; queryClient: QueryClient; queryKey: AgentListQueryKey; }) => { queryClient.setQueryData(queryKey, (current = []) => ( current.filter((item) => item.id !== agentId) )); };