import 'dotenv/config'; import { generateText, stepCountIs } from 'ai'; import { createMCPClient } from '@ai-sdk/mcp'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; import { deepseek } from '@ai-sdk/deepseek'; import { prisma } from '@omniloq/db'; import { randomUUID } from 'node:crypto'; import { fileURLToPath } from 'node:url'; import { dirname } from 'node:path'; const mockMcpPath = fileURLToPath(new URL('./mock-mcp-server.ts', import.meta.url)); const coreDir = dirname(mockMcpPath); export interface RunResult { runId: string; text: string; finishReason: string | null; toolCalls: { id: string; name: string; status: string }[]; } function extractText(content: unknown): string { if (Array.isArray(content)) { const textPart = (content as Array>).find((p) => p?.type === 'text'); return textPart ? String(textPart.text ?? '') : ''; } if (typeof content === 'string') return content; return JSON.stringify(content); } function isToolError(result: unknown): boolean { if (result && typeof result === 'object') { const r = result as Record; if (r.isError === true) return true; // certains providers wrappent l'erreur dans content if (Array.isArray(r.content)) { const txt = extractText(r.content); if (txt.toUpperCase().startsWith('ERREUR')) return true; } } return false; } /** * Runtime enrichi : persiste end-to-end Message inbound → AgentRun → ToolCall(s) → Message outbound. * Transactions DB courtes (chaque opération Prisma est sa propre TX) ; jamais de TX autour du LLM/MCP. * Chaque ToolCall est créé AVANT l'exécution MCP (statut EXECUTING), puis SUCCESS/ERROR après. */ export async function runAgentPersisted(conversationId: string): Promise { // 1. Charger conversation + agent + activeRevision + tools const conversation = await prisma.conversation.findUnique({ where: { id: conversationId }, include: { agent: { include: { activeRevision: true, tools: true } } }, }); if (!conversation) throw new Error('conversation not found'); const agent = conversation.agent; const revision = agent.activeRevision; if (!revision) throw new Error('agent has no active revision'); const lastInbound = await prisma.message.findFirst({ where: { conversationId, direction: 'inbound' }, orderBy: { createdAt: 'desc' }, }); if (!lastInbound) throw new Error('no inbound message'); const inboundText = extractText(lastInbound.content); // 2. Snapshot ToolPolicy const toolPolicySnapshot: Record = {}; for (const t of agent.tools) { toolPolicySnapshot[t.toolName] = { requiresConfirmation: t.requiresConfirmation, riskLevel: t.riskLevel, timeoutMs: t.timeoutMs, maxCallsPerRun: t.maxCallsPerRun, idempotencyRequired: t.idempotencyRequired, }; } // 3. Créer AgentRun (TX courte) const agentRun = await prisma.agentRun.create({ data: { conversationId, agentRevisionId: revision.id, triggerMessageId: lastInbound.id, provider: revision.provider, model: revision.model, status: 'running', toolPolicySnapshot: toolPolicySnapshot as any, }, }); const startMs = Date.now(); // 4. Connecter MCP const transport = new StdioClientTransport({ command: process.execPath, args: ['--import', 'tsx', mockMcpPath], cwd: coreDir, stderr: 'ignore', }); const mcp = await createMCPClient({ transport }); try { const mcpTools = await mcp.tools(); // 5. Envelopper chaque tool : créer ToolCall AVANT exécution, SUCCESS/ERROR après const wrappedTools = Object.fromEntries( Object.entries(mcpTools).map(([name, tool]) => [ name, { ...(tool as object), execute: async (args: unknown, options: unknown) => { const toolCall = await prisma.toolCall.create({ data: { runId: agentRun.id, toolName: name, arguments: (args ?? {}) as any, idempotencyKey: `${agentRun.id}:${name}:${randomUUID()}`, status: 'executing', startedAt: new Date(), }, }); try { const result = await (tool as any).execute(args, options); if (isToolError(result)) { await prisma.toolCall.update({ where: { id: toolCall.id }, data: { status: 'error', error: extractText((result as any)?.content) || 'MCP returned an error', result: result as any, finishedAt: new Date(), }, }); } else { await prisma.toolCall.update({ where: { id: toolCall.id }, data: { status: 'success', result: result as any, finishedAt: new Date() }, }); } return result; } catch (e) { const msg = e instanceof Error ? e.message : String(e); await prisma.toolCall.update({ where: { id: toolCall.id }, data: { status: 'error', error: msg, finishedAt: new Date() }, }); throw e; } }, }, ]) ); // 6. Boucle LLM (aucune TX longue : generateText est hors transaction) const result = await generateText({ model: deepseek(revision.model), tools: wrappedTools, stopWhen: stepCountIs(revision.maxSteps), maxRetries: 0, system: revision.systemPrompt, prompt: inboundText, }); const usage = (result.usage ?? {}) as Record; const inputTokens = usage.inputTokens ?? 0; const outputTokens = usage.outputTokens ?? 0; const totalTokens = usage.totalTokens ?? inputTokens + outputTokens; const latencyMs = Date.now() - startMs; // 7. Message outbound (TX courte) await prisma.message.create({ data: { conversationId, direction: 'outbound', senderType: 'agent', content: [{ type: 'text', text: result.text }] as any, status: 'sent', runId: agentRun.id, }, }); // 8. AgentRun COMPLETED (TX courte) await prisma.agentRun.update({ where: { id: agentRun.id }, data: { status: 'completed', finishReason: result.finishReason, inputTokens, outputTokens, totalTokens, latencyMs, steps: result.steps?.length ?? 0, usageRaw: usage as any, finishedAt: new Date(), }, }); const toolCalls = await prisma.toolCall.findMany({ where: { runId: agentRun.id }, orderBy: { startedAt: 'asc' }, }); return { runId: agentRun.id, text: result.text, finishReason: result.finishReason, toolCalls: toolCalls.map((tc) => ({ id: tc.id, name: tc.toolName, status: tc.status })), }; } catch (e) { // LLM error → AgentRun FAILED, données précédentes conservées await prisma.agentRun .update({ where: { id: agentRun.id }, data: { status: 'failed', finishedAt: new Date(), latencyMs: Date.now() - startMs } }) .catch(() => {}); throw e; } finally { await mcp.close?.(); } }