feat(sessions): add unified /sessions/messages entry point
Add SessionsService#routeIncomingMessage: if the user has an active non-completed session, route to its agent by status (only objective_discovery is implemented so far - any other status rejects with a clear 409 rather than failing silently); otherwise run the intent router first and only create a session + start Agent 1 when it detects a learning intent, replying as plain conversational Max (PERSONALITY_PROMPT only, no session) otherwise. Exposed as POST /sessions/messages (JWT-protected), the new single entry point the chat window should call instead of unconditionally creating a session on every message. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
dc368a32f0
commit
ce25d3f290
@@ -0,0 +1,26 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { ObjectiveDraftDto } from './objective-message-response.dto';
|
||||||
|
|
||||||
|
export class RouteMessageResponseDto {
|
||||||
|
@ApiProperty({
|
||||||
|
enum: ['chat', 'learn'],
|
||||||
|
description:
|
||||||
|
'"chat" : reponse conversationnelle, aucune session creee. "learn" : une session de formation est active (nouvelle ou existante).',
|
||||||
|
})
|
||||||
|
type!: 'chat' | 'learn';
|
||||||
|
|
||||||
|
@ApiProperty({ description: 'Reponse de Max a afficher dans le chat.' })
|
||||||
|
reply!: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
required: false,
|
||||||
|
description: 'Present uniquement si type="learn".',
|
||||||
|
})
|
||||||
|
sessionId?: number;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
ready?: boolean;
|
||||||
|
|
||||||
|
@ApiProperty({ type: ObjectiveDraftDto, required: false })
|
||||||
|
draft?: ObjectiveDraftDto;
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ describe('SessionsController', () => {
|
|||||||
findOne: jest.fn(),
|
findOne: jest.fn(),
|
||||||
sendObjectiveMessage: jest.fn(),
|
sendObjectiveMessage: jest.fn(),
|
||||||
confirmObjective: jest.fn(),
|
confirmObjective: jest.fn(),
|
||||||
|
routeIncomingMessage: jest.fn(),
|
||||||
};
|
};
|
||||||
const request = {
|
const request = {
|
||||||
user: { sub: 7, email: 'w@example.com' },
|
user: { sub: 7, email: 'w@example.com' },
|
||||||
@@ -66,4 +67,16 @@ describe('SessionsController', () => {
|
|||||||
await controller.confirmObjective(1, request);
|
await controller.confirmObjective(1, request);
|
||||||
expect(sessionsService.confirmObjective).toHaveBeenCalledWith(1, 7);
|
expect(sessionsService.confirmObjective).toHaveBeenCalledWith(1, 7);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should route an incoming message for the authenticated user', async () => {
|
||||||
|
sessionsService.routeIncomingMessage.mockResolvedValueOnce({
|
||||||
|
type: 'chat',
|
||||||
|
reply: 'ok',
|
||||||
|
});
|
||||||
|
await controller.routeMessage({ message: 'Salut' }, request);
|
||||||
|
expect(sessionsService.routeIncomingMessage).toHaveBeenCalledWith(
|
||||||
|
7,
|
||||||
|
'Salut',
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import {
|
|||||||
import type { AuthenticatedRequest } from '../auth/jwt-auth.guard';
|
import type { AuthenticatedRequest } from '../auth/jwt-auth.guard';
|
||||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||||
import { ObjectiveMessageResponseDto } from './dto/objective-message-response.dto';
|
import { ObjectiveMessageResponseDto } from './dto/objective-message-response.dto';
|
||||||
|
import { RouteMessageResponseDto } from './dto/route-message-response.dto';
|
||||||
import { SendObjectiveMessageDto } from './dto/send-objective-message.dto';
|
import { SendObjectiveMessageDto } from './dto/send-objective-message.dto';
|
||||||
import { SessionObjectiveResponseDto } from './dto/session-objective-response.dto';
|
import { SessionObjectiveResponseDto } from './dto/session-objective-response.dto';
|
||||||
import { SessionResponseDto } from './dto/session-response.dto';
|
import { SessionResponseDto } from './dto/session-response.dto';
|
||||||
@@ -38,6 +39,26 @@ export class SessionsController {
|
|||||||
return this.sessionsService.create(request.user.sub);
|
return this.sessionsService.create(request.user.sub);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post('messages')
|
||||||
|
@ApiOperation({
|
||||||
|
summary:
|
||||||
|
"Point d'entree unique du chat : route vers la session active ou demarre une formation selon l'intention detectee",
|
||||||
|
})
|
||||||
|
@ApiResponse({ status: HttpStatus.CREATED, type: RouteMessageResponseDto })
|
||||||
|
@ApiResponse({
|
||||||
|
status: HttpStatus.CONFLICT,
|
||||||
|
description: 'Etape du pipeline pas encore implementee',
|
||||||
|
})
|
||||||
|
routeMessage(
|
||||||
|
@Body() dto: SendObjectiveMessageDto,
|
||||||
|
@Req() request: AuthenticatedRequest,
|
||||||
|
): Promise<RouteMessageResponseDto> {
|
||||||
|
return this.sessionsService.routeIncomingMessage(
|
||||||
|
request.user.sub,
|
||||||
|
dto.message,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@Get(':id')
|
@Get(':id')
|
||||||
@ApiOperation({ summary: "Recuperer l'etat d'une session" })
|
@ApiOperation({ summary: "Recuperer l'etat d'une session" })
|
||||||
@ApiResponse({ status: HttpStatus.OK, type: SessionResponseDto })
|
@ApiResponse({ status: HttpStatus.OK, type: SessionResponseDto })
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
|
|||||||
import { AuthModule } from '../auth/auth.module';
|
import { AuthModule } from '../auth/auth.module';
|
||||||
import { LlmModule } from '../llm/llm.module';
|
import { LlmModule } from '../llm/llm.module';
|
||||||
import { PrismaModule } from '../prisma/prisma.module';
|
import { PrismaModule } from '../prisma/prisma.module';
|
||||||
|
import { IntentRouterAgent } from './agents/intent-router.agent';
|
||||||
import { ObjectiveAgent } from './agents/objective.agent';
|
import { ObjectiveAgent } from './agents/objective.agent';
|
||||||
import { SessionsController } from './sessions.controller';
|
import { SessionsController } from './sessions.controller';
|
||||||
import { SessionsService } from './sessions.service';
|
import { SessionsService } from './sessions.service';
|
||||||
@@ -9,7 +10,7 @@ import { SessionsService } from './sessions.service';
|
|||||||
@Module({
|
@Module({
|
||||||
imports: [PrismaModule, LlmModule, AuthModule],
|
imports: [PrismaModule, LlmModule, AuthModule],
|
||||||
controllers: [SessionsController],
|
controllers: [SessionsController],
|
||||||
providers: [SessionsService, ObjectiveAgent],
|
providers: [SessionsService, ObjectiveAgent, IntentRouterAgent],
|
||||||
exports: [SessionsService],
|
exports: [SessionsService],
|
||||||
})
|
})
|
||||||
export class SessionsModule {}
|
export class SessionsModule {}
|
||||||
|
|||||||
@@ -1,15 +1,19 @@
|
|||||||
import { ConflictException, NotFoundException } from '@nestjs/common';
|
import { ConflictException, NotFoundException } from '@nestjs/common';
|
||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { OpenRouterService } from '../llm/openrouter.service';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { IntentRouterAgent } from './agents/intent-router.agent';
|
||||||
import { ObjectiveAgent } from './agents/objective.agent';
|
import { ObjectiveAgent } from './agents/objective.agent';
|
||||||
import { SessionsService } from './sessions.service';
|
import { SessionsService } from './sessions.service';
|
||||||
|
|
||||||
describe('SessionsService', () => {
|
describe('SessionsService', () => {
|
||||||
let service: SessionsService;
|
let service: SessionsService;
|
||||||
const prisma = {
|
const prisma = {
|
||||||
session: { create: jest.fn(), findUnique: jest.fn() },
|
session: { create: jest.fn(), findUnique: jest.fn(), findFirst: jest.fn() },
|
||||||
};
|
};
|
||||||
const objectiveAgent = { converse: jest.fn(), confirm: jest.fn() };
|
const objectiveAgent = { converse: jest.fn(), confirm: jest.fn() };
|
||||||
|
const intentRouter = { analyze: jest.fn() };
|
||||||
|
const llm = { chat: jest.fn() };
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
jest.clearAllMocks();
|
jest.clearAllMocks();
|
||||||
@@ -18,6 +22,8 @@ describe('SessionsService', () => {
|
|||||||
SessionsService,
|
SessionsService,
|
||||||
{ provide: PrismaService, useValue: prisma },
|
{ provide: PrismaService, useValue: prisma },
|
||||||
{ provide: ObjectiveAgent, useValue: objectiveAgent },
|
{ provide: ObjectiveAgent, useValue: objectiveAgent },
|
||||||
|
{ provide: IntentRouterAgent, useValue: intentRouter },
|
||||||
|
{ provide: OpenRouterService, useValue: llm },
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
@@ -125,4 +131,105 @@ describe('SessionsService', () => {
|
|||||||
expect(result.validatedAt).toEqual(new Date('2026-01-02'));
|
expect(result.validatedAt).toEqual(new Date('2026-01-02'));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('routeIncomingMessage()', () => {
|
||||||
|
it('should route to the objective agent when an active objective_discovery session exists', async () => {
|
||||||
|
const activeSession = {
|
||||||
|
id: 1,
|
||||||
|
userId: 7,
|
||||||
|
status: 'objective_discovery',
|
||||||
|
objective: null,
|
||||||
|
};
|
||||||
|
prisma.session.findFirst.mockResolvedValueOnce(activeSession);
|
||||||
|
prisma.session.findUnique.mockResolvedValueOnce(activeSession);
|
||||||
|
objectiveAgent.converse.mockResolvedValueOnce({
|
||||||
|
reply: 'Quel est ton sujet ?',
|
||||||
|
ready: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.routeIncomingMessage(7, 'Je veux apprendre');
|
||||||
|
|
||||||
|
expect(objectiveAgent.converse).toHaveBeenCalledWith(
|
||||||
|
1,
|
||||||
|
7,
|
||||||
|
'Je veux apprendre',
|
||||||
|
);
|
||||||
|
expect(result).toEqual({
|
||||||
|
type: 'learn',
|
||||||
|
sessionId: 1,
|
||||||
|
reply: 'Quel est ton sujet ?',
|
||||||
|
ready: false,
|
||||||
|
draft: undefined,
|
||||||
|
});
|
||||||
|
expect(intentRouter.analyze).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject when the active session is in a status with no agent built yet', async () => {
|
||||||
|
prisma.session.findFirst.mockResolvedValueOnce({
|
||||||
|
id: 1,
|
||||||
|
userId: 7,
|
||||||
|
status: 'mapping',
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.routeIncomingMessage(7, 'un message'),
|
||||||
|
).rejects.toThrow(ConflictException);
|
||||||
|
expect(objectiveAgent.converse).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reply conversationally without creating a session when intent is chat', async () => {
|
||||||
|
prisma.session.findFirst.mockResolvedValueOnce(null);
|
||||||
|
intentRouter.analyze.mockResolvedValueOnce({
|
||||||
|
intent: 'chat',
|
||||||
|
subject: null,
|
||||||
|
});
|
||||||
|
llm.chat.mockResolvedValueOnce('Salut, comment puis-je aider ?');
|
||||||
|
|
||||||
|
const result = await service.routeIncomingMessage(7, 'Salut ça va ?');
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
type: 'chat',
|
||||||
|
reply: 'Salut, comment puis-je aider ?',
|
||||||
|
});
|
||||||
|
expect(prisma.session.create).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create a session and start Agent 1 when intent is learn', async () => {
|
||||||
|
prisma.session.findFirst.mockResolvedValueOnce(null);
|
||||||
|
intentRouter.analyze.mockResolvedValueOnce({
|
||||||
|
intent: 'learn',
|
||||||
|
subject: 'React',
|
||||||
|
});
|
||||||
|
prisma.session.create.mockResolvedValueOnce({
|
||||||
|
id: 9,
|
||||||
|
userId: 7,
|
||||||
|
status: 'objective_discovery',
|
||||||
|
});
|
||||||
|
objectiveAgent.converse.mockResolvedValueOnce({
|
||||||
|
reply: 'Quel est ton objectif avec React ?',
|
||||||
|
ready: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.routeIncomingMessage(
|
||||||
|
7,
|
||||||
|
'Apprends-moi React',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(prisma.session.create).toHaveBeenCalledWith({
|
||||||
|
data: { userId: 7 },
|
||||||
|
});
|
||||||
|
expect(objectiveAgent.converse).toHaveBeenCalledWith(
|
||||||
|
9,
|
||||||
|
7,
|
||||||
|
'Apprends-moi React',
|
||||||
|
);
|
||||||
|
expect(result).toEqual({
|
||||||
|
type: 'learn',
|
||||||
|
sessionId: 9,
|
||||||
|
reply: 'Quel est ton objectif avec React ?',
|
||||||
|
ready: false,
|
||||||
|
draft: undefined,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -4,18 +4,26 @@ import {
|
|||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { Session, SessionObjective } from '@prisma/client';
|
import { Session, SessionObjective } from '@prisma/client';
|
||||||
|
import { OpenRouterService } from '../llm/openrouter.service';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { IntentRouterAgent } from './agents/intent-router.agent';
|
||||||
import { ObjectiveAgent, ObjectiveTurnResult } from './agents/objective.agent';
|
import { ObjectiveAgent, ObjectiveTurnResult } from './agents/objective.agent';
|
||||||
|
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 { SessionObjectiveResponseDto } from './dto/session-objective-response.dto';
|
||||||
import { SessionResponseDto } from './dto/session-response.dto';
|
import { SessionResponseDto } from './dto/session-response.dto';
|
||||||
|
|
||||||
type SessionWithObjective = Session & { objective: SessionObjective | null };
|
type SessionWithObjective = Session & { objective: SessionObjective | null };
|
||||||
|
|
||||||
|
const IMPLEMENTED_STATUSES = new Set(['objective_discovery']);
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class SessionsService {
|
export class SessionsService {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly objectiveAgent: ObjectiveAgent,
|
private readonly objectiveAgent: ObjectiveAgent,
|
||||||
|
private readonly intentRouter: IntentRouterAgent,
|
||||||
|
private readonly llm: OpenRouterService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async create(userId: number): Promise<SessionResponseDto> {
|
async create(userId: number): Promise<SessionResponseDto> {
|
||||||
@@ -55,6 +63,65 @@ export class SessionsService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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<RouteMessageResponseDto> {
|
||||||
|
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.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
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(
|
private async findOwnedSession(
|
||||||
id: number,
|
id: number,
|
||||||
userId: number,
|
userId: number,
|
||||||
|
|||||||
Reference in New Issue
Block a user