feat(sessions): wire Agents 2-4 into the pipeline orchestration

confirmObjective() now chains Agent 2 (mapping) then starts Agent 3
(level) synchronously after Agent 1 confirms - by the time the HTTP
response returns, session.status is already "level_assessment" and
the response carries Agent 3's first question in a new "nextPrompt"
field, to be spoken aloud (never displayed as text).

New endpoints: POST /sessions/:id/level/confirm (runs Agent 4, advances
to "planning") and POST /sessions/:id/level/dispute. routeIncomingMessage
dispatches "level_assessment" sessions to LevelAgent.converse(), same
single entry point used for text and voice.

RouteMessageResponseDto gains levelDone/levelProfile fields: every
response field is a structured, typed signal the frontend's main
process can branch on to decide whether to open a result window - never
an instruction embedded in the LLM's reply text.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
william
2026-11-02 09:48:10 +01:00
co-authored by Claude Sonnet 5
parent 5c00976e8f
commit 755bc07d18
10 changed files with 459 additions and 7 deletions
+129 -1
View File
@@ -7,7 +7,12 @@ import { Session, SessionObjective } from '@prisma/client';
import { OpenRouterService } from '../llm/openrouter.service';
import { PrismaService } from '../prisma/prisma.service';
import { IntentRouterAgent } from './agents/intent-router.agent';
import { LevelAgent, StoredLevelAssessment } from './agents/level.agent';
import { MappingAgent } from './agents/mapping.agent';
import { ObjectiveAgent, ObjectiveTurnResult } from './agents/objective.agent';
import { ResearchAgent } from './agents/research.agent';
import { LevelDisputeDto } from './dto/level-dispute.dto';
import { LevelProfileResponseDto } from './dto/level-profile-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';
@@ -15,13 +20,22 @@ import { SessionResponseDto } from './dto/session-response.dto';
type SessionWithObjective = Session & { objective: SessionObjective | null };
const IMPLEMENTED_STATUSES = new Set(['objective_discovery']);
// "researching" est gere entierement cote code par confirmLevel() (declenche l'Agent 4 puis
// avance directement a "planning") - il ne passe jamais par routeIncomingMessage(), donc il n'a
// pas besoin de figurer ici. "planning" et au-dela restent a implementer (prochain agent).
const IMPLEMENTED_STATUSES = new Set([
'objective_discovery',
'level_assessment',
]);
@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 intentRouter: IntentRouterAgent,
private readonly llm: OpenRouterService,
) {}
@@ -46,6 +60,15 @@ export class SessionsService {
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,
@@ -53,6 +76,31 @@ export class SessionsService {
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,
@@ -60,9 +108,51 @@ export class SessionsService {
professionalGoal: objective.professionalGoal,
duration: objective.duration,
validatedAt: objective.validatedAt ?? new Date(),
nextPrompt: firstTurn.reply,
};
}
/**
* Agent 4 (Recherche Approfondie), 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".
* Avance directement a "planning" (l'Agent 5, prochain a etre implemente, prendra le relai).
*/
async confirmLevel(sessionId: number, userId: number): Promise<void> {
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' },
});
}
async disputeLevel(
sessionId: number,
userId: number,
dto: LevelDisputeDto,
): Promise<LevelProfileResponseDto> {
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
@@ -84,6 +174,22 @@ export class SessionsService {
"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,
};
}
const result = await this.sendObjectiveMessage(
activeSession.id,
userId,
@@ -146,6 +252,28 @@ export class SessionsService {
}
}
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,
};
}
private toResponse(session: SessionWithObjective): SessionResponseDto {
return {
id: session.id,