( teamId, question, conversationHistory, aiConversationId, userId, context = null, )
| 15 | } |
| 16 | |
| 17 | async function getOrchestration( |
| 18 | teamId, |
| 19 | question, |
| 20 | conversationHistory, |
| 21 | aiConversationId, |
| 22 | userId, |
| 23 | context = null, |
| 24 | ) { |
| 25 | let conversation; |
| 26 | |
| 27 | // Load existing conversation or create new one |
| 28 | if (aiConversationId) { |
| 29 | conversation = await db.AiConversation.findByPk(aiConversationId); |
| 30 | if (!conversation) { |
| 31 | throw new Error("Conversation not found"); |
| 32 | } |
| 33 | if (`${conversation.team_id}` !== `${teamId}`) { |
| 34 | throw new Error("Conversation does not belong to this team"); |
| 35 | } |
| 36 | assertConversationOwnership(conversation, userId); |
| 37 | } else { |
| 38 | // Create new conversation |
| 39 | conversation = await db.AiConversation.create({ |
| 40 | team_id: teamId, |
| 41 | user_id: userId, |
| 42 | title: "New Conversation", // Will be updated by orchestrator |
| 43 | status: "active", |
| 44 | }); |
| 45 | |
| 46 | // Emit conversation ID to user's room immediately so they can join before orchestration |
| 47 | socketManager.emitToUser(userId, "conversation-created", { |
| 48 | conversationId: conversation.id |
| 49 | }); |
| 50 | } |
| 51 | |
| 52 | // Load conversation history from database if not provided |
| 53 | let fullHistory = conversationHistory; |
| 54 | if (!conversationHistory || conversationHistory.length === 0) { |
| 55 | // Rebuild history from AiMessage table |
| 56 | const messages = await db.AiMessage.findAll({ |
| 57 | where: { conversation_id: conversation.id }, |
| 58 | order: [["sequence", "ASC"]], |
| 59 | }); |
| 60 | |
| 61 | fullHistory = messages.map((msg) => { |
| 62 | const messageObj = { |
| 63 | role: msg.role, |
| 64 | content: msg.content, |
| 65 | }; |
| 66 | |
| 67 | // Add tool-specific fields |
| 68 | if (msg.tool_calls) { |
| 69 | messageObj.tool_calls = msg.tool_calls; |
| 70 | } |
| 71 | if (msg.tool_name) { |
| 72 | messageObj.name = msg.tool_name; |
| 73 | } |
| 74 | if (msg.tool_call_id) { |
no test coverage detected