import { ForbiddenException, Injectable, Logger } from '@nestjs/common'; import { Cron, CronExpression } from '@nestjs/schedule'; import { FreelanceProfile, Prisma, VeilleSignal } from '@prisma/client'; import { OpenRouterService } from '../llm/openrouter.service'; import { PrismaService } from '../prisma/prisma.service'; import { SessionsService } from '../sessions/sessions.service'; import { VeilleSignalActionResultDto } from './dto/veille-signal-action-result.dto'; import { VeilleSignalResponseDto } from './dto/veille-signal-response.dto'; import { buildVeilleScanPrompt } from './veille.prompt'; export interface VeilleSignalSource { title: string; url: string; } interface RawVeilleSignal { type?: unknown; competence?: unknown; relevance_score?: unknown; sources?: unknown; } const MIN_SOURCES = 3; const DEFAULT_RELEVANCE_THRESHOLD = 0.7; const DEDUP_WINDOW_DAYS = 30; const SNOOZE_DAYS = 14; const SNOOZE_PREFIX = 'snoozed_until:'; const WEEKLY_STALENESS_DAYS = 7; const TYPE_PRIORITY: Record = { obsolete: 0, refresh: 1, emerging: 2, }; /** Domaines qui evoluent vite : veille quotidienne plutot qu'hebdomadaire, sauf si le freelance a * explicitement choisi une frequence (profile.veilleFrequency). Liste volontairement simple - * un faux negatif se rattrape a la prochaine veille hebdomadaire, pas de consequence grave. */ const VOLATILE_DOMAIN_KEYWORDS = [ 'ia', 'intelligence artificielle', 'ai', 'llm', 'genai', 'ia generative', 'web3', 'blockchain', 'no-code', 'low-code', ]; /** * Agent de veille (docs/Max Refonte Coach Freelance.md, "veille autonome") : tourne en tache de * fond (cron), jamais a la demande de l'utilisateur. Propose des signaux (competence emergente, a * rafraichir, ou obsolete) que le freelance traite explicitement (train/snooze/dismiss) - ne * modifie jamais le profil ou ne demarre jamais de session de son propre chef. */ @Injectable() export class VeilleService { private readonly logger = new Logger(VeilleService.name); constructor( private readonly prisma: PrismaService, private readonly llm: OpenRouterService, private readonly sessionsService: SessionsService, ) {} /** Un seul cron quotidien : la distinction quotidien/hebdomadaire se fait par profil (voir * isDueToday), pas par decorateur separe - plus simple a tester et a faire evoluer. */ @Cron(CronExpression.EVERY_DAY_AT_6AM) async runDailyTick(): Promise { const profiles = await this.prisma.freelanceProfile.findMany({ where: { veilleNotificationsEnabled: true }, }); for (const profile of profiles) { if (!this.isDueToday(profile)) continue; try { await this.runCycleForProfile(profile); } catch (error) { this.logger.warn( `Veille du profil ${profile.id} echouee: ${String(error)}`, ); } } } isDueToday(profile: FreelanceProfile): boolean { const frequency = profile.veilleFrequency ?? this.inferFrequency(profile); if (frequency === 'daily') return true; if (!profile.lastVeilleAt) return true; const daysSinceLastRun = (Date.now() - profile.lastVeilleAt.getTime()) / (1000 * 60 * 60 * 24); return daysSinceLastRun >= WEEKLY_STALENESS_DAYS; } private inferFrequency(profile: FreelanceProfile): 'daily' | 'weekly' { const domains = (profile.domains as unknown as string[]) ?? []; const isVolatile = domains.some((domain) => VOLATILE_DOMAIN_KEYWORDS.some((keyword) => domain.toLowerCase().includes(keyword), ), ); return isVolatile ? 'daily' : 'weekly'; } async runCycleForProfile(profile: FreelanceProfile): Promise { const domains = (profile.domains as unknown as string[]) ?? []; const extraTopics = (profile.veilleExtraTopics as unknown as string[]) ?? []; const topics = [...new Set([...domains, ...extraTopics])]; if (topics.length === 0) { await this.prisma.freelanceProfile.update({ where: { id: profile.id }, data: { lastVeilleAt: new Date() }, }); return; } const blacklist = new Set( ((profile.veilleBlacklist as unknown as string[]) ?? []).map((c) => c.toLowerCase(), ), ); const threshold = Math.max( DEFAULT_RELEVANCE_THRESHOLD, profile.veilleRelevanceThreshold ?? 0, ); const outcomes = await Promise.all( topics.map((topic) => this.scanTopic(profile.userId, topic)), ); const candidates = outcomes.flat(); for (const candidate of candidates) { if (candidate.sources.length < MIN_SOURCES) continue; if (candidate.relevanceScore < threshold) continue; if (blacklist.has(candidate.competence.toLowerCase())) continue; if ( await this.isDuplicate(profile.id, candidate.competence, candidate.type) ) { continue; } await this.prisma.veilleSignal.create({ data: { freelanceProfileId: profile.id, type: candidate.type, competence: candidate.competence, sources: candidate.sources as unknown as Prisma.InputJsonValue, relevanceScore: candidate.relevanceScore, }, }); } await this.prisma.freelanceProfile.update({ where: { id: profile.id }, data: { lastVeilleAt: new Date() }, }); } private async isDuplicate( freelanceProfileId: number, competence: string, type: string, ): Promise { const since = new Date(); since.setDate(since.getDate() - DEDUP_WINDOW_DAYS); const existing = await this.prisma.veilleSignal.findFirst({ where: { freelanceProfileId, competence, type, createdAt: { gte: since }, }, }); return existing !== null; } private async scanTopic( userId: number, topic: string, ): Promise< { type: string; competence: string; relevanceScore: number; sources: VeilleSignalSource[]; }[] > { try { const raw = await this.llm.chat( userId, [{ role: 'system', content: buildVeilleScanPrompt(topic) }], { jsonResponse: true, online: true }, ); return this.parseSignals(raw); } catch (error) { this.logger.warn(`Veille du sujet "${topic}" echouee: ${String(error)}`); return []; } } private parseSignals(raw: string): { type: string; competence: string; relevanceScore: number; sources: VeilleSignalSource[]; }[] { try { const data = JSON.parse(raw) as { signals?: unknown }; if (!Array.isArray(data.signals)) return []; const results: { type: string; competence: string; relevanceScore: number; sources: VeilleSignalSource[]; }[] = []; for (const rawSignal of data.signals as RawVeilleSignal[]) { if ( !['emerging', 'refresh', 'obsolete'].includes( String(rawSignal.type), ) || typeof rawSignal.competence !== 'string' || !Array.isArray(rawSignal.sources) ) { continue; } const sources: VeilleSignalSource[] = []; for (const rawSource of rawSignal.sources as { title?: unknown; url?: unknown; }[]) { if ( typeof rawSource.title === 'string' && typeof rawSource.url === 'string' ) { sources.push({ title: rawSource.title, url: rawSource.url }); } } results.push({ type: rawSignal.type as string, competence: rawSignal.competence, relevanceScore: Number(rawSignal.relevance_score) || 0, sources, }); } return results; } catch { this.logger.warn(`Reponse de veille non-JSON, rejetee: ${raw}`); return []; } } async getActiveSignals(userId: number): Promise { const profile = await this.prisma.freelanceProfile.findUnique({ where: { userId }, }); if (!profile) return []; const signals = await this.prisma.veilleSignal.findMany({ where: { freelanceProfileId: profile.id }, orderBy: { createdAt: 'desc' }, }); return signals .filter((signal) => this.isActionable(signal)) .sort( (a, b) => TYPE_PRIORITY[a.type] - TYPE_PRIORITY[b.type] || b.relevanceScore - a.relevanceScore, ) .map((signal) => this.toResponse(signal)); } /** Un signal sans action est actionnable. Un signal "snooze" le redevient automatiquement une * fois sa date de resurgence passee (voir SNOOZE_PREFIX) - pas de colonne dediee en base. */ private isActionable(signal: VeilleSignal): boolean { if (!signal.actionTaken) return true; if (signal.actionTaken.startsWith(SNOOZE_PREFIX)) { const resurfaceAt = new Date( signal.actionTaken.slice(SNOOZE_PREFIX.length), ); return resurfaceAt.getTime() <= Date.now(); } return false; } async applyAction( signalId: number, userId: number, action: 'train' | 'snooze' | 'dismiss', ): Promise { const signal = await this.prisma.veilleSignal.findUnique({ where: { id: signalId }, include: { freelanceProfile: true }, }); if (!signal || signal.freelanceProfile.userId !== userId) { throw new ForbiddenException('Signal de veille introuvable.'); } if (action === 'snooze') { const resurfaceAt = new Date(); resurfaceAt.setDate(resurfaceAt.getDate() + SNOOZE_DAYS); await this.prisma.veilleSignal.update({ where: { id: signalId }, data: { actionTaken: `${SNOOZE_PREFIX}${resurfaceAt.toISOString()}` }, }); return { actionTaken: 'snoozed' }; } if (action === 'dismiss') { await this.prisma.veilleSignal.update({ where: { id: signalId }, data: { actionTaken: 'dismissed' }, }); const dismissed = new Set( (signal.freelanceProfile.competencesDismissed as unknown as string[]) ?? [], ); dismissed.add(signal.competence); await this.prisma.freelanceProfile.update({ where: { id: signal.freelanceProfile.id }, data: { competencesDismissed: [...dismissed], }, }); return { actionTaken: 'dismissed' }; } await this.prisma.veilleSignal.update({ where: { id: signalId }, data: { actionTaken: 'trained' }, }); const session = await this.sessionsService.create(userId); await this.sessionsService.sendObjectiveMessage( session.id, userId, `Je veux me former sur ${signal.competence}.`, ); return { actionTaken: 'trained', sessionId: session.id }; } private toResponse(signal: VeilleSignal): VeilleSignalResponseDto { return { id: signal.id, type: signal.type, competence: signal.competence, sources: signal.sources as unknown as VeilleSignalSource[], relevanceScore: signal.relevanceScore, actionTaken: signal.actionTaken, createdAt: signal.createdAt, }; } }