1
0

BxDolAiChat.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  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 BxDolAiChat
  10. {
  11. protected $_oDb;
  12. protected $_oUi;
  13. protected $_aChatContext;
  14. /**
  15. * Buttons queued by the `chat_buttons` tool during the current turn. The chat
  16. * trigger emits them after the assistant text and pins them to the stored message.
  17. */
  18. protected $_aPendingChatActions = [];
  19. /**
  20. * The assistant already wrote visible text this turn: `chat_buttons` refuses
  21. * to hang buttons on an empty reply.
  22. */
  23. protected $_bTurnHasText = false;
  24. public static function getInstance()
  25. {
  26. if (!isset($GLOBALS['bxDolClasses'][__CLASS__]))
  27. $GLOBALS['bxDolClasses'][__CLASS__] = new self();
  28. return $GLOBALS['bxDolClasses'][__CLASS__];
  29. }
  30. public function __construct()
  31. {
  32. $this->_oDb = new BxDolAiQuery();
  33. $this->_oUi = BxDolAiChatUi::getInstance();
  34. $this->_aChatContext = null;
  35. $this->_aPendingChatActions = [];
  36. }
  37. public function setChatContext($aAgent, $aParams)
  38. {
  39. $this->_aChatContext = ['agent' => $aAgent, 'params' => $aParams];
  40. }
  41. /**
  42. * Optional `?chat=` partition. Not identity — owner stays profile id / session id.
  43. * `{owner}#{chat}` so parseThreadId does not treat the nonce as a context pid.
  44. */
  45. public static function sanitizeChatQueryId($s)
  46. {
  47. $s = is_string($s) ? $s : '';
  48. $s = preg_replace('/[^A-Za-z0-9_-]/', '', $s);
  49. $s = substr($s, 0, 64);
  50. return strlen($s) >= 8 ? $s : '';
  51. }
  52. /**
  53. * Owner (profile id or guest session id) of a `{owner}` / `{owner}#{chat}` subindex.
  54. */
  55. public static function chatHistoryOwnerFromSubindex($sSub)
  56. {
  57. $sSub = (string)$sSub;
  58. if ($sSub === '')
  59. return '';
  60. $i = strpos($sSub, '#');
  61. return $i === false ? $sSub : substr($sSub, 0, $i);
  62. }
  63. /**
  64. * Guests: UNA session id. Members: profile id.
  65. * Guest chats remember agent ids in session so login can adopt those threads.
  66. * `?chat=` appends a conversation id without changing the owner.
  67. */
  68. public function resolveChatHistoryParams($iAgentId = 0)
  69. {
  70. $iAgentId = (int)$iAgentId;
  71. $iProfileId = (int)bx_get_logged_profile_id();
  72. $oSession = BxDolSession::getInstance();
  73. $sSessionKey = 'ai_chat_agent_ids';
  74. $sChat = self::sanitizeChatQueryId(bx_get('chat'));
  75. if ($iProfileId) {
  76. $aIds = $oSession->getValue($sSessionKey);
  77. if (is_array($aIds) && $aIds) {
  78. $sSessionId = (string)$oSession->getId();
  79. if ($iAgentId)
  80. $aIds[] = $iAgentId;
  81. foreach (array_unique(array_map('intval', $aIds)) as $iStoredAgentId) {
  82. if (!$iStoredAgentId || $sSessionId === '')
  83. continue;
  84. $aAgent = BxDolAiQuery::getAgentObject($iStoredAgentId);
  85. if ($aAgent)
  86. $this->_oDb->adoptGuestChatHistory($aAgent, $sSessionId, $iProfileId);
  87. }
  88. $oSession->unsetValue($sSessionKey);
  89. }
  90. $sOwner = (string)$iProfileId;
  91. return [
  92. 'sender_profile_id' => $iProfileId,
  93. 'chat_history_subindex' => $sChat !== '' ? ($sOwner . '#' . $sChat) : $sOwner,
  94. ];
  95. }
  96. if ($iAgentId) {
  97. $aIds = $oSession->getValue($sSessionKey);
  98. $aIds = array_map('intval', is_array($aIds) ? $aIds : []);
  99. if (!in_array($iAgentId, $aIds, true)) {
  100. $aIds[] = $iAgentId;
  101. $oSession->setValue($sSessionKey, $aIds);
  102. }
  103. }
  104. $sOwner = (string)$oSession->getId();
  105. return [
  106. 'sender_profile_id' => 0,
  107. 'chat_history_subindex' => $sChat !== '' ? ($sOwner . '#' . $sChat) : $sOwner,
  108. ];
  109. }
  110. /**
  111. * `{trigger}:{agentId}:{contextPid}:{userSubindex}`.
  112. * Context is omitted when 0 so existing site-wide threads still load.
  113. * User suffix (session id or profile id, optionally `#{chat}`) stays last so adopt can replace it.
  114. */
  115. public static function threadId($aAgent, $aParams = [])
  116. {
  117. $s = ($aAgent['trigger'] ?? '') . ':' . ($aAgent['id'] ?? '');
  118. $iContextPid = (int)($aParams['chat_history_context_pid'] ?? 0);
  119. if ($iContextPid > 0)
  120. $s .= ':' . $iContextPid;
  121. if (isset($aParams['chat_history_subindex']) && $aParams['chat_history_subindex'] !== '')
  122. $s .= ':' . (string)$aParams['chat_history_subindex'];
  123. return $s;
  124. }
  125. /**
  126. * @return array{thread_id:string,chat_history_context_pid:int,chat_history_subindex:string}|false
  127. */
  128. public static function parseThreadId($aAgent, $sThreadId)
  129. {
  130. $sThreadId = (string)$sThreadId;
  131. $sBase = ($aAgent['trigger'] ?? '') . ':' . ($aAgent['id'] ?? '');
  132. if ($sBase === ':' || $sThreadId === '')
  133. return false;
  134. if ($sThreadId !== $sBase && strpos($sThreadId, $sBase . ':') !== 0)
  135. return false;
  136. $sRest = $sThreadId === $sBase ? '' : substr($sThreadId, strlen($sBase) + 1);
  137. $aParts = $sRest === '' ? [] : explode(':', $sRest);
  138. $iContext = 0;
  139. $sSub = '';
  140. if (count($aParts) >= 2) {
  141. $iContext = (int)$aParts[0];
  142. $sSub = implode(':', array_slice($aParts, 1));
  143. } elseif (count($aParts) === 1) {
  144. $sSub = $aParts[0];
  145. }
  146. return [
  147. 'thread_id' => $sThreadId,
  148. 'chat_history_context_pid' => $iContext,
  149. 'chat_history_subindex' => $sSub,
  150. ];
  151. }
  152. public function getChatHistoryRowId($aAgent, $aParams = [])
  153. {
  154. return $this->_oDb->getChatHistoryIdByThreadId(self::threadId($aAgent, $aParams));
  155. }
  156. public function getCurrentChatHistoryId()
  157. {
  158. if (!is_array($this->_aChatContext))
  159. return 0;
  160. $aAgent = $this->_aChatContext['agent'] ?? null;
  161. $aParams = $this->_aChatContext['params'] ?? [];
  162. if (!is_array($aAgent))
  163. return 0;
  164. return $this->getChatHistoryRowId($aAgent, is_array($aParams) ? $aParams : []);
  165. }
  166. /**
  167. * No `?chat=` in the request means "the conversation I am in", not "the base
  168. * thread": the newest open thread for this owner+context (a `?chat=` partition
  169. * or the base thread). Otherwise a block without `allow_new` would keep talking
  170. * to a base thread the agent closed days ago, while Studio shows a newer chat.
  171. *
  172. * Explicit `?chat=` (subindex with a #) is left alone. Falls back to the base
  173. * thread when nothing is open.
  174. */
  175. public function resolveCurrentChatThread($aAgent, $aParams)
  176. {
  177. $sSub = (string)($aParams['chat_history_subindex'] ?? '');
  178. if ($sSub === '' || strpos($sSub, '#') !== false)
  179. return $aParams;
  180. $sCurrent = $this->_oDb->getCurrentOpenChatThreadId($aAgent, $sSub, (int)($aParams['chat_history_context_pid'] ?? 0));
  181. if ($sCurrent === '')
  182. return $aParams;
  183. $aParsed = self::parseThreadId($aAgent, $sCurrent);
  184. if (!$aParsed || (string)$aParsed['chat_history_subindex'] === '')
  185. return $aParams;
  186. $aParams['chat_history_subindex'] = (string)$aParsed['chat_history_subindex'];
  187. return $aParams;
  188. }
  189. /**
  190. * Create the `?chat=` history row immediately, so the thread exists (and lists)
  191. * before its first message. The owner's other threads are left as they are: a
  192. * "New chat" is one more conversation, not the end of the previous one — people
  193. * switch back to an earlier open thread from the history panel and go on.
  194. * Threads close only when the agent or the turn limit closes them.
  195. *
  196. * @return int history row id, 0 when this is not a `?chat=` thread
  197. */
  198. public function openPartitionedChatThread($aAgent, $aParams)
  199. {
  200. $sSub = (string)($aParams['chat_history_subindex'] ?? '');
  201. if (strpos($sSub, '#') === false)
  202. return 0;
  203. $sThreadId = self::threadId($aAgent, $aParams);
  204. if ($sThreadId === '')
  205. return 0;
  206. return (int)$this->_oDb->ensureChatHistoryRow($sThreadId);
  207. }
  208. /**
  209. * `chat_buttons` tool: queue buttons for the reply being generated.
  210. *
  211. * @return int number of accepted buttons
  212. */
  213. public function setPendingChatActions($mixed)
  214. {
  215. $a = $this->_oUi->sanitizeChatActions($this->normalizeChatButtonsInput($mixed));
  216. if (!$a)
  217. return 0;
  218. $this->_aPendingChatActions = $this->_oUi->mergeChatActions($this->_aPendingChatActions, $a);
  219. return count($a);
  220. }
  221. public function getPendingChatActions()
  222. {
  223. return $this->_oUi->sanitizeChatActions($this->_aPendingChatActions);
  224. }
  225. public function takePendingChatActions()
  226. {
  227. $a = $this->getPendingChatActions();
  228. $this->_aPendingChatActions = [];
  229. return $a;
  230. }
  231. public function resetPendingChatActions()
  232. {
  233. $this->_aPendingChatActions = [];
  234. $this->_bTurnHasText = false;
  235. }
  236. public function markTurnText($sDelta)
  237. {
  238. if (trim((string)$sDelta) !== '')
  239. $this->_bTurnHasText = true;
  240. }
  241. public function hasTurnText()
  242. {
  243. return $this->_bTurnHasText;
  244. }
  245. protected function normalizeChatButtonsInput($mixed)
  246. {
  247. if (!is_array($mixed))
  248. return [];
  249. if (isset($mixed['buttons']) && is_array($mixed['buttons']))
  250. $mixed = $mixed['buttons'];
  251. if (isset($mixed['type']) && (isset($mixed['label']) || isset($mixed['url'])))
  252. return [$mixed];
  253. return $mixed;
  254. }
  255. public function emitConversationClosed($sReason, $sSummary = '', $aAgent = null, $aParams = null)
  256. {
  257. if (!is_array($aAgent) && is_array($this->_aChatContext))
  258. $aAgent = $this->_aChatContext['agent'] ?? null;
  259. if (!is_array($aParams) && is_array($this->_aChatContext))
  260. $aParams = $this->_aChatContext['params'] ?? [];
  261. if (!is_array($aAgent) || empty($aAgent['id']))
  262. return false;
  263. $iHistoryId = $this->getChatHistoryRowId($aAgent, is_array($aParams) ? $aParams : []);
  264. if ($iHistoryId <= 0)
  265. return false;
  266. $sClosed = $this->_oDb->getChatHistoryClosedReasonById($iHistoryId);
  267. if ($sClosed !== '')
  268. return false;
  269. bx_alert('system', 'agent_conversation_closed', $iHistoryId, 0, [
  270. 'agent_id' => (int)$aAgent['id'],
  271. 'summary' => (string)$sSummary,
  272. 'reason' => (string)$sReason,
  273. ]);
  274. return true;
  275. }
  276. /**
  277. * Thread belongs to the current profile / guest session (any `?chat=` partition of theirs).
  278. */
  279. public function isOwnAgentChatThread($aAgent, $sThreadId)
  280. {
  281. $aParsed = self::parseThreadId($aAgent, $sThreadId);
  282. if (!$aParsed)
  283. return false;
  284. $aMine = $this->resolveChatHistoryParams((int)$aAgent['id']);
  285. $sMineOwner = self::chatHistoryOwnerFromSubindex($aMine['chat_history_subindex'] ?? '');
  286. $sRowOwner = self::chatHistoryOwnerFromSubindex($aParsed['chat_history_subindex']);
  287. return $sMineOwner !== '' && $sMineOwner === $sRowOwner;
  288. }
  289. public function getChatHistoryUiMessagesByThread($aAgent, $sThreadId)
  290. {
  291. if (!self::parseThreadId($aAgent, $sThreadId))
  292. return false;
  293. $sJson = $this->_oDb->getChatHistoryMessagesByThreadId((string)$sThreadId);
  294. return $this->_oUi->storedChatJsonToUiMessages($sJson);
  295. }
  296. public function getChatHistoryArtifactsByThread($aAgent, $sThreadId)
  297. {
  298. if (!self::parseThreadId($aAgent, $sThreadId))
  299. return [];
  300. return $this->_oDb->getChatArtifactsByThreadId((string)$sThreadId);
  301. }
  302. public function getChatHistoryClosedReasonByThread($aAgent, $sThreadId)
  303. {
  304. if (!self::parseThreadId($aAgent, $sThreadId))
  305. return '';
  306. return $this->_oDb->getChatHistoryClosedReasonById($this->_oDb->getChatHistoryIdByThreadId((string)$sThreadId));
  307. }
  308. /**
  309. * Every thread of this agent (Studio chat popup): all owners, all contexts.
  310. */
  311. public function listAgentChatThreads($aAgent)
  312. {
  313. $aMineParams = $this->resolveChatHistoryParams((int)$aAgent['id']);
  314. $sMySub = (string)($aMineParams['chat_history_subindex'] ?? '');
  315. $sMyOwner = self::chatHistoryOwnerFromSubindex($sMySub);
  316. $sMyDefault = self::threadId($aAgent, $aMineParams);
  317. $aOut = [];
  318. $bHaveMineDefault = false;
  319. $aRows = $this->_oDb->getAgentChatHistoryRows($aAgent);
  320. if (!is_array($aRows))
  321. $aRows = [];
  322. $aHistoryIds = [];
  323. foreach ($aRows as $aRow)
  324. $aHistoryIds[] = (int)($aRow['id'] ?? 0);
  325. $aArtifactsMap = $this->_oDb->getChatArtifactsForAgent($aAgent);
  326. if (!$aArtifactsMap && $aHistoryIds)
  327. $aArtifactsMap = $this->_oDb->getChatArtifactsByHistoryIds($aHistoryIds);
  328. foreach ($aRows as $aRow) {
  329. $sThreadId = (string)($aRow['thread_id'] ?? '');
  330. $aParsed = self::parseThreadId($aAgent, $sThreadId);
  331. if (!$aParsed)
  332. continue;
  333. $aUi = $this->_oUi->storedChatJsonToUiMessages($aRow['messages'] ?? '');
  334. // A `?chat=` thread is listed even before its first message (it was opened on purpose).
  335. $bPartition = strpos((string)$aParsed['chat_history_subindex'], '#') !== false;
  336. if (!$aUi && $sThreadId !== $sMyDefault && !$bPartition)
  337. continue;
  338. $bMine = ($sMyOwner !== '' && $sMyOwner === self::chatHistoryOwnerFromSubindex($aParsed['chat_history_subindex']));
  339. if ($sThreadId === $sMyDefault)
  340. $bHaveMineDefault = true;
  341. $iHistoryId = (int)($aRow['id'] ?? 0);
  342. $aArtifacts = ($iHistoryId && !empty($aArtifactsMap[$iHistoryId])) ? $aArtifactsMap[$iHistoryId] : [];
  343. $aOut[] = $this->formatAgentChatThread($aParsed, $aRow, $aUi, $bMine, $aArtifacts);
  344. }
  345. if (!$bHaveMineDefault && $sMyDefault !== '') {
  346. $aParsedMine = self::parseThreadId($aAgent, $sMyDefault);
  347. if ($aParsedMine)
  348. $aOut[] = $this->formatAgentChatThread($aParsedMine, [], [], true);
  349. }
  350. usort($aOut, function ($a, $b) {
  351. return strcmp((string)$b['updated_sort'], (string)$a['updated_sort']);
  352. });
  353. return $aOut;
  354. }
  355. /**
  356. * The caller's own conversations with this agent, for the chat widget's history
  357. * panel (`system/get_ai_chat_threads`). Unlike listAgentChatThreads (Studio, every
  358. * owner) this only reads the current profile's / guest session's rows: any
  359. * context, base thread and `?chat=` partitions, newest first. Closed threads
  360. * with nothing in them are skipped; the open one is listed even when empty so
  361. * the panel can mark it as current.
  362. *
  363. * @return array<int, array<string, mixed>> see formatOwnAgentChatThread
  364. */
  365. public function listOwnAgentChatThreads($aAgent)
  366. {
  367. $aMine = $this->resolveChatHistoryParams((int)$aAgent['id']);
  368. $sOwner = self::chatHistoryOwnerFromSubindex($aMine['chat_history_subindex'] ?? '');
  369. if ($sOwner === '')
  370. return [];
  371. $aRows = $this->_oDb->getOwnerAgentChatHistoryRows($aAgent, $sOwner);
  372. if (!is_array($aRows))
  373. return [];
  374. $aOut = [];
  375. foreach ($aRows as $aRow) {
  376. $aParsed = self::parseThreadId($aAgent, (string)($aRow['thread_id'] ?? ''));
  377. // LIKE matched the owner loosely; the parsed id is the authority.
  378. if (!$aParsed || self::chatHistoryOwnerFromSubindex($aParsed['chat_history_subindex']) !== $sOwner)
  379. continue;
  380. $aUi = $this->_oUi->storedChatJsonToUiMessages($aRow['messages'] ?? '');
  381. $sReason = trim((string)($aRow['closed_reason'] ?? ''));
  382. if (!$aUi && $sReason !== '')
  383. continue;
  384. $aOut[] = $this->formatOwnAgentChatThread($aParsed, $aRow, $aUi);
  385. }
  386. return $aOut;
  387. }
  388. /**
  389. * `chat_title` tool: store the title the agent chose for the conversation it is
  390. * in right now (`_aChatContext`, set by the chat trigger). Set once —
  391. * a thread that already has a title keeps it.
  392. *
  393. * @return int 1 saved, 0 already titled, -1 no current thread or no `title` column yet
  394. */
  395. public function setCurrentChatThreadTitle($sTitle)
  396. {
  397. $sTitle = trim((string)$sTitle);
  398. if ($sTitle === '' || !is_array($this->_aChatContext))
  399. return -1;
  400. if (!$this->_oDb->isFieldExists('sys_agents_chat_history', 'title'))
  401. return -1;
  402. $aAgent = $this->_aChatContext['agent'] ?? null;
  403. $aParams = $this->_aChatContext['params'] ?? [];
  404. if (!is_array($aAgent))
  405. return -1;
  406. $sThreadId = self::threadId($aAgent, is_array($aParams) ? $aParams : []);
  407. if ($sThreadId === '' || $sThreadId === ':')
  408. return -1;
  409. // The row may not be there yet on the very first turn: the history is
  410. // persisted after the tools ran. Create it, so the title has somewhere to go.
  411. $this->_oDb->ensureChatHistoryRow($sThreadId);
  412. if ($this->_oDb->getChatHistoryTitle($sThreadId) !== '')
  413. return 0;
  414. return $this->_oDb->setChatHistoryTitle($sThreadId, $sTitle) ? 1 : -1;
  415. }
  416. /**
  417. * Context from chat HTTP (`?context=`). Missing/0 = site-wide. Invalid/denied = false (403).
  418. * Posting in a group is not the same as viewing it; chat requires post by default.
  419. * @return int|false
  420. */
  421. public function resolveChatHistoryContextPid($bRequirePost = true)
  422. {
  423. $mixed = bx_get('context');
  424. if ($mixed === false)
  425. return 0;
  426. $iPid = (int)$mixed;
  427. if ($iPid <= 0)
  428. return 0;
  429. $oProfile = BxDolProfile::getInstance($iPid);
  430. if (!$oProfile || !bx_srv('system', 'is_module_context', [$oProfile->getModule()]))
  431. return false;
  432. if (!$this->isAllowedContextChat($oProfile, $bRequirePost))
  433. return false;
  434. return $iPid;
  435. }
  436. /**
  437. * Context of the current page (AI agent block).
  438. * `bx_get_page_info()` reads the URL; App page JSON merges `i`/`id` into $_GET instead.
  439. * @param bool $bRequirePost also require posting into the context (membership / post ACL)
  440. */
  441. public function resolveChatHistoryContextPidFromPage($bRequirePost = false)
  442. {
  443. $aInfo = bx_get_page_info();
  444. if ($aInfo && !empty($aInfo['context_profile_id']))
  445. return $this->filterContextPid((int)$aInfo['context_profile_id'], $bRequirePost);
  446. $sUri = bx_get('i');
  447. $iContentId = (int)bx_process_input(bx_get('id'), BX_DATA_INT);
  448. if ($sUri && $iContentId > 0) {
  449. $oPage = BxDolPage::getObjectInstanceByURI($sUri);
  450. $sModule = $oPage ? (string)$oPage->getModule() : '';
  451. if ($sModule !== '' && bx_srv('system', 'is_module_context', [$sModule])) {
  452. $oProfile = BxDolProfile::getInstanceByContentAndType($iContentId, $sModule);
  453. if ($oProfile && ($iPid = $this->filterContextPid((int)$oProfile->id(), $bRequirePost)))
  454. return $iPid;
  455. }
  456. }
  457. $iPid = (int)bx_process_input(bx_get('profile_id'), BX_DATA_INT);
  458. if ($iPid > 0 && ($iPid = $this->filterContextPid($iPid, $bRequirePost)))
  459. return $iPid;
  460. return 0;
  461. }
  462. public function filterContextPid($iPid, $bRequirePost = false)
  463. {
  464. $iPid = (int)$iPid;
  465. if ($iPid <= 0)
  466. return 0;
  467. $oProfile = BxDolProfile::getInstance($iPid);
  468. if (!$oProfile || !bx_srv('system', 'is_module_context', [$oProfile->getModule()]))
  469. return 0;
  470. if (!$this->isAllowedContextChat($oProfile, $bRequirePost))
  471. return 0;
  472. return $iPid;
  473. }
  474. /**
  475. * Transcript for TanStack `useChat` hydrate / `initialMessages`.
  476. * Loads the same NeuronAI chat history the agent uses when streaming.
  477. *
  478. * @param bool $bAppendLimitMessage when the session is at max_turns, append limit_message for the UI
  479. */
  480. public function getChatHistoryUiMessages($iAgentId, $aParams = [], $bAppendLimitMessage = true)
  481. {
  482. if (!isset($aParams['chat_history_subindex']))
  483. $aParams = array_merge($this->resolveChatHistoryParams($iAgentId), $aParams);
  484. $aAgent = BxDolAiQuery::getAgentObject((int)$iAgentId);
  485. if (!$aAgent || empty($aAgent['chat_history_context']))
  486. return [];
  487. $sThreadId = self::threadId($aAgent, $aParams);
  488. $sJson = $this->_oDb->getChatHistoryMessagesByThreadId($sThreadId);
  489. $aStored = json_decode((string)$sJson, true);
  490. if (!is_array($aStored) || $aStored === [])
  491. return [];
  492. try {
  493. $o = BxDolAi::getAgentInstance((int)$iAgentId, $aParams);
  494. } catch (Exception $oException) {
  495. bx_log('sys_agents', "Hydrate exception for agent {$iAgentId}: " . $oException->getMessage(), BX_LOG_ERR);
  496. return [];
  497. }
  498. $aResult = $this->_oUi->neuronMessagesToUiMessages($o->getChatHistory()->getMessages());
  499. $oLimits = BxDolAiChatLimits::getInstance();
  500. if ($bAppendLimitMessage && $oLimits->isChatTurnLimitReached($aAgent, $oLimits->countChatUserTurns($aResult))) {
  501. $aResult[] = [
  502. 'id' => 'agent_limit_message',
  503. 'role' => 'assistant',
  504. 'parts' => [['type' => 'text', 'content' => $oLimits->getChatLimitMessage($aAgent)]],
  505. ];
  506. }
  507. return $aResult;
  508. }
  509. protected function formatAgentChatThread($aParsed, $aRow, $aUi, $bMine, $aArtifacts = [])
  510. {
  511. $iContext = (int)$aParsed['chat_history_context_pid'];
  512. $sSub = (string)$aParsed['chat_history_subindex'];
  513. $sContextName = '';
  514. if ($iContext > 0) {
  515. $oContext = BxDolProfile::getInstance($iContext);
  516. $sContextName = $oContext ? $oContext->getDisplayName() : ('#' . $iContext);
  517. }
  518. $sTitle = _t('_sys_agents_agents_txt_guest_chat');
  519. $sOwner = self::chatHistoryOwnerFromSubindex($sSub);
  520. $oProfile = (ctype_digit($sOwner) && (int)$sOwner > 0) ? BxDolProfile::getInstance((int)$sOwner) : false;
  521. if ($oProfile)
  522. $sTitle = $oProfile->getDisplayName();
  523. if ($sContextName !== '')
  524. $sTitle .= ' · ' . $sContextName;
  525. $sThreadTitle = trim((string)($aRow['title'] ?? ''));
  526. if ($sThreadTitle !== '')
  527. $sTitle .= ' · ' . $sThreadTitle;
  528. $sReason = trim((string)($aRow['closed_reason'] ?? ''));
  529. $sStatus = $sReason !== '' ? 'closed' : 'opened';
  530. $sStatusLabel = $sStatus;
  531. if ($sStatus === 'closed' && $sReason !== '')
  532. $sStatusLabel .= ' (' . $sReason . ')';
  533. $aArtifacts = is_array($aArtifacts) ? $aArtifacts : [];
  534. $sCreated = $this->formatAgentChatThreadTime($aRow['created_at'] ?? '');
  535. $sUpdated = $this->formatAgentChatThreadTime($aRow['updated_at'] ?? '');
  536. $sUpdatedRaw = (string)($aRow['updated_at'] ?? '');
  537. $sMeta = 'status: ' . $sStatusLabel;
  538. $sDates = '';
  539. if ($sCreated !== '' && $sUpdated !== '')
  540. $sDates = $sCreated . ' - ' . $sUpdated;
  541. else if ($sCreated !== '')
  542. $sDates = $sCreated;
  543. else if ($sUpdated !== '')
  544. $sDates = $sUpdated;
  545. if ($sDates !== '')
  546. $sMeta .= "\n" . $sDates;
  547. return [
  548. 'thread_id' => $aParsed['thread_id'],
  549. 'writable' => $bMine ? 1 : 0,
  550. 'context_pid' => $iContext,
  551. 'title' => $sTitle,
  552. 'meta' => $sMeta,
  553. 'status' => $sStatus,
  554. 'closed_reason' => $sReason,
  555. 'created_at' => $sCreated,
  556. 'updated_at' => $sUpdated,
  557. 'artifacts' => is_array($aArtifacts) ? $aArtifacts : [],
  558. 'messages' => is_array($aUi) ? $aUi : [],
  559. 'updated_sort' => $sUpdatedRaw,
  560. 'class_mine' => $bMine ? ' bx-agents-popup-chat-thread-mine' : '',
  561. ];
  562. }
  563. /**
  564. * One history-panel item. `chat` is the `?chat=` nonce ('' for the base thread),
  565. * so the client can tell which row its live widget is talking to. `title` is the
  566. * one the agent gave (`chat_title` tool) or the first thing the person typed (the
  567. * hidden "[page opened…" bootstrap is skipped), `preview` the last line said; both plain text.
  568. */
  569. protected function formatOwnAgentChatThread($aParsed, $aRow, $aUi)
  570. {
  571. $iContext = (int)$aParsed['chat_history_context_pid'];
  572. $sContextName = '';
  573. if ($iContext > 0) {
  574. $oContext = BxDolProfile::getInstance($iContext);
  575. $sContextName = $oContext ? $oContext->getDisplayName() : ('#' . $iContext);
  576. }
  577. $sSub = (string)$aParsed['chat_history_subindex'];
  578. $iDot = strpos($sSub, '#');
  579. $sChat = $iDot === false ? '' : substr($sSub, $iDot + 1);
  580. $sTitle = trim((string)($aRow['title'] ?? ''));
  581. $sPreview = '';
  582. foreach ($aUi as $aMessage) {
  583. $sText = $this->_oUi->uiChatMessagePlainText($aMessage);
  584. if ($sText === '')
  585. continue;
  586. if ($sTitle === '' && ($aMessage['role'] ?? '') === 'user' && strpos($sText, '[page opened') !== 0)
  587. $sTitle = $this->clipChatThreadText($sText, 80);
  588. $sPreview = $sText;
  589. }
  590. if ($sPreview !== '' && strpos($sPreview, '[page opened') === 0)
  591. $sPreview = '';
  592. $sReason = trim((string)($aRow['closed_reason'] ?? ''));
  593. return [
  594. 'thread_id' => (string)$aParsed['thread_id'],
  595. 'chat' => $sChat,
  596. 'context_pid' => $iContext,
  597. 'context_name' => $sContextName,
  598. 'status' => $sReason !== '' ? 'closed' : 'opened',
  599. 'closed_reason' => $sReason,
  600. 'title' => $sTitle,
  601. 'preview' => $this->clipChatThreadText($sPreview, 120),
  602. 'messages_count' => count($aUi),
  603. 'created_ts' => $this->chatThreadTimestamp($aRow['created_at'] ?? ''),
  604. 'updated_ts' => $this->chatThreadTimestamp($aRow['updated_at'] ?? ''),
  605. ];
  606. }
  607. protected function clipChatThreadText($s, $iMax)
  608. {
  609. $s = (string)$s;
  610. if (get_mb_len($s) <= $iMax)
  611. return $s;
  612. return rtrim(get_mb_substr($s, 0, $iMax - 1)) . '…';
  613. }
  614. /** Unix timestamp for a `created_at` / `updated_at` cell, 0 when unset. */
  615. protected function chatThreadTimestamp($mixed)
  616. {
  617. $s = trim((string)$mixed);
  618. if ($s === '' || $s === '0')
  619. return 0;
  620. $i = ctype_digit($s) ? (int)$s : (int)strtotime($s);
  621. return $i > 86400 ? $i : 0;
  622. }
  623. protected function formatAgentChatThreadTime($mixed): string
  624. {
  625. $s = trim((string)$mixed);
  626. if ($s === '' || $s === '0')
  627. return '';
  628. $i = ctype_digit($s) ? (int)$s : (int)strtotime($s);
  629. if ($i <= 86400)
  630. return '';
  631. return date('d.m.Y H:i', $i);
  632. }
  633. protected function isAllowedContextChat($oProfile, $bRequirePost = false)
  634. {
  635. if ($oProfile->checkAllowedProfileView() !== CHECK_ACTION_RESULT_ALLOWED)
  636. return false;
  637. if ($bRequirePost && $oProfile->checkAllowedPostInProfile() !== CHECK_ACTION_RESULT_ALLOWED)
  638. return false;
  639. return true;
  640. }
  641. }
  642. /** @} */