BxDolAiQuery.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaCore UNA Core
  7. * @{
  8. */
  9. class BxDolAiQuery extends BxDolDb
  10. {
  11. public function __construct()
  12. {
  13. parent::__construct();
  14. }
  15. static protected function _getObject(int $iId, string $sTable): array|bool
  16. {
  17. $oDb = BxDolDb::getInstance();
  18. $a = $oDb->getRow("SELECT * FROM `$sTable` WHERE `id` = :id", ['id' => $iId]);
  19. if(!$a || !is_array($a))
  20. return false;
  21. return $a;
  22. }
  23. static public function getModelObject(int $iId): array|bool
  24. {
  25. return self::_getObject($iId, 'sys_agents_models');
  26. }
  27. static public function getVectorStoreObject(int $iId): array|bool
  28. {
  29. return self::_getObject($iId, 'sys_agents_vector_store');
  30. }
  31. static public function getAgentObject(int $iId): array|bool
  32. {
  33. return self::_getObject($iId, 'sys_agents_agents');
  34. }
  35. static public function getToolObject(int $iId): array|bool
  36. {
  37. return self::_getObject($iId, 'sys_agents_tools');
  38. }
  39. public function insertModel($aModel)
  40. {
  41. if(empty($aModel))
  42. return false;
  43. return (int)$this->query("INSERT INTO `sys_agents_models` SET " . $this->arrayToSQL($aModel));
  44. }
  45. public function getModelsBy($aParams = [])
  46. {
  47. $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
  48. $sWhereClause = "";
  49. switch($aParams['sample']) {
  50. case 'id':
  51. $aMethod['name'] = 'getRow';
  52. $aMethod['params'][1] = [
  53. 'id' => $aParams['id']
  54. ];
  55. $sWhereClause .= " AND `id`=:id";
  56. break;
  57. case 'all_pairs':
  58. $aMethod['name'] = 'getPairs';
  59. $aMethod['params'][1] = 'id';
  60. $aMethod['params'][2] = 'title';
  61. $aMethod['params'][3] = [];
  62. if(isset($aParams['active'])) {
  63. $aMethod['params'][3]['active'] = $aParams['active'];
  64. $sWhereClause .= " AND `active`=:active";
  65. }
  66. if(isset($aParams['capabilities'])) {
  67. if (is_array($aParams['capabilities']))
  68. {
  69. $sWhereClause .= " AND `capabilities` IN (" . $this->implode_escape($aParams['capabilities']) . ")";
  70. }
  71. else {
  72. $aMethod['params'][3]['capabilities'] = $aParams['capabilities'];
  73. $sWhereClause .= " AND `capabilities` = :capabilities";
  74. }
  75. }
  76. if (!empty($aParams['type_not'])) {
  77. $aMethod['params'][3]['type_not'] = $aParams['type_not'];
  78. $sWhereClause .= " AND `type` <> :type_not";
  79. }
  80. break;
  81. }
  82. $aMethod['params'][0] = "SELECT *
  83. FROM `sys_agents_models`
  84. WHERE 1" . $sWhereClause;
  85. return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
  86. }
  87. public function getVectorStores (): mixed
  88. {
  89. $sQuery = "SELECT `id`, `title` FROM `sys_agents_vector_store` WHERE `active` = 1 ORDER BY `title` ASC";
  90. return $this->getPairs($sQuery, 'id', 'title');
  91. }
  92. public function getVectorStoreById (int $iId): mixed
  93. {
  94. $sQuery = "SELECT * FROM `sys_agents_vector_store` WHERE `id` = :id";
  95. return $this->getRow($sQuery, ['id' => $iId]);
  96. }
  97. public function insertVectorStore($aVectorStore)
  98. {
  99. if(empty($aVectorStore) || !is_array($aVectorStore))
  100. return false;
  101. return (int)$this->query("INSERT INTO `sys_agents_vector_store` SET " . $this->arrayToSQL($aVectorStore));
  102. }
  103. public function getVectorStoreDataNum (int $iVectorStoreId): int
  104. {
  105. $sQuery = "SELECT COUNT(*) FROM `sys_agents_vector_store_data` WHERE `vector_store_id` = :vector_store_id";
  106. return (int)$this->getOne($sQuery, ['vector_store_id' => $iVectorStoreId]);
  107. }
  108. public function addVectorStoreData (int $iVectorStoreId, string $sType, string $sName, int $iFileSize, string $sMetadata, string $sSettings, string $sContent): bool
  109. {
  110. $sQuery = "INSERT INTO `sys_agents_vector_store_data` SET
  111. `vector_store_id` = :vector_store_id,
  112. `type` = :type,
  113. `name` = :name,
  114. `size` = :size,
  115. `metadata` = :metadata,
  116. `settings` = :settings,
  117. `content` = :content,
  118. `added` = :ts
  119. ";
  120. return $this->query($sQuery, [
  121. 'vector_store_id' => $iVectorStoreId,
  122. 'type' => $sType,
  123. 'name' => $sName,
  124. 'size' => $iFileSize,
  125. 'metadata' => $sMetadata,
  126. 'settings' => $sSettings,
  127. 'content' => $sContent,
  128. 'ts' => time()]) > 0;
  129. }
  130. public function getVectorStoreDataById (int $iId): mixed
  131. {
  132. $sQuery = "SELECT * FROM `sys_agents_vector_store_data` WHERE `id` = :id";
  133. return $this->getRow($sQuery, ['id' => $iId]);
  134. }
  135. static public function getVectorStorePendingData (int $iLimit = 1): mixed
  136. {
  137. $oDb = BxDolDb::getInstance();
  138. $sQuery = "SELECT * FROM `sys_agents_vector_store_data` WHERE `status` = 'pending' ORDER BY `added` ASC LIMIT :limit";
  139. return $oDb->getAll($sQuery, ['limit' => $iLimit]);
  140. }
  141. static public function updateVectorStoreDataStatus (int $iId, string $sStatus): mixed
  142. {
  143. $oDb = BxDolDb::getInstance();
  144. $sQuery = "UPDATE `sys_agents_vector_store_data` SET `status` = :status WHERE `id` = :id";
  145. return $oDb->query($sQuery, ['status' => $sStatus, 'id' => $iId]);
  146. }
  147. public function getAgentsWithAlert($bActiveOnly = true)
  148. {
  149. return $this->fromCache('sys_agents_with_alert', 'getAll', "SELECT * FROM `sys_agents_agents` WHERE `trigger` = 'alert' AND `active` = :active", ['active' => $bActiveOnly ? 1 : 0]);
  150. }
  151. public function getAgentsByProfileId($iProfileId, $bActiveOnly = true)
  152. {
  153. return $this->getAll("SELECT * FROM `sys_agents_agents` WHERE `trigger` = 'message' AND `profile_id` = :profile AND `active` = :active", ['profile' => $iProfileId, 'active' => $bActiveOnly ? 1 : 0]);
  154. }
  155. public function getAgentsByFormObject($sFormObject, $bActiveOnly = true)
  156. {
  157. return $this->fromMemory('sys_agents_with_form_' . $sFormObject, 'getAll', "SELECT * FROM `sys_agents_agents` WHERE `trigger` = 'form-input' AND `form_object` = :form_object AND `active` = :active", ['form_object' => $sFormObject, 'active' => $bActiveOnly ? 1 : 0]);
  158. }
  159. public function getAgentsBy($aParams = [])
  160. {
  161. $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
  162. $sWhereClause = "";
  163. switch($aParams['sample']) {
  164. case 'id':
  165. $aMethod['name'] = 'getRow';
  166. $aMethod['params'][1] = [
  167. 'id' => $aParams['id']
  168. ];
  169. $sWhereClause .= " AND `id`=:id";
  170. break;
  171. case 'all':
  172. if(isset($aParams['active'])) {
  173. $aMethod['params'][3]['active'] = $aParams['active'];
  174. $sWhereClause .= " AND `active`=:active";
  175. }
  176. break;
  177. }
  178. $aMethod['params'][0] = "SELECT *
  179. FROM `sys_agents_agents`
  180. WHERE 1" . $sWhereClause;
  181. return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
  182. }
  183. public function getAgentById(int $iId): mixed
  184. {
  185. return $this->getAgentsBy(['sample' => 'id', 'id' => $iId]);
  186. }
  187. public function getAgentByTriggerWebhookKey($sKey, $bActiveOnly = true)
  188. {
  189. return $this->getRow("SELECT * FROM `sys_agents_agents` WHERE `trigger` = 'webhook' AND `webhook_key` = :key AND `active` = :active", ['key' => $sKey, 'active' => $bActiveOnly ? 1 : 0]);
  190. }
  191. public function getAgentsByTriggerType($sTrigger, $bActiveOnly = true)
  192. {
  193. return $this->getAll("SELECT * FROM `sys_agents_agents` WHERE `trigger` = :trigger AND `active` = :active", ['trigger' => $sTrigger, 'active' => $bActiveOnly ? 1 : 0]);
  194. }
  195. public function isAgentProfile($iProfileId)
  196. {
  197. return (int)$this->getOne("SELECT `id` FROM `sys_agents_agents` WHERE `profile_id` = :profile_id AND `active` = 1 LIMIT 1", ['profile_id' => (int)$iProfileId]) > 0;
  198. }
  199. public function updateAgentField($iId, $sField, $sValue)
  200. {
  201. return $this->query("UPDATE `sys_agents_agents` SET `$sField` = :value WHERE `id` = :id", ['value' => $sValue, 'id' => $iId]);
  202. }
  203. public function getToolById (int $iId): mixed
  204. {
  205. $sQuery = "SELECT * FROM `sys_agents_tools` WHERE `id` = :id";
  206. return $this->getRow($sQuery, ['id' => $iId]);
  207. }
  208. public function insertTool(array $aFields): int
  209. {
  210. if(empty($aFields) || !is_array($aFields))
  211. return false;
  212. return (int)$this->query("INSERT INTO `sys_agents_tools` SET " . $this->arrayToSQL($aFields));
  213. }
  214. public function getTools()
  215. {
  216. $sHidden = $this->implode_escape(BxDolAiAgentTools::hiddenTypes());
  217. $sQuery = "SELECT `id`, `title` FROM `sys_agents_tools` WHERE `active` = 1 AND `type` NOT IN (" . $sHidden . ") ORDER BY `title` ASC";
  218. return $this->getPairs($sQuery, 'id', 'title');
  219. }
  220. /**
  221. * Active tool rows for these types, lowest id first.
  222. *
  223. * @return array<int, array{id:int, type:string}>
  224. */
  225. public function getActiveToolsByTypes(array $aTypes): array
  226. {
  227. if (!$aTypes)
  228. return [];
  229. $aRows = $this->getAll("SELECT `id`, `type` FROM `sys_agents_tools` WHERE `active` = 1 AND `type` IN (" . $this->implode_escape($aTypes) . ") ORDER BY `id` ASC");
  230. $aOut = [];
  231. foreach ($aRows as $aRow) {
  232. $aOut[] = [
  233. 'id' => (int)$aRow['id'],
  234. 'type' => (string)$aRow['type'],
  235. ];
  236. }
  237. return $aOut;
  238. }
  239. /**
  240. * Every tool id of these types, including inactive copies.
  241. *
  242. * @return int[]
  243. */
  244. public function getToolIdsByTypes(array $aTypes): array
  245. {
  246. if (!$aTypes)
  247. return [];
  248. $aRows = $this->getAll("SELECT `id` FROM `sys_agents_tools` WHERE `type` IN (" . $this->implode_escape($aTypes) . ")");
  249. $aIds = [];
  250. foreach ($aRows as $aRow)
  251. $aIds[] = (int)$aRow['id'];
  252. return $aIds;
  253. }
  254. public function wipeAgentChatHistory($aAgent)
  255. {
  256. $sQuery = "DELETE FROM `sys_agents_chat_history` WHERE `thread_id` LIKE :val";
  257. $iAffected = 0;
  258. $iAffected += $this->query($sQuery, ['val' => $aAgent['trigger'] . ':' . $aAgent['id'] . ':%']);
  259. $iAffected += $this->query($sQuery, ['val' => $aAgent['trigger'] . ':' . $aAgent['id']]);
  260. return $iAffected;
  261. }
  262. public function getAgentChatHistoryRows($aAgent)
  263. {
  264. $sExact = ($aAgent['trigger'] ?? '') . ':' . ($aAgent['id'] ?? '');
  265. return $this->getAll("
  266. SELECT " . $this->getChatHistoryRowFields() . "
  267. FROM `sys_agents_chat_history`
  268. WHERE `thread_id` = :exact OR `thread_id` LIKE :prefix
  269. ORDER BY `updated_at` DESC
  270. LIMIT 200
  271. ", [
  272. 'exact' => $sExact,
  273. 'prefix' => $sExact . ':%',
  274. ]);
  275. }
  276. /**
  277. * Every thread one owner (profile id, or guest session id) has with this agent:
  278. * site-wide and in any context, base and `?chat=` partitions. Newest first.
  279. * Owner is matched by LIKE on the thread id, so callers still re-check it via
  280. * BxDolAiChat::parseThreadId.
  281. */
  282. public function getOwnerAgentChatHistoryRows($aAgent, $sOwner, $iLimit = 100)
  283. {
  284. $sPrefix = ($aAgent['trigger'] ?? '') . ':' . ($aAgent['id'] ?? '');
  285. $sOwner = (string)$sOwner;
  286. if ($sPrefix === ':' || $sOwner === '')
  287. return [];
  288. $sOwnerLike = str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $sOwner);
  289. return $this->getAll("
  290. SELECT " . $this->getChatHistoryRowFields() . "
  291. FROM `sys_agents_chat_history`
  292. WHERE `thread_id` = :site
  293. OR `thread_id` LIKE :site_chat
  294. OR `thread_id` LIKE :ctx
  295. OR `thread_id` LIKE :ctx_chat
  296. ORDER BY `updated_at` DESC, `id` DESC
  297. LIMIT " . (int)$iLimit, [
  298. 'site' => $sPrefix . ':' . $sOwner,
  299. 'site_chat' => $sPrefix . ':' . $sOwnerLike . '#%',
  300. 'ctx' => $sPrefix . ':%:' . $sOwnerLike,
  301. 'ctx_chat' => $sPrefix . ':%:' . $sOwnerLike . '#%',
  302. ]);
  303. }
  304. /**
  305. * The owner's current thread for this agent+context: the newest one that is not
  306. * closed — a `?chat=` partition or the base thread. '' when there is none.
  307. */
  308. public function getCurrentOpenChatThreadId($aAgent, $sOwner, $iContext)
  309. {
  310. if (!$this->isFieldExists('sys_agents_chat_history', 'closed_reason'))
  311. return '';
  312. $sPrefix = ($aAgent['trigger'] ?? '') . ':' . ($aAgent['id'] ?? '');
  313. $sOwner = (string)$sOwner;
  314. if ($sPrefix === ':' || $sOwner === '')
  315. return '';
  316. $sBase = ((int)$iContext > 0)
  317. ? ($sPrefix . ':' . (int)$iContext . ':' . $sOwner)
  318. : ($sPrefix . ':' . $sOwner);
  319. return (string)$this->getOne("
  320. SELECT `thread_id`
  321. FROM `sys_agents_chat_history`
  322. WHERE (`thread_id` = :exact OR `thread_id` LIKE :hash)
  323. AND (`closed_reason` = '' OR `closed_reason` IS NULL)
  324. ORDER BY `updated_at` DESC, `id` DESC
  325. LIMIT 1
  326. ", [
  327. 'exact' => $sBase,
  328. 'hash' => $sBase . '#%',
  329. ]);
  330. }
  331. /**
  332. * Stored thread title; '' when unset, or when the column is not there yet —
  333. * callers fall back to deriving one from the messages.
  334. */
  335. public function getChatHistoryTitle($sThreadId)
  336. {
  337. if (!$this->isFieldExists('sys_agents_chat_history', 'title'))
  338. return '';
  339. return (string)$this->getOne("SELECT `title` FROM `sys_agents_chat_history` WHERE `thread_id` = :t", [
  340. 't' => (string)$sThreadId,
  341. ]);
  342. }
  343. public function setChatHistoryTitle($sThreadId, $sTitle)
  344. {
  345. if (!$this->isFieldExists('sys_agents_chat_history', 'title'))
  346. return false;
  347. return (bool)$this->query("UPDATE `sys_agents_chat_history` SET `title` = :s WHERE `thread_id` = :t", [
  348. 's' => get_mb_substr((string)$sTitle, 0, 255),
  349. 't' => (string)$sThreadId,
  350. ]);
  351. }
  352. /**
  353. * History row for a thread, created empty when missing.
  354. *
  355. * @return int row id, 0 for an invalid thread id
  356. */
  357. public function ensureChatHistoryRow($sThreadId)
  358. {
  359. $sThreadId = (string)$sThreadId;
  360. if ($sThreadId === '' || $sThreadId === ':')
  361. return 0;
  362. $iId = $this->getChatHistoryIdByThreadId($sThreadId);
  363. if ($iId)
  364. return $iId;
  365. $this->query("INSERT IGNORE INTO `sys_agents_chat_history` (`thread_id`, `messages`) VALUES (:t, :m)", [
  366. 't' => $sThreadId,
  367. 'm' => '[]',
  368. ]);
  369. return $this->getChatHistoryIdByThreadId($sThreadId);
  370. }
  371. protected function getChatHistoryRowFields()
  372. {
  373. $sFields = "`id`, `thread_id`, `messages`, `created_at`, `updated_at`";
  374. if ($this->isFieldExists('sys_agents_chat_history', 'closed_reason'))
  375. $sFields .= ", `closed_reason`";
  376. if ($this->isFieldExists('sys_agents_chat_history', 'title'))
  377. $sFields .= ", `title`";
  378. return $sFields;
  379. }
  380. public function getChatHistoryIdByThreadId($sThreadId)
  381. {
  382. $sThreadId = (string)$sThreadId;
  383. if ($sThreadId === '' || $sThreadId === ':')
  384. return 0;
  385. return (int)$this->getOne("SELECT `id` FROM `sys_agents_chat_history` WHERE `thread_id` = :t", [
  386. 't' => $sThreadId,
  387. ]);
  388. }
  389. public function getChatHistoryMessagesByThreadId($sThreadId)
  390. {
  391. $sThreadId = (string)$sThreadId;
  392. if ($sThreadId === '')
  393. return '';
  394. return $this->getOne("SELECT `messages` FROM `sys_agents_chat_history` WHERE `thread_id` = :t", [
  395. 't' => $sThreadId,
  396. ]);
  397. }
  398. public function getChatHistoryClosedReasonById($iHistoryId)
  399. {
  400. $iHistoryId = (int)$iHistoryId;
  401. if ($iHistoryId <= 0 || !$this->isFieldExists('sys_agents_chat_history', 'closed_reason'))
  402. return '';
  403. return (string)$this->getOne(
  404. "SELECT `closed_reason` FROM `sys_agents_chat_history` WHERE `id` = :id",
  405. ['id' => $iHistoryId]
  406. );
  407. }
  408. public function isNewChatSession($sThreadId)
  409. {
  410. $sThreadId = (string)$sThreadId;
  411. if ($sThreadId === '')
  412. return true;
  413. $aRow = $this->getRow("SELECT `ip`, `messages` FROM `sys_agents_chat_history` WHERE `thread_id` = :t", [
  414. 't' => $sThreadId,
  415. ]);
  416. if (!$aRow)
  417. return true;
  418. $iIp = (int)($aRow['ip'] ?? 0);
  419. $sMessages = trim((string)($aRow['messages'] ?? ''));
  420. return $iIp <= 0 || $sMessages === '' || $sMessages === '[]';
  421. }
  422. public function countChatSessionsByIp($sIp, $sPrefix, $iWindowSec)
  423. {
  424. $sSince = date('Y-m-d H:i:s', time() - (int)$iWindowSec);
  425. return (int)$this->getOne("
  426. SELECT COUNT(*) FROM `sys_agents_chat_history`
  427. WHERE `ip` = :ip
  428. AND (`thread_id` = :prefix OR `thread_id` LIKE :prefix_like)
  429. AND `created_at` >= :since
  430. ", [
  431. 'ip' => $sIp,
  432. 'prefix' => $sPrefix,
  433. 'prefix_like' => $sPrefix . ':%',
  434. 'since' => $sSince,
  435. ]);
  436. }
  437. public function getChatArtifactsByHistoryIds($aIds)
  438. {
  439. $aIds = array_values(array_unique(array_filter(array_map('intval', (array)$aIds))));
  440. if (!$aIds)
  441. return [];
  442. $sIn = implode(',', $aIds);
  443. $aRows = $this->getAll("
  444. SELECT `history_id`, `field_name`, `field_value`
  445. FROM `sys_agents_chat_artifacts`
  446. WHERE `history_id` IN ($sIn)
  447. ORDER BY `id` ASC
  448. ");
  449. return $this->mapChatArtifactRows($aRows);
  450. }
  451. public function getChatArtifactsByThreadId($sThreadId)
  452. {
  453. $sThreadId = (string)$sThreadId;
  454. if ($sThreadId === '')
  455. return [];
  456. $aRows = $this->getAll("
  457. SELECT `a`.`history_id`, `a`.`field_name`, `a`.`field_value`
  458. FROM `sys_agents_chat_artifacts` AS `a`
  459. INNER JOIN `sys_agents_chat_history` AS `h` ON `h`.`id` = `a`.`history_id`
  460. WHERE `h`.`thread_id` = :t
  461. ORDER BY `a`.`id` ASC
  462. ", [
  463. 't' => $sThreadId,
  464. ]);
  465. $aMap = $this->mapChatArtifactRows($aRows);
  466. if (!$aMap)
  467. return [];
  468. return (array)reset($aMap);
  469. }
  470. public function getChatArtifactsForAgent($aAgent)
  471. {
  472. $sExact = ($aAgent['trigger'] ?? '') . ':' . ($aAgent['id'] ?? '');
  473. if ($sExact === ':')
  474. return [];
  475. $aRows = $this->getAll("
  476. SELECT `a`.`history_id`, `a`.`field_name`, `a`.`field_value`
  477. FROM `sys_agents_chat_artifacts` AS `a`
  478. INNER JOIN `sys_agents_chat_history` AS `h` ON `h`.`id` = `a`.`history_id`
  479. WHERE `h`.`thread_id` = :exact OR `h`.`thread_id` LIKE :prefix
  480. ORDER BY `a`.`id` ASC
  481. ", [
  482. 'exact' => $sExact,
  483. 'prefix' => $sExact . ':%',
  484. ]);
  485. return $this->mapChatArtifactRows($aRows);
  486. }
  487. protected function mapChatArtifactRows($aRows)
  488. {
  489. if (!is_array($aRows) || !$aRows)
  490. return [];
  491. $aOut = [];
  492. foreach ($aRows as $aRow) {
  493. if (!is_array($aRow))
  494. continue;
  495. $iHistoryId = (int)($aRow['history_id'] ?? 0);
  496. $sName = trim((string)($aRow['field_name'] ?? ''));
  497. if ($iHistoryId <= 0 || $sName === '')
  498. continue;
  499. $aOut[$iHistoryId][] = [
  500. 'field_name' => $sName,
  501. 'field_value' => (string)($aRow['field_value'] ?? ''),
  502. ];
  503. }
  504. return $aOut;
  505. }
  506. public function getExpiredAgentChatHistoryIds($aAgent, $iTtlMin)
  507. {
  508. if (!$this->isFieldExists('sys_agents_chat_history', 'closed_reason'))
  509. return [];
  510. $sExact = ($aAgent['trigger'] ?? '') . ':' . ($aAgent['id'] ?? '');
  511. $iTtlMin = (int)$iTtlMin;
  512. if ($sExact === ':' || $iTtlMin <= 0)
  513. return [];
  514. return $this->getColumn("
  515. SELECT `id` FROM `sys_agents_chat_history`
  516. WHERE (`thread_id` = :exact OR `thread_id` LIKE :prefix)
  517. AND `messages` IS NOT NULL AND `messages` != '' AND `messages` != '[]'
  518. AND (`closed_reason` = '' OR `closed_reason` IS NULL)
  519. AND `updated_at` <= DATE_SUB(NOW(), INTERVAL :ttl MINUTE)
  520. ", [
  521. 'exact' => $sExact,
  522. 'prefix' => $sExact . ':%',
  523. 'ttl' => $iTtlMin,
  524. ]);
  525. }
  526. /**
  527. * Rename this agent's guest threads (`…:{sessionId}` or `…:{sessionId}#{chat}`) onto a profile id.
  528. * If the member thread already has messages, drop the guest copy.
  529. */
  530. public function adoptGuestChatHistory($aAgent, $sSessionId, $iProfileId)
  531. {
  532. $sSessionId = (string)$sSessionId;
  533. $iProfileId = (int)$iProfileId;
  534. if ($sSessionId === '' || !$iProfileId || empty($aAgent['id']))
  535. return 0;
  536. $sPrefix = $aAgent['trigger'] . ':' . $aAgent['id'] . ':';
  537. $aRows = $this->getAll("SELECT `id`, `thread_id`, `messages` FROM `sys_agents_chat_history` WHERE `thread_id` LIKE :p", [
  538. 'p' => $sPrefix . '%',
  539. ]);
  540. if (!is_array($aRows) || !$aRows)
  541. return 0;
  542. $iAffected = 0;
  543. foreach ($aRows as $aRow) {
  544. $sThreadId = (string)($aRow['thread_id'] ?? '');
  545. $aParsed = BxDolAiChat::parseThreadId($aAgent, $sThreadId);
  546. if (!$aParsed)
  547. continue;
  548. $sSub = (string)$aParsed['chat_history_subindex'];
  549. $sOwner = BxDolAiChat::chatHistoryOwnerFromSubindex($sSub);
  550. if ($sOwner !== $sSessionId)
  551. continue;
  552. $sConv = strlen($sSub) > strlen($sOwner) ? substr($sSub, strlen($sOwner)) : '';
  553. $sNewThread = BxDolAiChat::threadId($aAgent, [
  554. 'chat_history_context_pid' => (int)$aParsed['chat_history_context_pid'],
  555. 'chat_history_subindex' => $iProfileId . $sConv,
  556. ]);
  557. if ($sNewThread === '' || $sNewThread === $sThreadId)
  558. continue;
  559. $aMember = $this->getRow("SELECT `id`, `messages` FROM `sys_agents_chat_history` WHERE `thread_id` = :t", [
  560. 't' => $sNewThread,
  561. ]);
  562. $sGuestMsg = trim((string)($aRow['messages'] ?? ''));
  563. $bGuestHas = $sGuestMsg !== '' && $sGuestMsg !== '[]';
  564. $sMemberMsg = is_array($aMember) ? trim((string)($aMember['messages'] ?? '')) : '';
  565. $bMemberHas = $sMemberMsg !== '' && $sMemberMsg !== '[]';
  566. if ($bMemberHas) {
  567. $this->query("DELETE FROM `sys_agents_chat_history` WHERE `id` = :id", ['id' => (int)$aRow['id']]);
  568. continue;
  569. }
  570. if (is_array($aMember) && (int)($aMember['id'] ?? 0) > 0)
  571. $this->query("DELETE FROM `sys_agents_chat_history` WHERE `id` = :id", ['id' => (int)$aMember['id']]);
  572. if (!$bGuestHas && is_array($aMember))
  573. continue;
  574. $iAffected += (int)$this->query("UPDATE `sys_agents_chat_history` SET `thread_id` = :n WHERE `id` = :id", [
  575. 'n' => $sNewThread,
  576. 'id' => (int)$aRow['id'],
  577. ]);
  578. }
  579. return $iAffected;
  580. }
  581. static public function getAlert($s) {
  582. if (!$s)
  583. return false;
  584. $a = explode(':', $s);
  585. $oDb = BxDolDb::getInstance();
  586. return $oDb->getRow("SELECT * FROM `sys_alerts_log` WHERE `unit` = :unit AND `action` = :action", [
  587. 'unit' => $a[0] ?? '',
  588. 'action' => $a[1] ?? '',
  589. ]);
  590. }
  591. public function getAlerts()
  592. {
  593. $aValues = [];
  594. $aAlerts = $this->getAll("SELECT `unit`, `action`, `counter_24h`, `counter_per_request` FROM `sys_alerts_log` ORDER BY `unit`, `action`");
  595. foreach ($aAlerts as $a) {
  596. $sKey = $a['unit'] . ':' . $a['action'];
  597. $aValues[$sKey] = [
  598. 'key' => $sKey,
  599. 'unit' => $a['unit'],
  600. 'action' => $a['action'],
  601. 'name' => $a['unit'] . ' - ' . $a['action'],
  602. 'desc' => $this->getAlertDesc($a['unit'] . ':' . $a['action']),
  603. 'counter_24h' => $a['counter_24h'],
  604. 'counter_per_request' => $a['counter_per_request'],
  605. ];
  606. }
  607. return $aValues;
  608. }
  609. public function getFormDisplay($sObject)
  610. {
  611. $aDisplays = $this->getColumn("SELECT `display_name` FROM `sys_form_displays` WHERE `object` = :object", ['object' => $sObject]);
  612. return $aDisplays ? current($aDisplays) : null;
  613. }
  614. public function getFormObjects()
  615. {
  616. $aValues = [];
  617. $aForms = $this->getAll("SELECT `f`.`object`, `f`.`title`, `f`.`module`, `m`.`title` AS `module_title` FROM `sys_objects_form` AS f INNER JOIN `sys_modules` as `m` ON `m`.`name` = `f`.`module` ORDER BY `f`.`module`, `f`.`object` ASC");
  618. foreach ($aForms as $r) {
  619. if ('system' != $r['module']) {
  620. $oModule = BxDolModule::getInstance($r['module']);
  621. if (!$oModule || !$oModule->isEnabled())
  622. continue;
  623. }
  624. $sDisplay = $this->getFormDisplay($r['object']);
  625. if (!$sDisplay)
  626. continue;
  627. $oForm = BxDolForm::getObjectInstance($r['object'], $sDisplay);
  628. $sFormId = $oForm->getId();
  629. $aValues[$r['object']] = [
  630. 'form_id' => $sFormId,
  631. 'form_object' => $r['object'],
  632. 'module' => $r['module'],
  633. 'module_title' => $r['module_title'],
  634. 'form_title' => _t($r['title']),
  635. ];
  636. }
  637. return $aValues;
  638. }
  639. static public function getAlertDesc($sAlert)
  640. {
  641. if (!$sAlert)
  642. return '';
  643. $oDb = BxDolDb::getInstance();
  644. [$sUnit, $sAction] = explode(':', $sAlert);
  645. $sDesc = $oDb->getOne("SELECT `description` FROM `sys_alerts_desc` WHERE `unit` = :unit AND `action` = :action LIMIT 1", [
  646. 'unit' => $sUnit,
  647. 'action' => $sAction,
  648. ]);
  649. if (!$sDesc) {
  650. $sDesc = $oDb->getOne("SELECT `description` FROM `sys_alerts_desc` WHERE `unit` LIKE '{%}' AND `action` = :action LIMIT 1", [
  651. 'action' => $sAction,
  652. ]);
  653. }
  654. return $sDesc;
  655. }
  656. }
  657. /** @} */