dolibarr 25.0.0-alpha
email_cleaner.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2026 Braito <braito4@hotmail.com>
3 * Copyright (C) 2026 MDW <mdeweerd@users.noreply.github.com>
4 * Copyright (C) 2026 Jose Martinez <jose.martinez@pichinov.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
30{
31 private const TABLE_AI_REQUEST_LOG = 'ai_request_log';
32 private const TOOL_NAME = 'email_cleaner';
33
37 private $tableExistsCache = array();
38
44 public function getDefinitions(): array
45 {
46 if (!isModEnabled('emailcollector') || !getDolGlobalInt('AI_EMAILCLEANER_ENABLED', 0)) {
47 return [];
48 }
49
50 return [
51 [
52 'name' => 'list_email_cleaner_runs',
53 'description' => 'List EmailCollector AI cleaner runs logged in the shared AI request log. Technical metadata only, no business interpretation.',
54 'inputSchema' => [
55 'type' => 'object',
56 'properties' => [
57 'actioncomm_id' => ['type' => 'integer', 'description' => 'Optional agenda event id filter.'],
58 'collector_id' => ['type' => 'integer', 'description' => 'Optional collector id filter.'],
59 'message_id' => ['type' => 'string', 'description' => 'Optional message-id filter.'],
60 'context_profile_code' => ['type' => 'string', 'description' => 'Optional context profile filter.'],
61 'min_confidence' => ['type' => 'number', 'description' => 'Optional minimum cleaning confidence (0..1).'],
62 'max_confidence' => ['type' => 'number', 'description' => 'Optional maximum cleaning confidence (0..1).'],
63 'limit' => ['type' => 'integer', 'default' => 20],
64 'offset' => ['type' => 'integer', 'default' => 0],
65 ],
66 ],
67 ],
68 [
69 'name' => 'get_email_cleaner_run',
70 'description' => 'Get one EmailCollector AI cleaner run from the shared AI request log.',
71 'inputSchema' => [
72 'type' => 'object',
73 'properties' => [
74 'ai_request_log_id' => ['type' => 'integer', 'description' => 'AI request log rowid.'],
75 'cleaning_id' => ['type' => 'integer', 'description' => 'Backward-compatible alias for ai_request_log_id.'],
76 'message_id' => ['type' => 'string', 'description' => 'Message-id fallback selector.'],
77 'collector_id' => ['type' => 'integer', 'description' => 'Optional collector filter when using message_id.'],
78 ],
79 'anyOf' => [
80 ['required' => ['ai_request_log_id']],
81 ['required' => ['cleaning_id']],
82 ['required' => ['message_id']],
83 ],
84 ],
85 ],
86 [
87 'name' => 'get_email_thread_context',
88 'description' => 'Get only the technical email thread context extracted by EmailCleaner. No business interpretation.',
89 'inputSchema' => [
90 'type' => 'object',
91 'properties' => [
92 'ai_request_log_id' => ['type' => 'integer', 'description' => 'AI request log rowid.'],
93 'cleaning_id' => ['type' => 'integer', 'description' => 'Backward-compatible alias for ai_request_log_id.'],
94 'message_id' => ['type' => 'string', 'description' => 'Message-id fallback selector.'],
95 'collector_id' => ['type' => 'integer', 'description' => 'Optional collector filter when using message_id.'],
96 ],
97 'anyOf' => [
98 ['required' => ['ai_request_log_id']],
99 ['required' => ['cleaning_id']],
100 ['required' => ['message_id']],
101 ],
102 ],
103 ],
104 [
105 'name' => 'get_email_handoff_payload',
106 'description' => 'Get handoff payload generated by EmailCleaner from the shared AI request log. Evidence only, no decision.',
107 'inputSchema' => [
108 'type' => 'object',
109 'properties' => [
110 'ai_request_log_id' => ['type' => 'integer', 'description' => 'AI request log rowid.'],
111 'handoff_id' => ['type' => 'integer', 'description' => 'Backward-compatible alias for ai_request_log_id.'],
112 'cleaning_id' => ['type' => 'integer', 'description' => 'Backward-compatible alias for ai_request_log_id.'],
113 ],
114 'anyOf' => [
115 ['required' => ['ai_request_log_id']],
116 ['required' => ['handoff_id']],
117 ['required' => ['cleaning_id']],
118 ],
119 ],
120 ],
121 ];
122 }
123
129 public function getCategories(): array
130 {
131 return ['global'];
132 }
133
144 public function getRequiredRights(string $toolName)
145 {
146 return array(array('emailcollector', 'read'));
147 }
148
156 public function execute(string $name, array $args)
157 {
158 if (!$this->canReadEmailData()) {
159 return $this->appendComplianceMetadata(['error' => "Permission Denied: You don't have rights to read email cleaner data."]);
160 }
161
162 $result = array();
163 switch ($name) {
164 case 'list_email_cleaner_runs':
165 $result = $this->listEmailCleanerRuns($args);
166 break;
167
168 case 'get_email_cleaner_run':
169 $result = $this->getEmailCleanerRun($args);
170 break;
171
172 case 'get_email_thread_context':
173 $result = $this->getEmailThreadContext($args);
174 break;
175
176 case 'get_email_handoff_payload':
177 $result = $this->getEmailHandoffPayload($args);
178 break;
179
180 default:
181 $result = ['error' => "Tool function '$name' not found."];
182 break;
183 }
184
185 return $this->appendComplianceMetadata($result);
186 }
187
193 private function canReadEmailData(): bool
194 {
195 if (empty($this->user->id)) {
196 return false;
197 }
198 if (!is_object($this->conf) || !isModEnabled('ai')) {
199 return false;
200 }
201 if (!isModEnabled('emailcollector')) {
202 return false;
203 }
204 if (!getDolGlobalInt('AI_EMAILCLEANER_ENABLED', 0)) {
205 return false;
206 }
207 if (!empty($this->user->admin)) {
208 return true;
209 }
210 if (method_exists($this->user, 'hasRight') && $this->user->hasRight('emailcollector', 'read')) {
211 return true;
212 }
213 return false;
214 }
215
222 private function listEmailCleanerRuns(array $args): array
223 {
224 if (!$this->isTableAvailable(self::TABLE_AI_REQUEST_LOG)) {
225 return ['error' => 'AI request log table is not available.'];
226 }
227
228 $entity = (int) (!empty($this->conf->entity) ? $this->conf->entity : 1);
229 $limit = $this->sanitizeLimit($args['limit'] ?? 20);
230 $offset = max(0, (int) ($args['offset'] ?? 0));
231 $actioncommId = (int) ($args['actioncomm_id'] ?? 0);
232 $collectorId = (int) ($args['collector_id'] ?? 0);
233 $messageId = trim((string) ($args['message_id'] ?? ''));
234 $contextProfileCode = trim((string) ($args['context_profile_code'] ?? ''));
235 $minConfidence = $this->sanitizeConfidenceOrNull($args['min_confidence'] ?? null);
236 $maxConfidence = $this->sanitizeConfidenceOrNull($args['max_confidence'] ?? null);
237
238 $sql = "SELECT rowid, fk_actioncomm, provider, confidence, status, raw_request_payload, date_request";
239 $sql .= " FROM ".MAIN_DB_PREFIX.self::TABLE_AI_REQUEST_LOG;
240 $sql .= " WHERE entity = ".((int) $entity);
241 $sql .= " AND tool_name = '".$this->db->escape(self::TOOL_NAME)."'";
242
243 if ($actioncommId > 0) {
244 $sql .= " AND fk_actioncomm = ".((int) $actioncommId);
245 }
246 if ($collectorId > 0) {
247 $sql .= " AND raw_request_payload LIKE '%\"collector_id\":".((int) $collectorId)."%'";
248 }
249 if ($messageId !== '') {
250 $sql .= " AND raw_request_payload LIKE '%".$this->db->escape($messageId)."%'";
251 }
252 if ($contextProfileCode !== '') {
253 $sql .= " AND raw_request_payload LIKE '%".$this->db->escape($contextProfileCode)."%'";
254 }
255 if ($minConfidence !== null) {
256 $sql .= " AND confidence >= ".((float) $minConfidence);
257 }
258 if ($maxConfidence !== null) {
259 $sql .= " AND confidence <= ".((float) $maxConfidence);
260 }
261
262 $sql .= " ORDER BY rowid DESC";
263 $sql .= $this->db->plimit($limit, $offset);
264
265 $resql = $this->db->query($sql);
266 if (!$resql) {
267 return ['error' => 'Database error while listing email cleaner runs: '.$this->db->lasterror()];
268 }
269
270 $items = array();
271 while ($obj = $this->db->fetch_object($resql)) {
272 $inputMetadata = $this->decodeJsonOrRaw((string) $obj->raw_request_payload);
273 $items[] = array(
274 'ai_request_log_id' => (int) $obj->rowid,
275 'cleaning_id' => (int) $obj->rowid,
276 'actioncomm_id' => (int) $obj->fk_actioncomm,
277 'collector_id' => (!empty($inputMetadata['collector_id']) ? (int) $inputMetadata['collector_id'] : null),
278 'message_id' => (!empty($inputMetadata['message_id']) ? (string) $inputMetadata['message_id'] : null),
279 'cleaning_confidence' => (float) $obj->confidence,
280 'cleaning_model' => null,
281 'prompt_code' => (!empty($inputMetadata['prompt_code']) ? (string) $inputMetadata['prompt_code'] : null),
282 'prompt_version' => (!empty($inputMetadata['prompt_version']) ? (string) $inputMetadata['prompt_version'] : null),
283 'context_profile_code' => (!empty($inputMetadata['context_profile_code']) ? (string) $inputMetadata['context_profile_code'] : null),
284 'context_profile_version' => (!empty($inputMetadata['context_profile_version']) ? (string) $inputMetadata['context_profile_version'] : null),
285 'status' => (!empty($obj->status) ? (string) $obj->status : null),
286 'date_creation' => (!empty($obj->date_request) ? (string) $obj->date_request : null),
287 );
288 }
289 $this->db->free($resql);
290
291 return array(
292 'items' => $items,
293 'count' => count($items),
294 'filters' => array(
295 'entity' => $entity,
296 'actioncomm_id' => ($actioncommId > 0 ? $actioncommId : null),
297 'collector_id' => ($collectorId > 0 ? $collectorId : null),
298 'message_id' => ($messageId !== '' ? $messageId : null),
299 'context_profile_code' => ($contextProfileCode !== '' ? $contextProfileCode : null),
300 'min_confidence' => $minConfidence,
301 'max_confidence' => $maxConfidence,
302 'limit' => $limit,
303 'offset' => $offset,
304 ),
305 );
306 }
307
314 private function getEmailCleanerRun(array $args): array
315 {
316 if (!$this->isTableAvailable(self::TABLE_AI_REQUEST_LOG)) {
317 return ['error' => 'AI request log table is not available.'];
318 }
319
320 $entity = (int) (!empty($this->conf->entity) ? $this->conf->entity : 1);
321 $aiRequestLogId = (int) ($args['ai_request_log_id'] ?? ($args['cleaning_id'] ?? 0));
322 $messageId = trim((string) ($args['message_id'] ?? ''));
323 $collectorId = (int) ($args['collector_id'] ?? 0);
324
325 $sql = "SELECT rowid, entity, fk_actioncomm, provider, input_hash, output_hash, security_hash, confidence, status, raw_request_payload, raw_response_payload, date_request";
326 $sql .= " FROM ".MAIN_DB_PREFIX.self::TABLE_AI_REQUEST_LOG;
327 $sql .= " WHERE entity = ".((int) $entity);
328 $sql .= " AND tool_name = '".$this->db->escape(self::TOOL_NAME)."'";
329
330 if ($aiRequestLogId > 0) {
331 $sql .= " AND rowid = ".((int) $aiRequestLogId);
332 } elseif ($messageId !== '') {
333 $sql .= " AND raw_request_payload LIKE '%".$this->db->escape($messageId)."%'";
334 if ($collectorId > 0) {
335 $sql .= " AND raw_request_payload LIKE '%\"collector_id\":".((int) $collectorId)."%'";
336 }
337 $sql .= " ORDER BY rowid DESC";
338 } else {
339 return ['error' => "Missing selector: use 'ai_request_log_id', 'cleaning_id' or 'message_id'."];
340 }
341
342 $sql .= $this->db->plimit(1);
343
344 $resql = $this->db->query($sql);
345 if (!$resql) {
346 return ['error' => 'Database error while reading cleaner run: '.$this->db->lasterror()];
347 }
348 $obj = $this->db->fetch_object($resql);
349 $this->db->free($resql);
350 if (!$obj) {
351 return ['error' => 'Email cleaner run not found.'];
352 }
353
354 $inputMetadata = $this->decodeJsonOrRaw((string) $obj->raw_request_payload);
355 $outputJson = $this->decodeJsonOrRaw((string) $obj->raw_response_payload);
356 $handoffJson = (!empty($outputJson['handoff_payload_json']) && is_array($outputJson['handoff_payload_json'])) ? $outputJson['handoff_payload_json'] : array();
357
358 return array(
359 'ai_request_log_id' => (int) $obj->rowid,
360 'cleaning_id' => (int) $obj->rowid,
361 'entity' => (int) $obj->entity,
362 'actioncomm_id' => (int) $obj->fk_actioncomm,
363 'collector_id' => (!empty($inputMetadata['collector_id']) ? (int) $inputMetadata['collector_id'] : 0),
364 'message_id' => (!empty($inputMetadata['message_id']) ? (string) $inputMetadata['message_id'] : ''),
365 'raw_hash' => (!empty($inputMetadata['raw_hash']) ? (string) $inputMetadata['raw_hash'] : null),
366 'clean_hash' => (!empty($inputMetadata['clean_hash']) ? (string) $inputMetadata['clean_hash'] : null),
367 'clean_body' => (!empty($outputJson['clean_body']) ? (string) $outputJson['clean_body'] : ''),
368 'cleaning_confidence' => (float) $obj->confidence,
369 'cleaning_model' => (!empty($outputJson['cleaning_model']) ? (string) $outputJson['cleaning_model'] : null),
370 'prompt_code' => (!empty($inputMetadata['prompt_code']) ? (string) $inputMetadata['prompt_code'] : null),
371 'prompt_version' => (!empty($inputMetadata['prompt_version']) ? (string) $inputMetadata['prompt_version'] : null),
372 'context_profile_code' => (!empty($inputMetadata['context_profile_code']) ? (string) $inputMetadata['context_profile_code'] : null),
373 'context_profile_version' => (!empty($inputMetadata['context_profile_version']) ? (string) $inputMetadata['context_profile_version'] : null),
374 'input_hash' => (!empty($obj->input_hash) ? (string) $obj->input_hash : null),
375 'output_hash' => (!empty($obj->output_hash) ? (string) $obj->output_hash : null),
376 'security_hash' => (!empty($obj->security_hash) ? (string) $obj->security_hash : null),
377 'status' => (!empty($obj->status) ? (string) $obj->status : null),
378 'raw_request_payload' => $inputMetadata,
379 'cleaning_json' => $outputJson,
380 'handoff_payload_json' => $handoffJson,
381 'date_creation' => (!empty($obj->date_request) ? (string) $obj->date_request : null),
382 );
383 }
384
391 private function getEmailThreadContext(array $args): array
392 {
393 $run = $this->getEmailCleanerRun($args);
394 if (!empty($run['error'])) {
395 return $run;
396 }
397
398 $cleaningJson = (!empty($run['cleaning_json']) && is_array($run['cleaning_json'])) ? $run['cleaning_json'] : array();
399 $handoffJson = (!empty($run['handoff_payload_json']) && is_array($run['handoff_payload_json'])) ? $run['handoff_payload_json'] : array();
400 $emailContext = array();
401
402 if (!empty($cleaningJson['email_context']) && is_array($cleaningJson['email_context'])) {
403 $emailContext = $cleaningJson['email_context'];
404 } elseif (!empty($handoffJson['conversation_context']) && is_array($handoffJson['conversation_context'])) {
405 $emailContext = $handoffJson['conversation_context'];
406 }
407
408 return array(
409 'ai_request_log_id' => (int) $run['ai_request_log_id'],
410 'cleaning_id' => (int) $run['cleaning_id'],
411 'actioncomm_id' => (int) $run['actioncomm_id'],
412 'collector_id' => (int) $run['collector_id'],
413 'message_id' => (string) $run['message_id'],
414 'email_context' => $emailContext,
415 'cleaning_confidence' => (float) $run['cleaning_confidence'],
416 'context_profile_code' => (!empty($run['context_profile_code']) ? (string) $run['context_profile_code'] : null),
417 'context_profile_version' => (!empty($run['context_profile_version']) ? (string) $run['context_profile_version'] : null),
418 );
419 }
420
427 private function getEmailHandoffPayload(array $args): array
428 {
429 $aiRequestLogId = (int) ($args['ai_request_log_id'] ?? ($args['handoff_id'] ?? ($args['cleaning_id'] ?? 0)));
430 if ($aiRequestLogId <= 0) {
431 return ['error' => "Missing selector: use 'ai_request_log_id', 'handoff_id' or 'cleaning_id'."];
432 }
433
434 $run = $this->getEmailCleanerRun(array('ai_request_log_id' => $aiRequestLogId));
435 if (!empty($run['error'])) {
436 return $run;
437 }
438
439 return array(
440 'ai_request_log_id' => (int) $run['ai_request_log_id'],
441 'handoff_id' => (int) $run['ai_request_log_id'],
442 'cleaning_id' => (int) $run['cleaning_id'],
443 'actioncomm_id' => (int) $run['actioncomm_id'],
444 'handoff_version' => (!empty($run['handoff_payload_json']['handoff_version']) ? (string) $run['handoff_payload_json']['handoff_version'] : null),
445 'consumer_code' => 'generic',
446 'payload_json' => $run['handoff_payload_json'],
447 'payload_hash' => (!empty($run['output_hash']) ? (string) $run['output_hash'] : null),
448 'quality_status' => (!empty($run['status']) ? (string) $run['status'] : null),
449 'date_creation' => (!empty($run['date_creation']) ? (string) $run['date_creation'] : null),
450 );
451 }
452
459 private function isTableAvailable(string $tableWithoutPrefix): bool
460 {
461 if (isset($this->tableExistsCache[$tableWithoutPrefix])) {
462 return $this->tableExistsCache[$tableWithoutPrefix];
463 }
464
465 $full = MAIN_DB_PREFIX.$tableWithoutPrefix;
466 $ok = (bool) count($this->db->DDLInfoTable($full));
467 $this->tableExistsCache[$tableWithoutPrefix] = $ok;
468
469 return $ok;
470 }
471
478 private function decodeJsonOrRaw(string $raw)
479 {
480 $raw = trim($raw);
481 if ($raw === '') {
482 return array();
483 }
484 $dec = json_decode($raw, true);
485 if (json_last_error() === JSON_ERROR_NONE && is_array($dec)) {
486 return $dec;
487 }
488 return $raw;
489 }
490
497 private function sanitizeLimit($raw): int
498 {
499 $limit = (int) $raw;
500 if ($limit <= 0) {
501 $limit = 20;
502 }
503 if ($limit > 200) {
504 $limit = 200;
505 }
506 return $limit;
507 }
508
515 private function sanitizeConfidenceOrNull($raw): ?float
516 {
517 if ($raw === null || $raw === '') {
518 return null;
519 }
520 $val = (float) $raw;
521 if ($val < 0) {
522 $val = 0;
523 }
524 if ($val > 1) {
525 $val = 1;
526 }
527 return $val;
528 }
529
536 private function appendComplianceMetadata(array $result): array
537 {
538 $result['compliance'] = array(
539 'ai_transparency_label' => 'AI-derived technical evidence',
540 'human_review_required' => 1,
541 'autonomous_business_action_allowed' => 0,
542 'policy_scope' => 'diagnostic_only_no_business_decision',
543 );
544
545 return $result;
546 }
547}
Abstract base class for all MCP (Model Context Protocol) tools.
Class ToolEmailCleaner.
decodeJsonOrRaw(string $raw)
Decode json string, fallback to raw.
sanitizeLimit($raw)
Sanitize limit.
appendComplianceMetadata(array $result)
Append compliance disclosure to MCP responses.
sanitizeConfidenceOrNull($raw)
Sanitize confidence value or return null.
isTableAvailable(string $tableWithoutPrefix)
Check if a table is available.
getEmailCleanerRun(array $args)
Get one cleaner run.
getRequiredRights(string $toolName)
Rights required to run one of these tools.
getEmailHandoffPayload(array $args)
Get handoff payload.
listEmailCleanerRuns(array $args)
List cleaner runs.
getDefinitions()
Returns tool definitions.
canReadEmailData()
Check read permission for technical email data.
getEmailThreadContext(array $args)
Get only the technical email thread context from a cleaner run.
getCategories()
Return categories this tool belongs to.
execute(string $name, array $args)
Execute tool.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
isModEnabled($module)
Is Dolibarr module enabled.
conf($dolibarr_main_document_root, $realpathconf=null)
Load conf file (file must exists)
Definition inc.php:431
$conf db user
Active Directory does not allow anonymous connections.
Definition repair.php:166