UNPKG

n8n

Version:

n8n Workflow Automation Tool

208 lines • 10.8 kB
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.AgentChatController = void 0; const api_types_1 = require("@n8n/api-types"); const decorators_1 = require("@n8n/decorators"); const crypto_1 = require("crypto"); const credentials_service_1 = require("../../credentials/credentials.service"); const not_found_error_1 = require("../../errors/response-errors/not-found.error"); const agents_credential_provider_1 = require("./adapters/agents-credential-provider"); const agent_execution_orchestrator_service_1 = require("./agent-execution-orchestrator.service"); const agent_execution_service_1 = require("./agent-execution.service"); const agent_message_mapper_1 = require("./agent-message-mapper"); const agent_sse_stream_1 = require("./agent-sse-stream"); const agent_test_chat_service_1 = require("./agent-test-chat.service"); const agent_validation_service_1 = require("./agent-validation.service"); const agents_service_1 = require("./agents.service"); const agents_builder_service_1 = require("./builder/agents-builder.service"); const agent_memory_scope_1 = require("./utils/agent-memory-scope"); const messages_envelope_1 = require("./utils/messages-envelope"); let AgentChatController = class AgentChatController { constructor(agentExecutionOrchestratorService, agentTestChatService, agentValidationService, agentsBuilderService, credentialsService, agentExecutionService, agentsService) { this.agentExecutionOrchestratorService = agentExecutionOrchestratorService; this.agentTestChatService = agentTestChatService; this.agentValidationService = agentValidationService; this.agentsBuilderService = agentsBuilderService; this.credentialsService = credentialsService; this.agentExecutionService = agentExecutionService; this.agentsService = agentsService; } async chat(req, res, agentId, payload) { const { projectId } = req.params; const { message, sessionId } = payload; const credentialProvider = new agents_credential_provider_1.AgentsCredentialProvider(this.credentialsService, projectId, req.user); const { send } = (0, agent_sse_stream_1.initSseStream)(res); if (sessionId) { const existing = await this.agentExecutionService.findThreadById(sessionId); if (existing && !(0, agent_execution_service_1.threadBelongsTo)(existing, projectId, agentId)) { send({ type: 'error', message: 'Session not found' }); res.end(); return; } } const threadId = sessionId ?? (0, crypto_1.randomUUID)(); const { missing } = await this.agentValidationService.validateAgentIsRunnable(agentId, projectId, credentialProvider); if (missing.length > 0) { send({ type: 'error', message: 'This agent is not ready to run yet.', errorCode: 'agent_misconfigured', missing, }); res.end(); return; } try { let executionId; const suspended = await (0, agent_sse_stream_1.pumpChunks)(this.agentExecutionOrchestratorService.executeForChat({ agentId, projectId, message, user: req.user, memory: { threadId, resourceId: (0, agent_memory_scope_1.draftChatMemoryResourceId)(req.user.id), }, onExecutionRecorded: (id) => { executionId = id; }, }), send); if (!suspended) { send({ type: 'done', sessionId: threadId, ...(executionId ? { executionId } : {}) }); } } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Chat failed'; send({ type: 'error', message: errorMessage }); } res.end(); } async chatResume(req, res, agentId, payload) { const { projectId } = req.params; const { runId, toolCallId, resumeData } = payload; const { send } = (0, agent_sse_stream_1.initSseStream)(res); try { let executionId; const suspended = await (0, agent_sse_stream_1.pumpChunks)(this.agentExecutionOrchestratorService.resumeForChat({ agentId, projectId, runId, toolCallId, resumeData, user: req.user, usePublishedVersion: false, integrationType: api_types_1.N8N_CHAT_INTEGRATION_TYPE, onExecutionRecorded: (id) => { executionId = id; }, }), send); if (!suspended) { send({ type: 'done', ...(executionId ? { executionId } : {}) }); } } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Resume failed'; send({ type: 'error', message: errorMessage }); } res.end(); } async getChatMessages(req) { const { projectId, agentId, threadId } = req.params; const agent = await this.agentsService.findById(agentId, projectId); if (!agent) throw new not_found_error_1.NotFoundError(`Agent "${agentId}" not found`); const history = await this.agentExecutionOrchestratorService.getConversationHistory({ threadId, projectId, agentId, }); let checkpoint = await this.agentsBuilderService.findOpenCheckpointForThread(agentId, threadId); if (!history) { if (checkpoint) return (0, messages_envelope_1.withOpenSuspensions)([], checkpoint); throw new not_found_error_1.NotFoundError(`Thread "${threadId}" not found`); } if (!checkpoint) { checkpoint = await this.agentsBuilderService.findOpenCheckpointForThread(agentId, threadId, { includeUnscoped: true, }); } return (0, messages_envelope_1.withOpenSuspensions)(history, checkpoint, { appendInactiveCheckpointMessages: false, }); } async getTestChatMessages(req) { const { projectId, agentId } = req.params; const agent = await this.agentsService.findById(agentId, projectId); if (!agent) throw new not_found_error_1.NotFoundError(`Agent "${agentId}" not found`); const messages = await this.agentTestChatService.getTestChatMessages(agentId, req.user.id); const checkpoint = await this.agentsBuilderService.findOpenCheckpointForThread(agentId, (0, agent_test_chat_service_1.chatThreadId)(agentId, req.user.id)); return (0, messages_envelope_1.withOpenSuspensions)((0, agent_message_mapper_1.messagesToDto)(messages), checkpoint); } async clearTestChatMessages(req) { const { projectId, agentId } = req.params; const agent = await this.agentsService.findById(agentId, projectId); if (!agent) throw new not_found_error_1.NotFoundError(`Agent "${agentId}" not found`); await this.agentTestChatService.clearTestChatMessages(agentId, req.user.id); return { ok: true }; } }; exports.AgentChatController = AgentChatController; __decorate([ (0, decorators_1.Post)('/:agentId/chat', { usesTemplates: true }), (0, decorators_1.ProjectScope)('agent:execute'), __param(2, (0, decorators_1.Param)('agentId')), __param(3, decorators_1.Body), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object, String, api_types_1.AgentChatMessageDto]), __metadata("design:returntype", Promise) ], AgentChatController.prototype, "chat", null); __decorate([ (0, decorators_1.Post)('/:agentId/chat/resume', { usesTemplates: true }), (0, decorators_1.ProjectScope)('agent:execute'), __param(2, (0, decorators_1.Param)('agentId')), __param(3, decorators_1.Body), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object, String, api_types_1.AgentChatResumeDto]), __metadata("design:returntype", Promise) ], AgentChatController.prototype, "chatResume", null); __decorate([ (0, decorators_1.Get)('/:agentId/chat/:threadId/messages'), (0, decorators_1.ProjectScope)('agent:read'), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], AgentChatController.prototype, "getChatMessages", null); __decorate([ (0, decorators_1.Get)('/:agentId/chat/messages'), (0, decorators_1.ProjectScope)('agent:read'), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], AgentChatController.prototype, "getTestChatMessages", null); __decorate([ (0, decorators_1.Delete)('/:agentId/chat/messages'), (0, decorators_1.ProjectScope)('agent:update'), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], AgentChatController.prototype, "clearTestChatMessages", null); exports.AgentChatController = AgentChatController = __decorate([ (0, decorators_1.RestController)('/projects/:projectId/agents/v2'), __metadata("design:paramtypes", [agent_execution_orchestrator_service_1.AgentExecutionOrchestratorService, agent_test_chat_service_1.AgentTestChatService, agent_validation_service_1.AgentValidationService, agents_builder_service_1.AgentsBuilderService, credentials_service_1.CredentialsService, agent_execution_service_1.AgentExecutionService, agents_service_1.AgentsService]) ], AgentChatController); //# sourceMappingURL=agent-chat.controller.js.map