import { ConflictException, Injectable, NotFoundException, } from '@nestjs/common'; import { Session, SessionCurriculum, SessionObjective } from '@prisma/client'; import { OpenRouterService } from '../llm/openrouter.service'; import { PrismaService } from '../prisma/prisma.service'; import { EvaluationAgent } from './agents/evaluation.agent'; import { IntentRouterAgent } from './agents/intent-router.agent'; import { LevelAgent, StoredLevelAssessment } from './agents/level.agent'; import { MappingAgent } from './agents/mapping.agent'; import { ModuleAgent } from './agents/module.agent'; import { ObjectiveAgent, ObjectiveTurnResult } from './agents/objective.agent'; import { PlanAgent } from './agents/plan.agent'; import { ResearchAgent } from './agents/research.agent'; import { CurriculumResponseDto } from './dto/curriculum-response.dto'; import { DebugCorrectionDto } from './dto/debug-correction.dto'; import { EvaluationResultResponseDto } from './dto/evaluation-result-response.dto'; import { ExerciseAnswerDto } from './dto/exercise-answer.dto'; import { FeynmanFeedbackResponseDto } from './dto/feynman-feedback-response.dto'; import { FeynmanSubmissionDto } from './dto/feynman-submission.dto'; import { HintRequestDto } from './dto/hint-request.dto'; import { HintResponseDto } from './dto/hint-response.dto'; import { JudgeResultResponseDto } from './dto/judge-result-response.dto'; import { LevelDisputeDto } from './dto/level-dispute.dto'; import { LevelProfileResponseDto } from './dto/level-profile-response.dto'; import { ModuleCompleteResponseDto } from './dto/module-complete-response.dto'; import { ModuleStateResponseDto } from './dto/module-content-response.dto'; import { RouteMessageResponseDto } from './dto/route-message-response.dto'; import { buildAgentPrompt, PERSONALITY_PROMPT } from './prompts/base.prompt'; import { SessionObjectiveResponseDto } from './dto/session-objective-response.dto'; import { SessionResponseDto } from './dto/session-response.dto'; import { PublicModuleContent, StoredModuleContent, } from './agents/module.agent'; type SessionWithObjective = Session & { objective: SessionObjective | null }; // "researching" est gere entierement cote code par confirmLevel() (declenche l'Agent 4 puis // l'Agent 5 et avance directement a "planning") - il ne passe jamais par routeIncomingMessage(), // donc il n'a pas besoin de figurer ici. "planning" (en attente de confirmation du curriculum) et // "evaluating" (Agent 7, conversationnel) sont geres ici. "teaching" n'est PAS un dispatch // conversationnel libre (voir routeTeachingMessage()) : un message libre y est interprete via // "currentAwaiting" plutot que classifie par un agent, donc il figure aussi dans ce Set mais est // traite a part dans routeIncomingMessage(). const IMPLEMENTED_STATUSES = new Set([ 'objective_discovery', 'level_assessment', 'planning', 'teaching', 'evaluating', ]); @Injectable() export class SessionsService { constructor( private readonly prisma: PrismaService, private readonly objectiveAgent: ObjectiveAgent, private readonly mappingAgent: MappingAgent, private readonly levelAgent: LevelAgent, private readonly researchAgent: ResearchAgent, private readonly planAgent: PlanAgent, private readonly moduleAgent: ModuleAgent, private readonly evaluationAgent: EvaluationAgent, private readonly intentRouter: IntentRouterAgent, private readonly llm: OpenRouterService, ) {} async create(userId: number): Promise { const session = await this.prisma.session.create({ data: { userId } }); return this.toResponse({ ...session, objective: null }); } async findOne(id: number, userId: number): Promise { const session = await this.findOwnedSession(id, userId); return this.toResponse(session); } async sendObjectiveMessage( sessionId: number, userId: number, message: string, ): Promise { const session = await this.findOwnedSession(sessionId, userId); this.assertObjectiveDiscoveryInProgress(session); return this.objectiveAgent.converse(sessionId, userId, message); } /** * Confirme l'objectif (Agent 1) puis enchaine automatiquement, dans le meme appel : Agent 2 * (Cartographie, aucun tour utilisateur), puis demarre Agent 3 (Niveau) pour obtenir sa * premiere question. Par le moment ou cette methode repond, session.status vaut deja * "level_assessment" (voir SessionStatus, docs/Max_System_Prompt.md table des declencheurs). * Si l'Agent 2 ou l'Agent 3 echoue, l'exception remonte telle quelle : l'objectif reste * confirme (status="objective_validated") et reappeler cet endpoint relance la chaine de * maniere idempotente (mappingAgent.runForSession() ne refait rien si la carte existe deja). */ async confirmObjective( sessionId: number, userId: number, ): Promise { const session = await this.findOwnedSession(sessionId, userId); this.assertObjectiveDiscoveryInProgress(session); const objective = await this.objectiveAgent.confirm(sessionId, userId); const objectiveSummary = `${objective.subject} pour ${objective.professionalGoal}, en ${objective.duration}`; await this.prisma.session.update({ where: { id: sessionId }, data: { status: 'mapping' }, }); await this.mappingAgent.runForSession(sessionId, userId, objectiveSummary); await this.prisma.session.update({ where: { id: sessionId }, data: { status: 'level_assessment' }, }); const conceptMap = await this.prisma.sessionConceptMap.findUniqueOrThrow({ where: { sessionId }, }); const conceptMapSummary = this.summarizeConceptMap( conceptMap.concepts as unknown as { name: string }[], ); const firstTurn = await this.levelAgent.start( sessionId, userId, objectiveSummary, conceptMapSummary, ); return { id: objective.id, sessionId: objective.sessionId, subject: objective.subject, professionalGoal: objective.professionalGoal, duration: objective.duration, validatedAt: objective.validatedAt ?? new Date(), nextPrompt: firstTurn.reply, }; } /** * Agent 4 (Recherche Approfondie) puis Agent 5 (Plan), une fois le profil de niveau confirme * par l'utilisateur (pas de contestation, ou contestation resolue) - voir docs/Max Refonte * Coach Freelance.md, "Avant de passer a l'Agent 4, Max presente un resume du profil de niveau * a l'utilisateur". Enchaine jusqu'au curriculum inclus (aucun tour utilisateur requis entre * les deux, "Max ne parle pas pendant les phases de traitement") : par le moment ou cette * methode repond, session.status vaut "planning" ET le curriculum est deja stocke, pret pour * CurriculumCard - seule la confirmation finale ("Demarrer la formation") attend l'utilisateur. */ async confirmLevel( sessionId: number, userId: number, ): Promise { const session = await this.findOwnedSession(sessionId, userId); if (session.status !== 'level_assessment') { throw new ConflictException( "Cette session n'est plus a l'etape d'evaluation de niveau.", ); } await this.levelAgent.confirm(sessionId); await this.researchAgent.runForSession(sessionId, userId); await this.prisma.session.update({ where: { id: sessionId }, data: { status: 'planning' }, }); await this.planAgent.runForSession(sessionId, userId); const curriculum = await this.prisma.sessionCurriculum.findUniqueOrThrow({ where: { sessionId }, }); return this.toCurriculumResponse(curriculum); } /** * Confirmation explicite du curriculum (CurriculumCard, "Demarrer la formation") - immuable * une fois validatedAt renseigne, meme principe que l'objectif (Agent 1). Enchaine * immediatement la generation du module 1 (Agent 6) : lire ce module EST le prochain moment * utilisateur reel, donc on s'arrete la plutot que d'attendre un message. */ async confirmCurriculum( sessionId: number, userId: number, ): Promise { const session = await this.findOwnedSession(sessionId, userId); if (session.status !== 'planning') { throw new ConflictException( "Cette session n'est plus a l'etape de planification.", ); } const curriculum = await this.prisma.sessionCurriculum.findUnique({ where: { sessionId }, }); if (!curriculum) { throw new ConflictException( 'Aucun curriculum pret a confirmer pour cette session.', ); } if (curriculum.validatedAt) { throw new ConflictException('Ce curriculum est deja confirme.'); } await this.prisma.sessionCurriculum.update({ where: { sessionId }, data: { validatedAt: new Date() }, }); await this.prisma.session.update({ where: { id: sessionId }, data: { status: 'teaching' }, }); const content = await this.moduleAgent.generateModule(sessionId, userId, 1); return this.toModuleStateResponse(1, content); } async submitExerciseAnswer( sessionId: number, userId: number, dto: ExerciseAnswerDto, ): Promise { const moduleIndex = await this.assertTeachingInProgress(sessionId, userId); return this.moduleAgent.submitExerciseAnswer( sessionId, userId, moduleIndex, dto.exerciseId, dto.answer, ); } async requestHint( sessionId: number, userId: number, dto: HintRequestDto, ): Promise { const moduleIndex = await this.assertTeachingInProgress(sessionId, userId); return this.moduleAgent.requestHint(sessionId, moduleIndex, dto.exerciseId); } async submitDebugCorrection( sessionId: number, userId: number, dto: DebugCorrectionDto, ): Promise { const moduleIndex = await this.assertTeachingInProgress(sessionId, userId); return this.moduleAgent.submitDebugCorrection( sessionId, userId, moduleIndex, dto.correction, ); } async submitFeynmanExplanation( sessionId: number, userId: number, dto: FeynmanSubmissionDto, ): Promise { const moduleIndex = await this.assertTeachingInProgress(sessionId, userId); return this.moduleAgent.submitFeynmanExplanation( sessionId, userId, moduleIndex, dto.explanation, ); } async completeModule( sessionId: number, userId: number, ): Promise { const moduleIndex = await this.assertTeachingInProgress(sessionId, userId); return this.moduleAgent.completeModule( sessionId, userId, moduleIndex, (sid, uid) => this.startEvaluation(sid, uid), ); } async getEvaluationResult( sessionId: number, userId: number, ): Promise { await this.findOwnedSession(sessionId, userId); const record = await this.prisma.sessionEvaluation.findUnique({ where: { sessionId }, }); if (!record || !record.completedAt) { throw new NotFoundException( 'Aucun resultat d-evaluation disponible pour cette session.', ); } const feedback = record.feedback as unknown as { interview: { feedback: string; remedialModules: number[] }; mission?: { feedback: string }; }; return { validated: record.validated, interviewScore: record.interviewScore ?? 0, interviewFeedback: [feedback.interview.feedback], practicalScore: record.practicalScore ?? 0, practicalFeedback: feedback.mission ? [feedback.mission.feedback] : [], strengths: [], remainingGaps: feedback.interview.remedialModules.map(String), }; } private async startEvaluation( sessionId: number, userId: number, ): Promise { await this.evaluationAgent.start(sessionId, userId); } private async assertTeachingInProgress( sessionId: number, userId: number, ): Promise { const session = await this.findOwnedSession(sessionId, userId); if (session.status !== 'teaching') { throw new ConflictException( "Cette session n'est pas a l'etape de redaction/exercices.", ); } const current = await this.prisma.sessionModule.findFirst({ where: { sessionId, status: { not: 'completed' } }, orderBy: { moduleIndex: 'desc' }, }); if (!current) { throw new ConflictException('Aucun module en cours pour cette session.'); } return current.moduleIndex; } async disputeLevel( sessionId: number, userId: number, dto: LevelDisputeDto, ): Promise { const session = await this.findOwnedSession(sessionId, userId); if (session.status !== 'level_assessment') { throw new ConflictException( "Cette session n'est plus a l'etape d'evaluation de niveau.", ); } const updated = await this.levelAgent.dispute( sessionId, userId, dto.concept, dto.answer, ); return this.toLevelProfileResponse(updated); } /** * Porte d'entree unique du chat (docs/Max_System_Prompt.md) : route vers l'agent de la session * active si elle existe, sinon classifie le message (routeur d'intention) pour decider de * demarrer une formation ou de repondre simplement en conversation. Le statut de session n'est * jamais choisi par le LLM : seul le code decide ici de creer une session ou non. */ async routeIncomingMessage( userId: number, message: string, ): Promise { const activeSession = await this.prisma.session.findFirst({ where: { userId, status: { not: 'completed' } }, orderBy: { createdAt: 'desc' }, }); if (activeSession) { if (!IMPLEMENTED_STATUSES.has(activeSession.status)) { throw new ConflictException( "Cette etape du pipeline n'est pas encore implementee.", ); } if (activeSession.status === 'level_assessment') { const turn = await this.levelAgent.converse( activeSession.id, userId, message, ); return { type: 'learn', sessionId: activeSession.id, reply: turn.reply, levelDone: turn.done, levelProfile: turn.profile, }; } if (activeSession.status === 'planning') { // Reponse figee cote code (pas d'appel LLM) : le curriculum est deja pret des la fin de // confirmLevel(), il ne manque que la confirmation explicite (CurriculumCard, "Demarrer // la formation"). Evite un 409 deroutant si l'utilisateur dit quelque chose en attendant. return { type: 'learn', sessionId: activeSession.id, reply: 'Ton plan de formation est pret. Confirme-le pour commencer la redaction du premier module.', }; } if (activeSession.status === 'teaching') { return this.routeTeachingMessage(activeSession.id, userId, message); } if (activeSession.status === 'evaluating') { const turn = await this.evaluationAgent.converse( activeSession.id, userId, message, ); return { type: 'learn', sessionId: activeSession.id, reply: turn.reply, evaluationStage: turn.stage, evaluationDone: turn.done, }; } const result = await this.sendObjectiveMessage( activeSession.id, userId, message, ); return { type: 'learn', sessionId: activeSession.id, reply: result.reply, ready: result.ready, draft: result.draft, }; } const intent = await this.intentRouter.analyze(userId, message); if (intent.intent === 'chat') { const reply = await this.llm.chat(userId, [ { role: 'system', content: buildAgentPrompt(PERSONALITY_PROMPT) }, { role: 'user', content: message }, ]); return { type: 'chat', reply }; } const session = await this.prisma.session.create({ data: { userId } }); const result = await this.objectiveAgent.converse( session.id, userId, message, ); return { type: 'learn', sessionId: session.id, reply: result.reply, ready: result.ready, draft: result.draft, }; } private async findOwnedSession( id: number, userId: number, ): Promise { const session = await this.prisma.session.findUnique({ where: { id }, include: { objective: true }, }); if (!session || session.userId !== userId) { throw new NotFoundException(`Session ${id} introuvable`); } return session; } private assertObjectiveDiscoveryInProgress( session: SessionWithObjective, ): void { if (session.status !== 'objective_discovery') { throw new ConflictException( "L'objectif de cette session est deja valide ou cette session n'en est plus a cette etape.", ); } } private summarizeConceptMap(concepts: { name: string }[]): string { return concepts.map((c) => c.name).join(', '); } private toLevelProfileResponse( record: StoredLevelAssessment, ): LevelProfileResponseDto { return { id: record.id, sessionId: record.sessionId, mastered: record.masteredConcepts as string[], gaps: record.gapConcepts as { concept: string; description: string; }[], unknown: record.unknownConcepts as string[], overallLevel: record.overallLevel as 'beginner' | 'intermediate' | 'advanced', completedAt: record.completedAt ?? undefined, }; } /** * Route un message libre (voix ou texte) vers la sous-action attendue par le module en cours, * a partir de "currentAwaiting" (jamais une classification par le LLM) : repond a l'exercice * attendu, a la correction de debogage, ou a l'explication Feynman. Une demande d'indice est * detectee par un motif simple ("indice"/"aide"/"hint"), uniquement quand un exercice est * attendu (le debogage/Feynman n'ont pas d'echelle d'indices). Apres toute sous-action, * verifie immediatement si le module est complet pour enchainer (module suivant ou Agent 7) * sans attendre une action separee de l'utilisateur. */ private async routeTeachingMessage( sessionId: number, userId: number, message: string, ): Promise { const moduleIndex = await this.assertTeachingInProgress(sessionId, userId); const record = await this.prisma.sessionModule.findUniqueOrThrow({ where: { sessionId_moduleIndex: { sessionId, moduleIndex } }, }); const content = record.content as unknown as StoredModuleContent; const awaiting = content.progress.currentAwaiting; let reply: string; if (!awaiting) { reply = 'Ce module est deja termine.'; } else if ( awaiting.type === 'exercise' && /\b(indice|aide|hint)\b/i.test(message) ) { const hint = await this.moduleAgent.requestHint( sessionId, moduleIndex, awaiting.exerciseId, ); reply = hint.hint ?? 'Tu as deja utilise les 5 indices disponibles pour cet exercice.'; } else if (awaiting.type === 'exercise') { const judged = await this.moduleAgent.submitExerciseAnswer( sessionId, userId, moduleIndex, awaiting.exerciseId, message, ); reply = judged.feedback; } else if (awaiting.type === 'debug') { const judged = await this.moduleAgent.submitDebugCorrection( sessionId, userId, moduleIndex, message, ); reply = judged.feedback; } else { const feynman = await this.moduleAgent.submitFeynmanExplanation( sessionId, userId, moduleIndex, message, ); reply = feynman.validated ? `Explication validee. ${feynman.strengths.join(' ')}` : `Pas tout a fait. ${feynman.gaps.join(' ')}`; } const completion = await this.moduleAgent.completeModule( sessionId, userId, moduleIndex, (sid, uid) => this.startEvaluation(sid, uid), ); if (completion.completed && completion.nextModuleIndex) { reply += ` Module suivant debloque : module ${completion.nextModuleIndex}.`; } else if (completion.completed && completion.evaluationStarted) { reply += ' Tous les modules sont termines. Place a l-evaluation finale.'; } return { type: 'learn', sessionId, reply, moduleComplete: completion, }; } private toCurriculumResponse( curriculum: SessionCurriculum, ): CurriculumResponseDto { return { modules: curriculum.modules as unknown as CurriculumResponseDto['modules'], totalDuration: curriculum.totalDuration, validatedAt: curriculum.validatedAt ?? undefined, }; } private toModuleStateResponse( moduleIndex: number, content: PublicModuleContent, ): ModuleStateResponseDto { return { moduleIndex, title: content.title, hook: content.hook, theory: content.theory, weDo: content.weDo, exercises: content.exercises, debugExercise: content.debugExercise, synthesis: content.synthesis, awaiting: content.progress.currentAwaiting, }; } private toResponse(session: SessionWithObjective): SessionResponseDto { return { id: session.id, status: session.status, createdAt: session.createdAt, updatedAt: session.updatedAt, objective: session.objective ? { id: session.objective.id, sessionId: session.objective.sessionId, subject: session.objective.subject, professionalGoal: session.objective.professionalGoal, duration: session.objective.duration, validatedAt: session.objective.validatedAt ?? session.objective.createdAt, } : undefined, }; } }