BxDolAi.php 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  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 BxDolAi extends BxDolFactory implements iBxDolSingleton
  10. {
  11. protected $_oDb;
  12. protected $_iProfileId;
  13. protected $_aChatContext;
  14. protected function __construct()
  15. {
  16. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  17. trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
  18. parent::__construct();
  19. $this->_oDb = new BxDolAiQuery();
  20. $this->_iProfileId = (int)getParam('sys_profile_bot');
  21. $this->_aChatContext = null;
  22. }
  23. /**
  24. * Prevent cloning the instance
  25. */
  26. public function __clone()
  27. {
  28. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  29. trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
  30. }
  31. /**
  32. * Get singleton instance of the class
  33. */
  34. public static function getInstance()
  35. {
  36. if (!isset($GLOBALS['bxDolClasses'][__CLASS__])) {
  37. $GLOBALS['bxDolClasses'][__CLASS__] = BxDolDb::getInstance()->isTableExists('sys_agents_agents') ? new BxDolAi() : null;
  38. }
  39. return $GLOBALS['bxDolClasses'][__CLASS__];
  40. }
  41. public static function getAgentInstance(int $iId, array $aParams = []): NeuronAI\Agent\Agent
  42. {
  43. if (isset($GLOBALS['bxDolClasses'][__CLASS__ . '_Agent_' . $iId]))
  44. return $GLOBALS['bxDolClasses'][__CLASS__ . '_Agent_' . $iId];
  45. $a = BxDolAiQuery::getAgentObject($iId);
  46. if (!$a) {
  47. $s = "Agent with id {$iId} not found";
  48. bx_log('sys_agents', $s, BX_LOG_ERR);
  49. throw new Exception($s);
  50. }
  51. if (!$a['active']) {
  52. $s = "Agent with id {$iId} isn't active";
  53. bx_log('sys_agents', $s, BX_LOG_ERR);
  54. throw new Exception($s);
  55. }
  56. if (!$a['prompt_system'] || !$a['model_id']) {
  57. $s = "Agent with id {$iId} can't be used because it haven't prompt or AI model";
  58. bx_log('sys_agents', $s, BX_LOG_ERR);
  59. throw new Exception($s);
  60. }
  61. $o = BxDolAiAgent::make($a, $aParams);
  62. if ((int)$a['tools_max_run'] > 0)
  63. $o->toolMaxRuns($a['tools_max_run']);
  64. if ($a['vector_store_id']) {
  65. $aVectorStore = BxDolAiQuery::getVectorStoreObject($a['vector_store_id']);
  66. if ($aVectorStore && $aVectorStore['embedding_provider_id']) {
  67. $oEmbedder = self::getAiEmbeddingsProviderInstance($aVectorStore['embedding_provider_id']);
  68. $o->setEmbeddingsProvider($oEmbedder);
  69. }
  70. }
  71. $GLOBALS['bxDolClasses'][__CLASS__ . '_Agent_' . $iId] = $o;
  72. return $o;
  73. }
  74. public static function getAiProviderInstance(int $iId):NeuronAI\Providers\AIProviderInterface
  75. {
  76. return BxDolAIModelFactory::getModelInstance($iId);
  77. }
  78. public static function getAiEmbeddingsProviderInstance(int $iId):NeuronAI\RAG\Embeddings\EmbeddingsProviderInterface
  79. {
  80. return BxDolAIModelFactory::getModelInstance($iId);
  81. }
  82. public static function getDefaultModel()
  83. {
  84. return (int)getParam('sys_agents_model');
  85. }
  86. public function getProfileId()
  87. {
  88. return $this->_iProfileId;
  89. }
  90. public function getModels($aParams = [])
  91. {
  92. $aParamsDb = ['sample' => 'all_pairs'];
  93. if(isset($aParams['active']))
  94. $aParamsDb['active'] = $aParams['active'] === true ? 1 : 0;
  95. if(isset($aParams['capabilities']))
  96. $aParamsDb['capabilities'] = $aParams['capabilities'];
  97. return $this->_oDb->getModelsBy($aParamsDb);
  98. }
  99. public function callAgent($sType, $aAgent, $mixedParams = [])
  100. {
  101. return BxDolAiTrigger::getInstance($sType)->call($aAgent, $mixedParams);
  102. }
  103. public function setChatContext($aAgent, $aParams)
  104. {
  105. $this->_aChatContext = ['agent' => $aAgent, 'params' => $aParams];
  106. }
  107. /**
  108. * Whether the current (or given) member may interact with the agent
  109. * via chat, messenger, or form-input. Empty acl_levels means Nobody.
  110. * Site admins / Studio operators always may, so they can debug.
  111. */
  112. public function canInteract($aAgent, $iProfileId = false, $bAllowOperators = true)
  113. {
  114. if (!is_array($aAgent) || empty($aAgent['id']))
  115. return false;
  116. if ($bAllowOperators && isAdmin())
  117. return true;
  118. $iLevels = (int)($aAgent['acl_levels'] ?? 0);
  119. if (!$iLevels)
  120. return false;
  121. return (bool)BxDolAcl::getInstance()->isMemberLevelInSet($iLevels, $iProfileId);
  122. }
  123. /**
  124. * Direct HTTP chat (`sys-ai-chat`). Operators may talk to any trigger;
  125. * everyone else only `manual` and `message` agents they can interact with.
  126. */
  127. public function canChatDirectly($aAgent, $iProfileId = false)
  128. {
  129. if (!$this->canInteract($aAgent, $iProfileId))
  130. return false;
  131. if (isAdmin())
  132. return true;
  133. return in_array($aAgent['trigger'] ?? '', ['manual', 'message'], true);
  134. }
  135. /**
  136. * Runner limits from the agent row. 0 = no cap. Never put these in the prompt.
  137. */
  138. public function applyChatInputLimit($sPrompt, $aAgent)
  139. {
  140. $sPrompt = (string)$sPrompt;
  141. $iMax = (int)($aAgent['max_input_chars'] ?? 0);
  142. if ($iMax <= 0)
  143. return $sPrompt;
  144. if (function_exists('mb_strlen') && function_exists('mb_substr')) {
  145. if (mb_strlen($sPrompt, 'UTF-8') > $iMax)
  146. return mb_substr($sPrompt, 0, $iMax, 'UTF-8');
  147. return $sPrompt;
  148. }
  149. return strlen($sPrompt) > $iMax ? substr($sPrompt, 0, $iMax) : $sPrompt;
  150. }
  151. public function getChatLimitMessage($aAgent)
  152. {
  153. $s = trim((string)($aAgent['limit_message'] ?? ''));
  154. return $s !== '' ? $s : 'This chat has reached its limit.';
  155. }
  156. public function getChatSessionRateLimitError()
  157. {
  158. $s = _t('_sys_agents_err_session_rate_limit');
  159. return ($s !== '' && $s !== '_sys_agents_err_session_rate_limit')
  160. ? $s
  161. : 'Too many chat sessions from this IP. Try again later.';
  162. }
  163. public function countChatUserTurns($aUiMessages)
  164. {
  165. $i = 0;
  166. if (!is_array($aUiMessages))
  167. return 0;
  168. foreach ($aUiMessages as $aMessage) {
  169. if (is_array($aMessage) && ($aMessage['role'] ?? '') === 'user')
  170. $i++;
  171. }
  172. return $i;
  173. }
  174. public function isChatTurnLimitReached($aAgent, $iTurns, $iRequestUserTurns = 0)
  175. {
  176. $iMax = (int)($aAgent['max_turns'] ?? 0);
  177. if ($iMax <= 0)
  178. return false;
  179. if ((int)$iTurns >= $iMax)
  180. return true;
  181. // Client transcript includes the message being submitted.
  182. return (int)$iRequestUserTurns > $iMax;
  183. }
  184. public function getChatUserTurnCount($iAgentId, $aParams = [])
  185. {
  186. if (!isset($aParams['chat_history_subindex']))
  187. $aParams = array_merge($this->resolveChatHistoryParams($iAgentId), $aParams);
  188. try {
  189. $o = self::getAgentInstance((int)$iAgentId, $aParams);
  190. } catch (Throwable $oException) {
  191. return 0;
  192. }
  193. $i = 0;
  194. foreach ($o->getChatHistory()->getMessages() as $oMessage) {
  195. if ($oMessage instanceof NeuronAI\Chat\Messages\ToolCallMessage
  196. || $oMessage instanceof NeuronAI\Chat\Messages\ToolResultMessage
  197. ) {
  198. continue;
  199. }
  200. if ($oMessage instanceof NeuronAI\Chat\Messages\UserMessage)
  201. $i++;
  202. }
  203. return $i;
  204. }
  205. /**
  206. * New chat threads per IP for this agent. 0 on the agent = no cap.
  207. * Continuation of an existing thread is not a new session.
  208. */
  209. public function isChatSessionRateLimited($aAgent, $aParams = [])
  210. {
  211. $iHour = (int)($aAgent['max_sessions_per_hour'] ?? 0);
  212. $iDay = (int)($aAgent['max_sessions_per_day'] ?? 0);
  213. if ($iHour <= 0 && $iDay <= 0)
  214. return false;
  215. if (!isset($aParams['chat_history_subindex']))
  216. $aParams = array_merge($this->resolveChatHistoryParams((int)($aAgent['id'] ?? 0)), $aParams);
  217. $sThreadId = self::chatHistoryThreadId($aAgent, $aParams);
  218. if (!$this->isNewChatSession($sThreadId))
  219. return false;
  220. $sIp = $this->getVisitorIpHash();
  221. if ($sIp === '0' || $sIp === '')
  222. return false;
  223. $sPrefix = ($aAgent['trigger'] ?? '') . ':' . ($aAgent['id'] ?? '');
  224. if ($sPrefix === ':')
  225. return false;
  226. if ($iHour > 0 && $this->countChatSessionsByIp($sIp, $sPrefix, 3600) >= $iHour)
  227. return true;
  228. if ($iDay > 0 && $this->countChatSessionsByIp($sIp, $sPrefix, 86400) >= $iDay)
  229. return true;
  230. return false;
  231. }
  232. protected function getVisitorIpHash()
  233. {
  234. if (!function_exists('getVisitorIP') || !function_exists('bx_get_ip_hash'))
  235. return '0';
  236. return (string)bx_get_ip_hash(getVisitorIP());
  237. }
  238. protected function isNewChatSession($sThreadId)
  239. {
  240. $sThreadId = (string)$sThreadId;
  241. if ($sThreadId === '')
  242. return true;
  243. $aRow = $this->_oDb->getRow("SELECT `ip`, `messages` FROM `sys_agents_chat_history` WHERE `thread_id` = :t", [
  244. 't' => $sThreadId,
  245. ]);
  246. if (!$aRow)
  247. return true;
  248. $iIp = (int)($aRow['ip'] ?? 0);
  249. $sMessages = trim((string)($aRow['messages'] ?? ''));
  250. return $iIp <= 0 || $sMessages === '' || $sMessages === '[]';
  251. }
  252. protected function countChatSessionsByIp($sIp, $sPrefix, $iWindowSec)
  253. {
  254. $sSince = date('Y-m-d H:i:s', time() - (int)$iWindowSec);
  255. return (int)$this->_oDb->getOne("
  256. SELECT COUNT(*) FROM `sys_agents_chat_history`
  257. WHERE `ip` = :ip
  258. AND (`thread_id` = :prefix OR `thread_id` LIKE :prefix_like)
  259. AND `created_at` >= :since
  260. ", [
  261. 'ip' => $sIp,
  262. 'prefix' => $sPrefix,
  263. 'prefix_like' => $sPrefix . ':%',
  264. 'since' => $sSince,
  265. ]);
  266. }
  267. public function extractChatPromptFromRequest($aData)
  268. {
  269. return BxDolAiTrigger::getInstance('chat')->extractPromptFromRequest($aData);
  270. }
  271. /**
  272. * Guests: UNA session id. Members: profile id.
  273. * Guest chats remember agent ids in session so login can adopt those threads.
  274. */
  275. public function resolveChatHistoryParams($iAgentId = 0)
  276. {
  277. $iAgentId = (int)$iAgentId;
  278. $iProfileId = (int)bx_get_logged_profile_id();
  279. $oSession = BxDolSession::getInstance();
  280. $sSessionKey = 'ai_chat_agent_ids';
  281. if ($iProfileId) {
  282. $aIds = $oSession->getValue($sSessionKey);
  283. if (is_array($aIds) && $aIds) {
  284. $sSessionId = (string)$oSession->getId();
  285. if ($iAgentId)
  286. $aIds[] = $iAgentId;
  287. foreach (array_unique(array_map('intval', $aIds)) as $iStoredAgentId) {
  288. if (!$iStoredAgentId || $sSessionId === '')
  289. continue;
  290. $aAgent = BxDolAiQuery::getAgentObject($iStoredAgentId);
  291. if ($aAgent)
  292. $this->_oDb->adoptGuestChatHistory($aAgent, $sSessionId, $iProfileId);
  293. }
  294. $oSession->unsetValue($sSessionKey);
  295. }
  296. return [
  297. 'sender_profile_id' => $iProfileId,
  298. 'chat_history_subindex' => (string)$iProfileId,
  299. ];
  300. }
  301. if ($iAgentId) {
  302. $aIds = $oSession->getValue($sSessionKey);
  303. $aIds = array_map('intval', is_array($aIds) ? $aIds : []);
  304. if (!in_array($iAgentId, $aIds, true)) {
  305. $aIds[] = $iAgentId;
  306. $oSession->setValue($sSessionKey, $aIds);
  307. }
  308. }
  309. return [
  310. 'sender_profile_id' => 0,
  311. 'chat_history_subindex' => (string)$oSession->getId(),
  312. ];
  313. }
  314. /**
  315. * `{trigger}:{agentId}:{contextPid}:{userSubindex}`.
  316. * Context is omitted when 0 so existing site-wide threads still load.
  317. * User suffix (session id or profile id) stays last so adopt can replace it.
  318. */
  319. public static function chatHistoryThreadId($aAgent, $aParams = [])
  320. {
  321. $s = ($aAgent['trigger'] ?? '') . ':' . ($aAgent['id'] ?? '');
  322. $iContextPid = (int)($aParams['chat_history_context_pid'] ?? 0);
  323. if ($iContextPid > 0)
  324. $s .= ':' . $iContextPid;
  325. if (isset($aParams['chat_history_subindex']) && $aParams['chat_history_subindex'] !== '')
  326. $s .= ':' . (string)$aParams['chat_history_subindex'];
  327. return $s;
  328. }
  329. public function getChatHistoryRowId($aAgent, $aParams = [])
  330. {
  331. $sThreadId = self::chatHistoryThreadId($aAgent, $aParams);
  332. if ($sThreadId === '' || $sThreadId === ':')
  333. return 0;
  334. return (int)$this->_oDb->getOne("SELECT `id` FROM `sys_agents_chat_history` WHERE `thread_id` = :t", [
  335. 't' => $sThreadId,
  336. ]);
  337. }
  338. public function getCurrentChatHistoryId()
  339. {
  340. if (!is_array($this->_aChatContext))
  341. return 0;
  342. $aAgent = $this->_aChatContext['agent'] ?? null;
  343. $aParams = $this->_aChatContext['params'] ?? [];
  344. if (!is_array($aAgent))
  345. return 0;
  346. return $this->getChatHistoryRowId($aAgent, is_array($aParams) ? $aParams : []);
  347. }
  348. public function emitConversationClosed($sReason, $sSummary = '', $aAgent = null, $aParams = null)
  349. {
  350. if (!is_array($aAgent) && is_array($this->_aChatContext))
  351. $aAgent = $this->_aChatContext['agent'] ?? null;
  352. if (!is_array($aParams) && is_array($this->_aChatContext))
  353. $aParams = $this->_aChatContext['params'] ?? [];
  354. if (!is_array($aAgent) || empty($aAgent['id']))
  355. return false;
  356. $iHistoryId = $this->getChatHistoryRowId($aAgent, is_array($aParams) ? $aParams : []);
  357. if ($iHistoryId <= 0)
  358. return false;
  359. if ($this->_oDb->isFieldExists('sys_agents_chat_history', 'closed_reason')) {
  360. $sClosed = (string)$this->_oDb->getOne(
  361. "SELECT `closed_reason` FROM `sys_agents_chat_history` WHERE `id` = :id",
  362. ['id' => $iHistoryId]
  363. );
  364. if ($sClosed !== '')
  365. return false;
  366. }
  367. bx_alert('system', 'agent_conversation_closed', $iHistoryId, 0, [
  368. 'agent_id' => (int)$aAgent['id'],
  369. 'summary' => (string)$sSummary,
  370. 'reason' => (string)$sReason,
  371. ]);
  372. return true;
  373. }
  374. /**
  375. * @return array{thread_id:string,chat_history_context_pid:int,chat_history_subindex:string}|false
  376. */
  377. public static function parseChatHistoryThreadId($aAgent, $sThreadId)
  378. {
  379. $sThreadId = (string)$sThreadId;
  380. $sBase = ($aAgent['trigger'] ?? '') . ':' . ($aAgent['id'] ?? '');
  381. if ($sBase === ':' || $sThreadId === '')
  382. return false;
  383. if ($sThreadId !== $sBase && strpos($sThreadId, $sBase . ':') !== 0)
  384. return false;
  385. $sRest = $sThreadId === $sBase ? '' : substr($sThreadId, strlen($sBase) + 1);
  386. $aParts = $sRest === '' ? [] : explode(':', $sRest);
  387. $iContext = 0;
  388. $sSub = '';
  389. if (count($aParts) >= 2) {
  390. $iContext = (int)$aParts[0];
  391. $sSub = implode(':', array_slice($aParts, 1));
  392. } elseif (count($aParts) === 1) {
  393. $sSub = $aParts[0];
  394. }
  395. return [
  396. 'thread_id' => $sThreadId,
  397. 'chat_history_context_pid' => $iContext,
  398. 'chat_history_subindex' => $sSub,
  399. ];
  400. }
  401. public function isOwnAgentChatThread($aAgent, $sThreadId)
  402. {
  403. $aParsed = self::parseChatHistoryThreadId($aAgent, $sThreadId);
  404. if (!$aParsed)
  405. return false;
  406. $aMine = $this->resolveChatHistoryParams((int)$aAgent['id']);
  407. $sMine = (string)($aMine['chat_history_subindex'] ?? '');
  408. return $sMine !== '' && $aParsed['chat_history_subindex'] === $sMine;
  409. }
  410. public function storedChatJsonToUiMessages($sJson)
  411. {
  412. $aStored = json_decode((string)$sJson, true);
  413. if (!is_array($aStored) || $aStored === [])
  414. return [];
  415. $aResult = [];
  416. $i = 0;
  417. foreach ($aStored as $aMessage) {
  418. if (!is_array($aMessage))
  419. continue;
  420. $sType = (string)($aMessage['type'] ?? '');
  421. if ($sType === 'tool_call' || $sType === 'tool_call_result')
  422. continue;
  423. $sRole = (string)($aMessage['role'] ?? '');
  424. if ($sRole === 'model')
  425. $sRole = 'assistant';
  426. if ($sRole !== 'user' && $sRole !== 'assistant')
  427. continue;
  428. $aParts = [];
  429. $mixedContent = $aMessage['content'] ?? '';
  430. if (is_string($mixedContent) && $mixedContent !== '') {
  431. $aParts[] = ['type' => 'text', 'content' => $mixedContent];
  432. } elseif (is_array($mixedContent)) {
  433. foreach ($mixedContent as $aBlock) {
  434. if (!is_array($aBlock))
  435. continue;
  436. $sBlockType = (string)($aBlock['type'] ?? '');
  437. $sBlockText = (string)($aBlock['content'] ?? '');
  438. if ($sBlockText === '')
  439. continue;
  440. if ($sBlockType === 'text' || $sBlockType === '')
  441. $aParts[] = ['type' => 'text', 'content' => $sBlockText];
  442. }
  443. }
  444. $sId = '';
  445. if (!empty($aMessage['__id']) && is_string($aMessage['__id']))
  446. $sId = $aMessage['__id'];
  447. elseif (!empty($aMessage['metadata']['__id']) && is_string($aMessage['metadata']['__id']))
  448. $sId = $aMessage['metadata']['__id'];
  449. $mixedActions = $aMessage['actions'] ?? ($aMessage['metadata']['actions'] ?? null);
  450. $aUi = $this->finalizeUiChatMessage($sId !== '' ? $sId : ('msg_' . $i), $sRole, $aParts, $mixedActions);
  451. if (!$aUi)
  452. continue;
  453. $aResult[] = $aUi;
  454. $i++;
  455. }
  456. return $aResult;
  457. }
  458. public function getChatHistoryUiMessagesByThread($aAgent, $sThreadId)
  459. {
  460. if (!self::parseChatHistoryThreadId($aAgent, $sThreadId))
  461. return false;
  462. $sJson = $this->_oDb->getOne("SELECT `messages` FROM `sys_agents_chat_history` WHERE `thread_id` = :t", [
  463. 't' => (string)$sThreadId,
  464. ]);
  465. return $this->storedChatJsonToUiMessages($sJson);
  466. }
  467. public function getChatHistoryArtifactsByThread($aAgent, $sThreadId)
  468. {
  469. if (!self::parseChatHistoryThreadId($aAgent, $sThreadId))
  470. return [];
  471. return $this->_oDb->getChatArtifactsByThreadId((string)$sThreadId);
  472. }
  473. public function listAgentChatThreads($aAgent)
  474. {
  475. $aMineParams = $this->resolveChatHistoryParams((int)$aAgent['id']);
  476. $sMySub = (string)($aMineParams['chat_history_subindex'] ?? '');
  477. $sMyDefault = self::chatHistoryThreadId($aAgent, $aMineParams);
  478. $aOut = [];
  479. $bHaveMineDefault = false;
  480. $aRows = $this->_oDb->getAgentChatHistoryRows($aAgent);
  481. if (!is_array($aRows))
  482. $aRows = [];
  483. $aHistoryIds = [];
  484. foreach ($aRows as $aRow)
  485. $aHistoryIds[] = (int)($aRow['id'] ?? 0);
  486. $aArtifactsMap = $this->_oDb->getChatArtifactsForAgent($aAgent);
  487. if (!$aArtifactsMap && $aHistoryIds)
  488. $aArtifactsMap = $this->_oDb->getChatArtifactsByHistoryIds($aHistoryIds);
  489. foreach ($aRows as $aRow) {
  490. $sThreadId = (string)($aRow['thread_id'] ?? '');
  491. $aParsed = self::parseChatHistoryThreadId($aAgent, $sThreadId);
  492. if (!$aParsed)
  493. continue;
  494. $aUi = $this->storedChatJsonToUiMessages($aRow['messages'] ?? '');
  495. if (!$aUi && $sThreadId !== $sMyDefault)
  496. continue;
  497. $bMine = ($sMySub !== '' && $aParsed['chat_history_subindex'] === $sMySub);
  498. if ($sThreadId === $sMyDefault)
  499. $bHaveMineDefault = true;
  500. $iHistoryId = (int)($aRow['id'] ?? 0);
  501. $aArtifacts = ($iHistoryId && !empty($aArtifactsMap[$iHistoryId])) ? $aArtifactsMap[$iHistoryId] : [];
  502. $aOut[] = $this->formatAgentChatThread($aParsed, $aRow, $aUi, $bMine, $aArtifacts);
  503. }
  504. if (!$bHaveMineDefault && $sMyDefault !== '') {
  505. $aParsedMine = self::parseChatHistoryThreadId($aAgent, $sMyDefault);
  506. if ($aParsedMine)
  507. $aOut[] = $this->formatAgentChatThread($aParsedMine, [], [], true);
  508. }
  509. usort($aOut, function ($a, $b) {
  510. return strcmp((string)$b['updated_sort'], (string)$a['updated_sort']);
  511. });
  512. return $aOut;
  513. }
  514. protected function formatAgentChatThread($aParsed, $aRow, $aUi, $bMine, $aArtifacts = [])
  515. {
  516. $iContext = (int)$aParsed['chat_history_context_pid'];
  517. $sSub = (string)$aParsed['chat_history_subindex'];
  518. $sContextName = '';
  519. if ($iContext > 0) {
  520. $oContext = BxDolProfile::getInstance($iContext);
  521. $sContextName = $oContext ? $oContext->getDisplayName() : ('#' . $iContext);
  522. }
  523. $sTitle = _t('_sys_agents_agents_txt_guest_chat');
  524. $oProfile = (ctype_digit($sSub) && (int)$sSub > 0) ? BxDolProfile::getInstance((int)$sSub) : false;
  525. if ($oProfile)
  526. $sTitle = $oProfile->getDisplayName();
  527. if ($sContextName !== '')
  528. $sTitle .= ' · ' . $sContextName;
  529. $sReason = trim((string)($aRow['closed_reason'] ?? ''));
  530. $sStatus = $sReason !== '' ? 'closed' : 'opened';
  531. $sStatusLabel = $sStatus;
  532. if ($sStatus === 'closed' && $sReason !== '')
  533. $sStatusLabel .= ' (' . $sReason . ')';
  534. $aArtifacts = is_array($aArtifacts) ? $aArtifacts : [];
  535. $sCreated = $this->formatAgentChatThreadTime($aRow['created_at'] ?? '');
  536. $sUpdated = $this->formatAgentChatThreadTime($aRow['updated_at'] ?? '');
  537. $sUpdatedRaw = (string)($aRow['updated_at'] ?? '');
  538. $sMeta = 'status: ' . $sStatusLabel;
  539. $sDates = '';
  540. if ($sCreated !== '' && $sUpdated !== '')
  541. $sDates = $sCreated . ' - ' . $sUpdated;
  542. else if ($sCreated !== '')
  543. $sDates = $sCreated;
  544. else if ($sUpdated !== '')
  545. $sDates = $sUpdated;
  546. if ($sDates !== '')
  547. $sMeta .= "\n" . $sDates;
  548. return [
  549. 'thread_id' => $aParsed['thread_id'],
  550. 'writable' => $bMine ? 1 : 0,
  551. 'context_pid' => $iContext,
  552. 'title' => $sTitle,
  553. 'meta' => $sMeta,
  554. 'status' => $sStatus,
  555. 'closed_reason' => $sReason,
  556. 'created_at' => $sCreated,
  557. 'updated_at' => $sUpdated,
  558. 'artifacts' => is_array($aArtifacts) ? $aArtifacts : [],
  559. 'updated_sort' => $sUpdatedRaw,
  560. 'class_mine' => $bMine ? ' bx-agents-popup-chat-thread-mine' : '',
  561. ];
  562. }
  563. protected function formatAgentChatThreadTime($mixed): string
  564. {
  565. $s = trim((string)$mixed);
  566. if ($s === '' || $s === '0')
  567. return '';
  568. $i = ctype_digit($s) ? (int)$s : (int)strtotime($s);
  569. if ($i <= 86400)
  570. return '';
  571. return date('d.m.Y H:i', $i);
  572. }
  573. /**
  574. * Context from chat HTTP (`?context=`). Missing/0 = site-wide. Invalid/denied = false (403).
  575. * Posting in a group is not the same as viewing it; chat requires post by default.
  576. * @return int|false
  577. */
  578. public function resolveChatHistoryContextPid($bRequirePost = true)
  579. {
  580. $mixed = bx_get('context');
  581. if ($mixed === false)
  582. return 0;
  583. $iPid = (int)$mixed;
  584. if ($iPid <= 0)
  585. return 0;
  586. $oProfile = BxDolProfile::getInstance($iPid);
  587. if (!$oProfile || !bx_srv('system', 'is_module_context', [$oProfile->getModule()]))
  588. return false;
  589. if (!$this->isAllowedContextChat($oProfile, $bRequirePost))
  590. return false;
  591. return $iPid;
  592. }
  593. /**
  594. * Context of the current page (AI agent block).
  595. * `bx_get_page_info()` reads the URL; App page JSON merges `i`/`id` into $_GET instead.
  596. * @param bool $bRequirePost also require posting into the context (membership / post ACL)
  597. */
  598. public function resolveChatHistoryContextPidFromPage($bRequirePost = false)
  599. {
  600. $aInfo = bx_get_page_info();
  601. if ($aInfo && !empty($aInfo['context_profile_id']))
  602. return $this->filterContextPid((int)$aInfo['context_profile_id'], $bRequirePost);
  603. $sUri = bx_get('i');
  604. $iContentId = (int)bx_process_input(bx_get('id'), BX_DATA_INT);
  605. if ($sUri && $iContentId > 0) {
  606. $oPage = BxDolPage::getObjectInstanceByURI($sUri);
  607. $sModule = $oPage ? (string)$oPage->getModule() : '';
  608. if ($sModule !== '' && bx_srv('system', 'is_module_context', [$sModule])) {
  609. $oProfile = BxDolProfile::getInstanceByContentAndType($iContentId, $sModule);
  610. if ($oProfile && ($iPid = $this->filterContextPid((int)$oProfile->id(), $bRequirePost)))
  611. return $iPid;
  612. }
  613. }
  614. $iPid = (int)bx_process_input(bx_get('profile_id'), BX_DATA_INT);
  615. if ($iPid > 0 && ($iPid = $this->filterContextPid($iPid, $bRequirePost)))
  616. return $iPid;
  617. return 0;
  618. }
  619. public function filterContextPid($iPid, $bRequirePost = false)
  620. {
  621. $iPid = (int)$iPid;
  622. if ($iPid <= 0)
  623. return 0;
  624. $oProfile = BxDolProfile::getInstance($iPid);
  625. if (!$oProfile || !bx_srv('system', 'is_module_context', [$oProfile->getModule()]))
  626. return 0;
  627. if (!$this->isAllowedContextChat($oProfile, $bRequirePost))
  628. return 0;
  629. return $iPid;
  630. }
  631. protected function isAllowedContextChat($oProfile, $bRequirePost = false)
  632. {
  633. if ($oProfile->checkAllowedProfileView() !== CHECK_ACTION_RESULT_ALLOWED)
  634. return false;
  635. if ($bRequirePost && $oProfile->checkAllowedPostInProfile() !== CHECK_ACTION_RESULT_ALLOWED)
  636. return false;
  637. return true;
  638. }
  639. /**
  640. * Transcript for TanStack `useChat` hydrate / `initialMessages`.
  641. * Loads the same NeuronAI chat history the agent uses when streaming.
  642. *
  643. * @param bool $bAppendLimitMessage when the session is at max_turns, append limit_message for the UI
  644. */
  645. public function getChatHistoryUiMessages($iAgentId, $aParams = [], $bAppendLimitMessage = true)
  646. {
  647. if (!isset($aParams['chat_history_subindex']))
  648. $aParams = array_merge($this->resolveChatHistoryParams($iAgentId), $aParams);
  649. $aAgent = BxDolAiQuery::getAgentObject((int)$iAgentId);
  650. if (!$aAgent || empty($aAgent['chat_history_context']))
  651. return [];
  652. $sThreadId = self::chatHistoryThreadId($aAgent, $aParams);
  653. $sJson = $this->_oDb->getOne("SELECT `messages` FROM `sys_agents_chat_history` WHERE `thread_id` = :t", [
  654. 't' => $sThreadId,
  655. ]);
  656. $aStored = json_decode((string)$sJson, true);
  657. if (!is_array($aStored) || $aStored === [])
  658. return [];
  659. try {
  660. $o = self::getAgentInstance((int)$iAgentId, $aParams);
  661. } catch (Exception $oException) {
  662. bx_log('sys_agents', "Hydrate exception for agent {$iAgentId}: " . $oException->getMessage(), BX_LOG_ERR);
  663. return [];
  664. }
  665. $aResult = $this->neuronMessagesToUiMessages($o->getChatHistory()->getMessages());
  666. if ($bAppendLimitMessage && $this->isChatTurnLimitReached($aAgent, $this->countChatUserTurns($aResult))) {
  667. $aResult[] = [
  668. 'id' => 'agent_limit_message',
  669. 'role' => 'assistant',
  670. 'parts' => [['type' => 'text', 'content' => $this->getChatLimitMessage($aAgent)]],
  671. ];
  672. }
  673. return $aResult;
  674. }
  675. /**
  676. * @param NeuronAI\Chat\Messages\Message[] $aMessages
  677. * @return array<int, array<string, mixed>>
  678. */
  679. protected function neuronMessagesToUiMessages($aMessages)
  680. {
  681. $aResult = [];
  682. $i = 0;
  683. foreach ($aMessages as $oMessage) {
  684. if (
  685. $oMessage instanceof NeuronAI\Chat\Messages\ToolCallMessage
  686. || $oMessage instanceof NeuronAI\Chat\Messages\ToolResultMessage
  687. ) {
  688. continue;
  689. }
  690. $sRole = $oMessage->getRole();
  691. if ($sRole === 'model')
  692. $sRole = 'assistant';
  693. if ($sRole !== 'user' && $sRole !== 'assistant')
  694. continue;
  695. $aParts = [];
  696. foreach ($oMessage->getContentBlocks() as $oBlock) {
  697. if ($oBlock instanceof NeuronAI\Chat\Messages\ContentBlocks\ReasoningContent) {
  698. if ($oBlock->content !== '')
  699. $aParts[] = ['type' => 'thinking', 'content' => $oBlock->content];
  700. continue;
  701. }
  702. if ($oBlock instanceof NeuronAI\Chat\Messages\ContentBlocks\TextContent && $oBlock->content !== '')
  703. $aParts[] = ['type' => 'text', 'content' => $oBlock->content];
  704. }
  705. $sId = $oMessage->getMetadata('__id');
  706. $aUi = $this->finalizeUiChatMessage(
  707. is_string($sId) && $sId !== '' ? $sId : ('msg_' . $i),
  708. $sRole,
  709. $aParts,
  710. $sRole === 'assistant' ? $oMessage->getMetadata('actions') : null
  711. );
  712. if (!$aUi)
  713. continue;
  714. $aResult[] = $aUi;
  715. $i++;
  716. }
  717. return $aResult;
  718. }
  719. /**
  720. * Split assistant JSON {content, actions} into UI text + actions.
  721. * User messages pass through unchanged.
  722. *
  723. * @param array<int, array<string, mixed>> $aParts
  724. * @return array<string, mixed>|null
  725. */
  726. protected function finalizeUiChatMessage($sId, $sRole, $aParts, $mixedActions = null)
  727. {
  728. $aActions = $sRole === 'assistant' ? $this->sanitizeChatActions($mixedActions) : [];
  729. if ($sRole === 'assistant') {
  730. $sText = '';
  731. foreach ($aParts as $aPart) {
  732. if (($aPart['type'] ?? '') === 'text')
  733. $sText .= (string)($aPart['content'] ?? '');
  734. }
  735. $aParsed = $this->parseAssistantChatPayload($sText);
  736. if ($aParsed) {
  737. $aKept = [];
  738. foreach ($aParts as $aPart) {
  739. if (($aPart['type'] ?? '') === 'text')
  740. continue;
  741. $aKept[] = $aPart;
  742. }
  743. if ($aParsed['content'] !== '')
  744. $aKept[] = ['type' => 'text', 'content' => $aParsed['content']];
  745. $aParts = $aKept;
  746. if (!$aActions)
  747. $aActions = $aParsed['actions'];
  748. }
  749. }
  750. if (!$aParts && !$aActions)
  751. return null;
  752. $aOut = [
  753. 'id' => $sId,
  754. 'role' => $sRole,
  755. 'parts' => $aParts,
  756. ];
  757. if ($sRole === 'assistant')
  758. $aOut['actions'] = $aActions;
  759. return $aOut;
  760. }
  761. /**
  762. * @return array{content: string, actions: array}|null
  763. */
  764. public function parseAssistantChatPayload($sText)
  765. {
  766. $s = trim((string)$sText);
  767. if ($s === '')
  768. return null;
  769. if (preg_match('/^```(?:json)?\s*(\{.*\})\s*```$/s', $s, $aM))
  770. $s = trim($aM[1]);
  771. if ($s === '' || $s[0] !== '{') {
  772. $iStart = strpos($s, '{');
  773. $iEnd = strrpos($s, '}');
  774. if ($iStart === false || $iEnd === false || $iEnd <= $iStart)
  775. return null;
  776. $s = substr($s, $iStart, $iEnd - $iStart + 1);
  777. }
  778. $a = json_decode($s, true);
  779. if (!is_array($a) || !array_key_exists('content', $a) || !is_string($a['content']))
  780. return null;
  781. if (!array_key_exists('actions', $a))
  782. return null;
  783. return [
  784. 'content' => $a['content'],
  785. 'actions' => $this->sanitizeChatActions($a['actions']),
  786. ];
  787. }
  788. /**
  789. * @return array<int, array<string, mixed>>
  790. */
  791. protected function sanitizeChatActions($mixed)
  792. {
  793. if (!is_array($mixed))
  794. return [];
  795. $aOut = [];
  796. foreach ($mixed as $aItem) {
  797. if (!is_array($aItem))
  798. continue;
  799. $sType = strtolower(trim((string)($aItem['type'] ?? '')));
  800. $sLabel = trim((string)($aItem['label'] ?? ''));
  801. if ($sLabel === '')
  802. continue;
  803. if (function_exists('mb_substr'))
  804. $sLabel = mb_substr($sLabel, 0, 80);
  805. else
  806. $sLabel = substr($sLabel, 0, 80);
  807. if ($sType === 'reply') {
  808. $aOut[] = ['type' => 'reply', 'label' => $sLabel];
  809. } elseif ($sType === 'link') {
  810. $sUrl = trim((string)($aItem['url'] ?? ''));
  811. if (!$this->isAllowedChatActionUrl($sUrl))
  812. continue;
  813. $aOut[] = ['type' => 'link', 'label' => $sLabel, 'url' => $sUrl];
  814. }
  815. if (count($aOut) >= 8)
  816. break;
  817. }
  818. return $aOut;
  819. }
  820. protected function isAllowedChatActionUrl($sUrl)
  821. {
  822. $a = parse_url((string)$sUrl);
  823. if (($a['scheme'] ?? '') !== 'https' || empty($a['host']))
  824. return false;
  825. $sHost = strtolower((string)$a['host']);
  826. $aAllowed = ['hiweave.com', 'www.hiweave.com'];
  827. if (defined('BX_DOL_URL_ROOT')) {
  828. $aSite = parse_url(BX_DOL_URL_ROOT);
  829. if (!empty($aSite['host']))
  830. $aAllowed[] = strtolower((string)$aSite['host']);
  831. }
  832. return in_array($sHost, $aAllowed, true);
  833. }
  834. public function streamAgentChat($iAgentId, $sPrompt, $aParams = [], $sThreadId = null)
  835. {
  836. return BxDolAiTrigger::getInstance('chat')->stream($iAgentId, $sPrompt, $aParams, $sThreadId);
  837. }
  838. public function sendMessengerMessage($iSender, $iRecipient, $sMsg)
  839. {
  840. return BxDolAiTrigger::getInstance('message')->sendMessengerMessage($iSender, $iRecipient, $sMsg);
  841. }
  842. public function getAgentsByAlertUnitAndAction($sUnit, $sAction)
  843. {
  844. return BxDolAiTrigger::getInstance('alert')->getAgentsByUnitAndAction($sUnit, $sAction);
  845. }
  846. public function getAgentsBy($aParams)
  847. {
  848. return $this->_oDb->getAgentsBy($aParams);
  849. }
  850. public function getAgentsByProfileId($iProfileId)
  851. {
  852. return BxDolAiTrigger::getInstance('message')->getAgentsByProfileId($iProfileId);
  853. }
  854. public function getAgentsByFormObject($sFormObject)
  855. {
  856. return $this->_oDb->getAgentsByFormObject($sFormObject);
  857. }
  858. public function getAgentsByTriggerType($sTrigger)
  859. {
  860. return $this->_oDb->getAgentsByTriggerType($sTrigger);
  861. }
  862. public function getAgentByTriggerWebhookKey($sKey)
  863. {
  864. return BxDolAiTrigger::getInstance('webhook')->getAgentByKey($sKey);
  865. }
  866. }
  867. /** @} */