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 { openai } from '@ai-sdk/openai'; import { prisma } from '@omniloq/db'; import type { AgentRevision, AgentTool, McpServer, ToolCall, Message } from '@omniloq/db'; import { randomUUID } from 'node:crypto'; import { fileURLToPath } from 'node:url'; import { dirname } from 'node:path'; import { buildContext } from './context-builder'; import { evaluateToolPolicy } from './tool-policy'; import { guardFinalAnswer } from './response-guard'; import { extractText } from './text'; const mockMcpPath = fileURLToPath(new URL('./mock-mcp-server.ts', import.meta.url)); const coreDir = dirname(mockMcpPath); /** Durée de validité d'une demande de confirmation (2 h). */ const CONFIRMATION_TTL_MS = 2 * 60 * 60 * 1000; export interface RunResult { runId: string; text: string; finishReason: string | null; toolCalls: { id: string; name: string; status: string }[]; awaitingConfirmation?: boolean; } function isToolError(result: unknown): boolean { if (result && typeof result === 'object') { const r = result as Record; if (r.isError === true) return true; if (Array.isArray(r.content)) { const txt = extractText(r.content); if (txt.toUpperCase().startsWith('ERREUR')) return true; } } return false; } /** Réponse affirmative (à raffiner — pas de NLP lourd pour le premier jet). */ const CONFIRM_PATTERN = /^(oui|ouais|ok|okay|confirme|confirmé|confirm|valide|valider|je confirme|d'accord|daccord|yes|go|vas-y|vasy|fais-le|fais le|fait le)\b/i; function isConfirmation(text: string): boolean { return CONFIRM_PATTERN.test(text.trim()); } async function connectMcp() { const transport = new StdioClientTransport({ command: process.execPath, args: ['--import', 'tsx', mockMcpPath], cwd: coreDir, stderr: 'ignore', }); return createMCPClient({ transport }); } function getModel(revision: { provider: string; model: string }) { return revision.provider === 'openai' ? openai(revision.model) : deepseek(revision.model); } function buildPolicySnapshot(tools: AgentTool[]): Record { const snapshot: Record = {}; for (const t of tools) { snapshot[t.toolName] = { requiresConfirmation: t.requiresConfirmation, riskLevel: t.riskLevel, timeoutMs: t.timeoutMs, maxCallsPerRun: t.maxCallsPerRun, idempotencyRequired: t.idempotencyRequired, }; } return snapshot; } function buildConfirmationPrompt(toolName: string, args: unknown): string { const details = args && typeof args === 'object' ? JSON.stringify(args) : String(args ?? ''); return `Confirmez-vous l'action « ${toolName} » ? Détails : ${details}\n(répondez « oui » pour confirmer)`; } /** * Runtime enrichi + Phase 1.5 : * - ContextBuilder (system + variables + derniers messages, budget tokens) * - ToolPolicy (ALLOW / CONFIRM / DENY) via des wrappers Omniloq — jamais de MCP direct * - Confirmation persistante / resume (AWAITING_CONFIRMATION → résolution ultérieure) * - ResponseGuard (fuite de reasoning → régénération, jamais de mutilation regex) */ export async function runAgentPersisted(conversationId: string): Promise { // 1. Charger conversation + agent + révision + tools + variables + messages const conversation = await prisma.conversation.findUnique({ where: { id: conversationId }, include: { agent: { include: { activeRevision: true, tools: { include: { mcpServer: true } }, variables: true, }, }, messages: { orderBy: { createdAt: 'asc' } }, }, }); 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 = [...conversation.messages].reverse().find((m) => m.direction === 'inbound'); if (!lastInbound) throw new Error('no inbound message'); const inboundText = extractText(lastInbound.content); // 2. Confirmation pending non expirée ? → résoudre avant tout const pendingToolCall = await prisma.toolCall.findFirst({ where: { run: { conversationId }, status: 'awaiting_confirmation', confirmationExpiresAt: { gt: new Date() }, }, orderBy: { confirmationRequestedAt: 'desc' }, }); if (pendingToolCall && isConfirmation(inboundText)) { return resumeConfirmation(conversationId, revision, agent.tools, lastInbound, pendingToolCall); } // 3. ContextBuilder — seule porte d'entrée du contexte LLM const ctx = buildContext({ agentRevision: revision, variables: agent.variables, allMessages: conversation.messages, triggerMessage: lastInbound, }); // 4. 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: buildPolicySnapshot(agent.tools) as any, }, }); const startMs = Date.now(); const mcp = await connectMcp(); try { const mcpTools = await mcp.tools(); // Index toolName → agentTool (pour ToolPolicy) + compteur d'appels du run const toolIndex = new Map(); for (const t of agent.tools) toolIndex.set(t.toolName, { agentTool: t, mcpServer: t.mcpServer }); const callsByTool: Record = {}; // 5. Wrapper Omniloq : chaque tool exposé au LLM est un proxy (jamais de MCP direct) const wrappedTools: Record = Object.fromEntries( Object.entries(mcpTools).map(([name, tool]) => { const idx = toolIndex.get(name) ?? null; return [ name, { ...(tool as object), execute: async (args: unknown, options: unknown) => { const policy = evaluateToolPolicy({ agentTool: idx?.agentTool ?? null, mcpServer: idx?.mcpServer ?? null, callsSoFarThisRun: callsByTool[name] ?? 0, }); if (policy.decision === 'DENY') { // Refus SANS appeler MCP. Audit : ToolCall en error. await prisma.toolCall.create({ data: { runId: agentRun.id, toolName: name, mcpServerId: idx?.agentTool?.mcpServerId ?? null, arguments: (args ?? {}) as any, idempotencyKey: `${agentRun.id}:${name}:${randomUUID()}`, status: 'error', error: `DENY: ${policy.reason}`, startedAt: new Date(), finishedAt: new Date(), }, }); return { isError: true, content: [{ type: 'text', text: `ERREUR: action refusée (${policy.reason}).` }], }; } if (policy.decision === 'CONFIRM') { // Persiste la demande de confirmation (AVANT tout side effect), // puis retourne un résultat neutre : le runtime remplacera la // réponse LLM par un message de confirmation déterministe. await prisma.toolCall.create({ data: { runId: agentRun.id, toolName: name, mcpServerId: idx?.agentTool?.mcpServerId ?? null, arguments: (args ?? {}) as any, idempotencyKey: `${agentRun.id}:${name}:${randomUUID()}`, status: 'awaiting_confirmation', confirmationRequestedAt: new Date(), confirmationExpiresAt: new Date(Date.now() + CONFIRMATION_TTL_MS), startedAt: new Date(), }, }); return { content: [ { type: 'text', text: `L'action « ${name} » nécessite la confirmation du client. Ne fais aucune autre action : demande simplement au client de confirmer.`, }, ], }; } // ALLOW → exécution réelle (persistance AVANT side effect) callsByTool[name] = (callsByTool[name] ?? 0) + 1; const tc = await prisma.toolCall.create({ data: { runId: agentRun.id, toolName: name, mcpServerId: idx?.agentTool?.mcpServerId ?? null, 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: tc.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: tc.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: tc.id }, data: { status: 'error', error: msg, finishedAt: new Date() } }) .catch(() => {}); throw e; } }, }, ]; }) ); // 6. Boucle LLM (aucune TX longue) const result = await generateText({ model: getModel(revision), tools: wrappedTools, stopWhen: stepCountIs(revision.maxSteps), maxRetries: 0, system: ctx.system, prompt: ctx.prompt, }); // 7. ResponseGuard : fuite de reasoning → régénération (jamais de mutilation) const guarded = await guardFinalAnswer(result.text, async () => { const regen = await generateText({ model: getModel(revision), stopWhen: stepCountIs(1), system: ctx.system + '\nRègle stricte : réponds directement au client, sans jamais exposer ton raisonnement interne ni aucune balise.', prompt: 'Réponds à la dernière demande du client de façon concise et directe.', }); return regen.text; }); const usage = (result.usage ?? {}) as unknown as Record; const inputTokens = usage.inputTokens ?? 0; const outputTokens = usage.outputTokens ?? 0; const totalTokens = usage.totalTokens ?? inputTokens + outputTokens; const toolCalls = await prisma.toolCall.findMany({ where: { runId: agentRun.id }, orderBy: { startedAt: 'asc' }, }); // 8. Confirmation déclenchée pendant ce run ? → message déterministe, run interrompu proprement const awaiting = toolCalls.filter((tc) => tc.status === 'awaiting_confirmation'); if (awaiting.length > 0) { const tc = awaiting[0]; // une seule confirmation active ambiguë au début const confirmMsg = await prisma.message.create({ data: { conversationId, direction: 'outbound', senderType: 'agent', content: [{ type: 'text', text: buildConfirmationPrompt(tc.toolName, tc.arguments) }] as any, status: 'sent', runId: agentRun.id, }, }); await prisma.toolCall.update({ where: { id: tc.id }, data: { confirmationMessageId: confirmMsg.id }, }); await prisma.agentRun.update({ where: { id: agentRun.id }, data: { status: 'completed', finishReason: 'awaiting_confirmation', inputTokens, outputTokens, totalTokens, latencyMs: Date.now() - startMs, steps: result.steps?.length ?? 0, usageRaw: usage as any, finishedAt: new Date(), }, }); return { runId: agentRun.id, text: '', finishReason: 'awaiting_confirmation', toolCalls: toolCalls.map((tc) => ({ id: tc.id, name: tc.toolName, status: tc.status })), awaitingConfirmation: true, }; } // 9. Message outbound (TX courte) await prisma.message.create({ data: { conversationId, direction: 'outbound', senderType: 'agent', content: [{ type: 'text', text: guarded.text }] as any, status: 'sent', runId: agentRun.id, }, }); // 10. AgentRun COMPLETED (TX courte) await prisma.agentRun.update({ where: { id: agentRun.id }, data: { status: 'completed', finishReason: result.finishReason, inputTokens, outputTokens, totalTokens, latencyMs: Date.now() - startMs, steps: result.steps?.length ?? 0, usageRaw: usage as any, finishedAt: new Date(), }, }); return { runId: agentRun.id, text: guarded.text, finishReason: result.finishReason, toolCalls: toolCalls.map((tc) => ({ id: tc.id, name: tc.toolName, status: tc.status })), }; } catch (e) { // LLM error → AgentRun FAILED 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?.(); } } /** * Résolution d'une confirmation : exécute le ToolCall en attente (non expiré), * crée un NOUVEAU AgentRun, génère la réponse finale. * Le ToolCall garde son runId d'origine (celui qui l'a demandé) — l'exécution * est tracée par confirmedAt / confirmedByMessageId / confirmationDecision. */ async function resumeConfirmation( conversationId: string, revision: AgentRevision, agentTools: (AgentTool & { mcpServer: McpServer })[], triggerMessage: Message, pendingToolCall: ToolCall ): Promise { const agentRun = await prisma.agentRun.create({ data: { conversationId, agentRevisionId: revision.id, triggerMessageId: triggerMessage.id, provider: revision.provider, model: revision.model, status: 'running', toolPolicySnapshot: buildPolicySnapshot(agentTools) as any, }, }); const startMs = Date.now(); // Marquer la confirmation + passage à executing (avant side effect) await prisma.toolCall.update({ where: { id: pendingToolCall.id }, data: { status: 'executing', confirmedAt: new Date(), confirmedByMessageId: triggerMessage.id, confirmationDecision: 'confirmed', }, }); const mcp = await connectMcp(); try { const mcpTools = await mcp.tools(); const tool = mcpTools[pendingToolCall.toolName]; if (!tool) throw new Error(`tool not found in MCP: ${pendingToolCall.toolName}`); const result = await (tool as any).execute((pendingToolCall.arguments ?? {}) as any, {}); let finalStatus: string; if (isToolError(result)) { finalStatus = 'error'; await prisma.toolCall.update({ where: { id: pendingToolCall.id }, data: { status: 'error', error: extractText((result as any)?.content) || 'MCP returned an error', result: result as any, finishedAt: new Date(), }, }); } else { finalStatus = 'success'; await prisma.toolCall.update({ where: { id: pendingToolCall.id }, data: { status: 'success', result: result as any, finishedAt: new Date() }, }); } // Réponse finale (appel LLM sans tools — pas de nouveau side effect) const final = await generateText({ model: getModel(revision), stopWhen: stepCountIs(1), system: revision.systemPrompt + '\nRègle : confirme brièvement au client le résultat de l\'action déjà exécutée. Ne refais aucune action.', prompt: `L'action « ${pendingToolCall.toolName} » a été exécutée avec le résultat : ${extractText( (result as any)?.content )}. Formule la réponse au client.`, }); await prisma.message.create({ data: { conversationId, direction: 'outbound', senderType: 'agent', content: [{ type: 'text', text: final.text }] as any, status: 'sent', runId: agentRun.id, }, }); const usage = (final.usage ?? {}) as unknown as Record; await prisma.agentRun.update({ where: { id: agentRun.id }, data: { status: 'completed', finishReason: final.finishReason, inputTokens: usage.inputTokens ?? 0, outputTokens: usage.outputTokens ?? 0, totalTokens: usage.totalTokens ?? 0, latencyMs: Date.now() - startMs, steps: final.steps?.length ?? 0, usageRaw: usage as any, finishedAt: new Date(), }, }); return { runId: agentRun.id, text: final.text, finishReason: final.finishReason, toolCalls: [{ id: pendingToolCall.id, name: pendingToolCall.toolName, status: finalStatus }], }; } catch (e) { 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?.(); } }