Files
Momento/memento-note/app/api/cron/agents/route.ts
Antigravity 5821e2c96f
Some checks failed
CI / Lint, Unit Tests & Build (push) Failing after 1m8s
CI / Deploy production (on server) (push) Has been skipped
fix(audit): sécurité + perf + DB — 40 problèmes adressés
SÉCURITÉ (CRITIQUE):
- link-preview: auth() obligatoire + filtre IP privées (SSRF fix)
- metrics: !metricsToken → 401 au lieu d'etre ouvert si token absent
- contextual-ai-chat: DOMPurify.sanitize() sur dangerouslySetInnerHTML (XSS fix)

PERFORMANCE:
- graph/route.ts: take:500 + orderBy updatedAt desc (pas de full table scan)
- syncAllEmbeddings: batch parallèle Promise.allSettled × 5 (pas séquentiel)
- 80 console.log supprimés du code production

BASE DE DONNÉES:
- Note: index contentUpdatedAt + isPublic ajoutés au schema
- DocumentChunk: commentaire index vectoriel HNSW (à exécuter manuellement)
2026-07-05 08:51:21 +00:00

107 lines
3.1 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { calculateNextRun } from '@/lib/agents/schedule'
export const dynamic = 'force-dynamic'
/**
* POST /api/cron/agents
*
* Finds all enabled, non-manual agents whose nextRun <= now,
* executes them, and schedules the next run.
*
* Optional auth: set CRON_SECRET env var, callers must pass
* Authorization: Bearer <CRON_SECRET>
*/
export async function POST(request: NextRequest) {
const cronSecret = process.env.CRON_SECRET
if (!cronSecret) {
console.error('[CronAgents] CRON_SECRET env var is required but not set')
return NextResponse.json({ error: 'Server misconfiguration' }, { status: 500 })
}
const authHeader = request.headers.get('authorization')
if (authHeader !== `Bearer ${cronSecret}`) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
try {
const now = new Date()
const dueAgents = await prisma.agent.findMany({
where: {
isEnabled: true,
frequency: { not: 'manual' },
nextRun: { lte: now },
},
select: {
id: true,
userId: true,
frequency: true,
scheduledTime: true,
scheduledDay: true,
timezone: true,
},
})
if (dueAgents.length === 0) {
return NextResponse.json({ success: true, executed: 0 })
}
const results: { id: string; success: boolean; error?: string }[] = []
// Execute agents sequentially (max 3 per cycle)
for (const agent of dueAgents.slice(0, 3)) {
try {
const { executeAgent } = await import('@/lib/ai/services/agent-executor.service')
const result = await executeAgent(agent.id, agent.userId)
// Calculate and set next run
const nextRun = calculateNextRun({
frequency: agent.frequency,
scheduledTime: agent.scheduledTime,
scheduledDay: agent.scheduledDay,
timezone: agent.timezone,
})
await prisma.agent.update({
where: { id: agent.id },
data: { nextRun },
})
results.push({ id: agent.id, success: result.success, error: result.error })
} catch (error) {
const msg = error instanceof Error ? error.message : 'Unknown error'
console.error(`[CronAgents] Agent ${agent.id} failed:`, msg)
// Still schedule next run even on failure
const nextRun = calculateNextRun({
frequency: agent.frequency,
scheduledTime: agent.scheduledTime,
scheduledDay: agent.scheduledDay,
timezone: agent.timezone,
})
await prisma.agent.update({
where: { id: agent.id },
data: { nextRun },
})
results.push({ id: agent.id, success: false, error: msg })
}
}
return NextResponse.json({
success: true,
executed: results.length,
results,
})
} catch (error) {
console.error('[CronAgents] Error:', error)
return NextResponse.json(
{ success: false, error: 'Internal Server Error' },
{ status: 500 }
)
}
}