import BaseAgentService from '../BaseAgentService'; import type { ServiceError } from '../serviceUtils'; import type { IAgentCard, IAgentConfigUpdate, IAgentDecision, IAgentProposals, IAgentsOverview, } from './agents.interface'; import { AGENTS_ROUTES } from './agents.routes'; export const SEO_MEDIC = 'seo_medic'; const failed = (answer: unknown): string | null => { const error = (answer ?? {}) as ServiceError & { error?: string }; if (typeof error.error === 'string' && error.error !== '') return error.error; if (typeof error.errors === 'string' && error.errors !== '') return error.errors; return null; }; /** * The agents of this merchant with their pending work, as the agent * reports them; the SEO medic's card is among them once the site is * connected. */ export const fetchAgentsOverview = async (): Promise => { const answer = await BaseAgentService.get(AGENTS_ROUTES.OVERVIEW); const reason = failed(answer); if (reason || !Array.isArray(answer?.agents)) { throw new Error(reason ?? 'The agents could not be read.'); } return answer as IAgentsOverview; }; /** Save an agent's settings and enabled state; the refreshed card comes back. */ export const updateAgentConfig = async ( kind: string, updates: IAgentConfigUpdate ): Promise => { const answer = await BaseAgentService.put( AGENTS_ROUTES.config(kind), updates ); const reason = failed(answer); if (reason || typeof answer?.kind !== 'string') { throw new Error(reason ?? 'The settings could not be saved.'); } return answer as IAgentCard; }; /** Dispatch one run of an agent now, outside its schedule. */ export const runAgentNow = async (kind: string): Promise => { const answer = await BaseAgentService.post(AGENTS_ROUTES.runNow(kind), {}); const reason = failed(answer); if (reason || !answer?.dispatched) { throw new Error(reason ?? 'The run could not be started.'); } }; /** The proposals of every agent, pending ones unless another status is asked for. */ export const fetchProposals = async ( status: 'pending' | 'applied' | 'rejected' = 'pending', limit = 50 ): Promise => { const answer = await BaseAgentService.get( `${AGENTS_ROUTES.PROPOSALS}?status=${status}&limit=${limit}` ); const reason = failed(answer); if (reason || !Array.isArray(answer?.proposals)) { throw new Error(reason ?? 'The proposals could not be read.'); } return answer as IAgentProposals; }; /** Approve (write to the site) or reject a batch of pending proposals. */ export const decideProposals = async ( proposalIds: string[], approve: boolean ): Promise => { const answer = await BaseAgentService.post( approve ? AGENTS_ROUTES.APPROVE : AGENTS_ROUTES.REJECT, { proposal_ids: proposalIds } ); const reason = failed(answer); if (reason) throw new Error(reason); return (answer ?? {}) as IAgentDecision; };