import type { AgentTool, McpServer } from '@omniloq/db'; export type ToolPolicyDecision = 'ALLOW' | 'CONFIRM' | 'DENY'; export interface ToolPolicyInput { /** AgentTool enregistré pour cet agent, ou null si le tool n'appartient pas à l'agent. */ agentTool: AgentTool | null; /** McpServer de rattachement, ou null si introuvable/désactivé. */ mcpServer: McpServer | null; /** Nombre d'appels déjà effectués pour ce tool dans le run courant. */ callsSoFarThisRun: number; } export interface ToolPolicyResult { decision: ToolPolicyDecision; reason: string; } const HIGH_RISK_LEVELS = new Set(['high', 'critical']); /** * Seul point de décision d'autorisation d'un appel de tool. * Le LLM ne décide JAMAIS si une action a besoin de confirmation — c'est le runtime. * * Ordre de vérification : * 1. le tool est bien enregistré pour cet agent (sinon DENY) * 2. le tool est activé (enabled) (sinon DENY) * 3. le MCP est activé (sinon DENY) * 4. limite maxCallsPerRun non dépassée (sinon DENY) * 5. requiresConfirmation ou riskLevel haut (→ CONFIRM) * 6. sinon ALLOW */ export function evaluateToolPolicy({ agentTool, mcpServer, callsSoFarThisRun, }: ToolPolicyInput): ToolPolicyResult { if (!agentTool) return { decision: 'DENY', reason: 'tool_not_registered_for_agent' }; if (!agentTool.enabled) return { decision: 'DENY', reason: 'tool_disabled' }; if (!mcpServer || !mcpServer.enabled) return { decision: 'DENY', reason: 'mcp_server_disabled' }; if (agentTool.maxCallsPerRun > 0 && callsSoFarThisRun >= agentTool.maxCallsPerRun) { return { decision: 'DENY', reason: 'max_calls_per_run_exceeded' }; } if (agentTool.requiresConfirmation || HIGH_RISK_LEVELS.has(agentTool.riskLevel)) { return { decision: 'CONFIRM', reason: 'requires_confirmation' }; } return { decision: 'ALLOW', reason: 'allowed' }; }