session_export_html.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. """Standalone single-file HTML export (single or multi-session with sidebar); no remote deps."""
  2. import datetime
  3. import secrets
  4. from typing import Any, Dict, List
  5. from urllib.parse import quote
  6. from hermes_cli.timefmt import coerce_epoch
  7. # --- Icons (Lucide-style SVGs) ---
  8. ICON_USER = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-user"><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>'
  9. ICON_BOT = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-bot"><path d="M12 8V4H8"/><rect width="16" height="12" x="4" y="8" rx="2"/><path d="M2 14h2"/><path d="M20 14h2"/><path d="M15 13v2"/><path d="M9 13v2"/></svg>'
  10. ICON_TERMINAL = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-terminal"><polyline points="4 17 10 11 4 5"/><line x1="12" x2="20" y1="19" y2="19"/></svg>'
  11. ICON_WRENCH = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-wrench"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>'
  12. ICON_SPARKLES = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-sparkles"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/><path d="M5 3v4"/><path d="M19 17v4"/><path d="M3 5h4"/><path d="M17 19h4"/></svg>'
  13. ICON_CHEVRON_RIGHT = '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-right"><path d="m9 18 6-6-6-6"/></svg>'
  14. ICON_SEARCH = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-search"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>'
  15. ICON_SHIELD = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-shield"><path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.5 3.8 17 5 19 5a1 1 0 0 1 1 1z"/></svg>'
  16. ICON_HERMES = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FFD700" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="m9 12 2 2 4-4"/></svg>'
  17. HTML_TEMPLATE = """<!DOCTYPE html>
  18. <html lang="en">
  19. <head>
  20. <meta charset="UTF-8">
  21. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  22. <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'nonce-{script_nonce}'; style-src 'unsafe-inline' https://fonts.googleapis.com; font-src https://fonts.gstatic.com; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'; object-src 'none'">
  23. <title>{page_title}</title>
  24. <link rel="preconnect" href="https://fonts.googleapis.com">
  25. <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  26. <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
  27. <style>
  28. :root {{
  29. --bg-color: #F8FAFC;
  30. --text-color: #0F172A;
  31. --secondary-text: #475569;
  32. --user-bg: #FFFFFF;
  33. --assistant-bg: #F1F5F9;
  34. --border-color: #E2E8F0;
  35. --accent-color: #CD7F32;
  36. --accent-foreground: #FFFFFF;
  37. --code-bg: #1E293B;
  38. --code-text: #F8FAFC;
  39. --reasoning-bg: #FFFBEB;
  40. --reasoning-border: #FEF3C7;
  41. --tool-bg: #F0F9FF;
  42. --tool-border: #E0F2FE;
  43. --shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
  44. --sidebar-bg: #FFFFFF;
  45. --sidebar-width: 320px;
  46. }}
  47. @media (prefers-color-scheme: dark) {{
  48. :root {{
  49. --bg-color: #000101;
  50. --text-color: #FFF8DC;
  51. --secondary-text: #94A3B8;
  52. --user-bg: #041c1c;
  53. --assistant-bg: #0c1a1a;
  54. --border-color: #CD7F32;
  55. --accent-color: #FFD700;
  56. --code-bg: #000000;
  57. --reasoning-bg: #1a1a1a;
  58. --reasoning-border: #CD7F32;
  59. --tool-bg: #0c4a6e;
  60. --tool-border: #075985;
  61. --shadow: 0 4px 6px -1px rgb(0 0 0 / 0.3), 0 2px 4px -2px rgb(0 0 0 / 0.3);
  62. --sidebar-bg: #041c1c;
  63. }}
  64. }}
  65. * {{
  66. box-sizing: border-box;
  67. margin: 0;
  68. padding: 0;
  69. }}
  70. body {{
  71. font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  72. line-height: 1.6;
  73. color: var(--text-color);
  74. background-color: var(--bg-color);
  75. -webkit-font-smoothing: antialiased;
  76. overflow-x: hidden;
  77. }}
  78. .layout {{
  79. display: flex;
  80. min-height: 100vh;
  81. }}
  82. /* Sidebar */
  83. .sidebar {{
  84. width: var(--sidebar-width);
  85. background-color: var(--sidebar-bg);
  86. border-right: 1px solid var(--border-color);
  87. display: flex;
  88. flex-direction: column;
  89. position: fixed;
  90. height: 100vh;
  91. z-index: 100;
  92. transition: transform 0.3s ease;
  93. }}
  94. @media (max-width: 768px) {{
  95. .sidebar {{
  96. transform: translateX(-100%);
  97. }}
  98. .sidebar.open {{
  99. transform: translateX(0);
  100. }}
  101. .main-content {{
  102. margin-left: 0 !important;
  103. }}
  104. }}
  105. .sidebar-header {{
  106. padding: 1.5rem;
  107. border-bottom: 1px solid var(--border-color);
  108. }}
  109. .sidebar-brand {{
  110. display: flex;
  111. align-items: center;
  112. gap: 0.75rem;
  113. font-weight: 700;
  114. font-size: 1.25rem;
  115. color: var(--accent-color);
  116. margin-bottom: 1rem;
  117. }}
  118. .search-container {{
  119. position: relative;
  120. }}
  121. .search-container input {{
  122. width: 100%;
  123. padding: 0.5rem 1rem 0.5rem 2.25rem;
  124. border-radius: 0.5rem;
  125. border: 1px solid var(--border-color);
  126. background-color: var(--bg-color);
  127. color: var(--text-color);
  128. font-size: 0.875rem;
  129. outline: none;
  130. }}
  131. .search-container svg {{
  132. position: absolute;
  133. left: 0.75rem;
  134. top: 50%;
  135. transform: translateY(-50%);
  136. color: var(--secondary-text);
  137. }}
  138. .session-list {{
  139. flex: 1;
  140. overflow-y: auto;
  141. padding: 1rem;
  142. }}
  143. .session-item {{
  144. display: block;
  145. padding: 0.75rem 1rem;
  146. border-radius: 0.5rem;
  147. margin-bottom: 0.5rem;
  148. cursor: pointer;
  149. transition: all 0.2s ease;
  150. text-decoration: none;
  151. color: inherit;
  152. border: 1px solid transparent;
  153. }}
  154. .session-item:hover {{
  155. background-color: rgba(0, 0, 0, 0.05);
  156. }}
  157. @media (prefers-color-scheme: dark) {{
  158. .session-item:hover {{
  159. background-color: rgba(255, 255, 255, 0.05);
  160. }}
  161. }}
  162. .session-item.active {{
  163. background-color: var(--user-bg);
  164. border-color: var(--accent-color);
  165. box-shadow: var(--shadow);
  166. }}
  167. .session-item-title {{
  168. font-weight: 600;
  169. font-size: 0.875rem;
  170. white-space: nowrap;
  171. overflow: hidden;
  172. text-overflow: ellipsis;
  173. margin-bottom: 0.25rem;
  174. }}
  175. .session-item-meta {{
  176. font-size: 0.75rem;
  177. color: var(--secondary-text);
  178. display: flex;
  179. justify-content: space-between;
  180. }}
  181. /* Main Content */
  182. .main-content {{
  183. flex: 1;
  184. margin-left: {main_margin};
  185. padding: 3rem 2rem;
  186. max-width: 100%;
  187. transition: margin-left 0.3s ease;
  188. }}
  189. .session-view {{
  190. display: none;
  191. width: 100%;
  192. margin: 0 auto;
  193. }}
  194. .layout-single .session-view {{
  195. max-width: 90%;
  196. margin: 0 auto;
  197. }}
  198. .layout-multi .session-view {{
  199. max-width: 100%;
  200. margin: 0;
  201. }}
  202. .layout-multi .main-content {{
  203. width: 0;
  204. }}
  205. .session-view.active {{
  206. display: block;
  207. }}
  208. header {{
  209. margin-bottom: 3rem;
  210. text-align: center;
  211. }}
  212. .meta {{
  213. display: flex;
  214. justify-content: center;
  215. flex-wrap: wrap;
  216. gap: 1.5rem;
  217. margin-top: 1rem;
  218. font-size: 0.875rem;
  219. color: var(--secondary-text);
  220. }}
  221. .meta-item strong {{
  222. color: var(--text-color);
  223. }}
  224. /* Messages */
  225. .message {{
  226. margin-bottom: 1.5rem;
  227. border-radius: 0.75rem;
  228. background-color: var(--user-bg);
  229. border: 1px solid var(--border-color);
  230. box-shadow: var(--shadow);
  231. overflow: hidden;
  232. }}
  233. .message-user {{
  234. background-color: #f0fdf4;
  235. }}
  236. .message-assistant {{
  237. background-color: var(--assistant-bg);
  238. border-left: 4px solid var(--accent-color);
  239. }}
  240. .message-system {{
  241. background-color: var(--bg-color);
  242. border-left: 4px solid var(--secondary-text);
  243. opacity: 0.9;
  244. }}
  245. .message-tool {{
  246. background-color: #f8fafc;
  247. border-style: dotted;
  248. }}
  249. @media (prefers-color-scheme: dark) {{
  250. .message-user {{
  251. background-color: #0c2121;
  252. }}
  253. .message-assistant {{
  254. background-color: #041c1c;
  255. }}
  256. .message-system {{
  257. background-color: #020617;
  258. border-left: 4px solid var(--secondary-text);
  259. }}
  260. .message-tool {{
  261. background-color: #0f172a;
  262. }}
  263. }}
  264. .message-header {{
  265. display: flex;
  266. align-items: center;
  267. justify-content: space-between;
  268. padding: 1rem 1.5rem;
  269. cursor: pointer;
  270. user-select: none;
  271. transition: background-color 0.2s ease;
  272. }}
  273. .message-header:hover {{
  274. background-color: rgba(0,0,0,0.02);
  275. }}
  276. .message-header svg.chevron {{
  277. transition: transform 0.2s ease;
  278. color: var(--secondary-text);
  279. }}
  280. .message.active svg.chevron {{
  281. transform: rotate(90deg);
  282. }}
  283. .role-badge {{
  284. display: flex;
  285. align-items: center;
  286. gap: 0.5rem;
  287. font-size: 0.75rem;
  288. font-weight: 700;
  289. text-transform: uppercase;
  290. letter-spacing: 0.05em;
  291. color: var(--secondary-text);
  292. }}
  293. .role-badge svg {{
  294. color: var(--accent-color);
  295. }}
  296. .timestamp {{
  297. font-size: 0.75rem;
  298. color: var(--secondary-text);
  299. font-variant-numeric: tabular-nums;
  300. }}
  301. .message-body {{
  302. display: none;
  303. padding: 0 1.5rem 1.5rem 1.5rem;
  304. border-top: 1px solid var(--border-color);
  305. padding-top: 1.5rem;
  306. }}
  307. .message.active .message-body {{
  308. display: block;
  309. }}
  310. .content {{
  311. white-space: pre-wrap;
  312. word-break: break-word;
  313. font-size: 1rem;
  314. }}
  315. /* Code Blocks */
  316. code {{
  317. font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, monospace;
  318. background-color: rgba(0,0,0,0.05);
  319. padding: 0.2rem 0.4rem;
  320. border-radius: 0.375rem;
  321. font-size: 0.9em;
  322. }}
  323. pre {{
  324. background-color: var(--code-bg);
  325. color: var(--code-text);
  326. padding: 1.25rem;
  327. border-radius: 0.75rem;
  328. overflow-x: auto;
  329. margin: 1.25rem 0;
  330. font-size: 0.9rem;
  331. line-height: 1.5;
  332. box-shadow: inset 0 2px 4px 0 rgb(0 0 0 / 0.1);
  333. }}
  334. pre code {{
  335. background-color: transparent;
  336. padding: 0;
  337. border-radius: 0;
  338. color: inherit;
  339. }}
  340. /* Tool Calls */
  341. .tool-call {{
  342. margin: 1rem 0;
  343. border-radius: 0.5rem;
  344. overflow: hidden;
  345. border: 1px solid var(--tool-border);
  346. background-color: var(--tool-bg);
  347. }}
  348. .tool-call-header {{
  349. padding: 0.75rem 1rem;
  350. display: flex;
  351. align-items: center;
  352. gap: 0.5rem;
  353. cursor: pointer;
  354. user-select: none;
  355. font-size: 0.875rem;
  356. font-weight: 600;
  357. }}
  358. .tool-call-header:hover {{
  359. background-color: rgba(0,0,0,0.03);
  360. }}
  361. .tool-call-header svg.chevron {{
  362. transition: transform 0.2s ease;
  363. color: var(--secondary-text);
  364. }}
  365. .tool-call.active svg.chevron {{
  366. transform: rotate(90deg);
  367. }}
  368. .tool-call-content {{
  369. display: none;
  370. padding: 0 1rem 1rem 1rem;
  371. }}
  372. .tool-call.active .tool-call-content {{
  373. display: block;
  374. }}
  375. /* Reasoning */
  376. .reasoning {{
  377. margin-top: 1.5rem;
  378. border-radius: 0.75rem;
  379. border: 1px solid var(--reasoning-border);
  380. background-color: var(--reasoning-bg);
  381. overflow: hidden;
  382. }}
  383. .reasoning-header {{
  384. padding: 0.75rem 1rem;
  385. display: flex;
  386. align-items: center;
  387. gap: 0.5rem;
  388. cursor: pointer;
  389. user-select: none;
  390. font-size: 0.875rem;
  391. font-weight: 600;
  392. }}
  393. .reasoning-header:hover {{
  394. background-color: rgba(0,0,0,0.02);
  395. }}
  396. .reasoning-header svg.chevron {{
  397. transition: transform 0.2s ease;
  398. color: var(--secondary-text);
  399. }}
  400. .reasoning.active svg.chevron {{
  401. transform: rotate(90deg);
  402. }}
  403. .reasoning-content {{
  404. display: none;
  405. padding: 0 1rem 1rem 1rem;
  406. font-size: 0.925rem;
  407. color: var(--secondary-text);
  408. border-top: 1px solid var(--reasoning-border);
  409. padding-top: 1rem;
  410. }}
  411. .reasoning.active .reasoning-content {{
  412. display: block;
  413. }}
  414. /* System Prompt Section */
  415. .system-prompt-section {{
  416. margin-top: 2rem;
  417. border-radius: 0.75rem;
  418. border: 1px solid var(--border-color);
  419. background-color: var(--user-bg);
  420. overflow: hidden;
  421. text-align: left;
  422. max-width: 800px;
  423. margin-left: auto;
  424. margin-right: auto;
  425. }}
  426. .system-prompt-header {{
  427. padding: 0.75rem 1.25rem;
  428. display: flex;
  429. align-items: center;
  430. gap: 0.6rem;
  431. cursor: pointer;
  432. user-select: none;
  433. font-size: 0.875rem;
  434. font-weight: 600;
  435. color: var(--secondary-text);
  436. }}
  437. .system-prompt-header:hover {{
  438. background-color: rgba(0,0,0,0.02);
  439. }}
  440. .system-prompt-header svg.chevron {{
  441. transition: transform 0.2s ease;
  442. }}
  443. .system-prompt-section.active svg.chevron {{
  444. transform: rotate(90deg);
  445. }}
  446. .system-prompt-content {{
  447. display: none;
  448. padding: 0 1.25rem 1.25rem 1.25rem;
  449. font-size: 0.9rem;
  450. border-top: 1px solid var(--border-color);
  451. padding-top: 1rem;
  452. }}
  453. .system-prompt-section.active .system-prompt-content {{
  454. display: block;
  455. }}
  456. footer {{
  457. margin-top: 5rem;
  458. padding-top: 2rem;
  459. border-top: 1px solid var(--border-color);
  460. text-align: center;
  461. font-size: 0.875rem;
  462. color: var(--secondary-text);
  463. }}
  464. /* Animation */
  465. .fade-in {{
  466. animation: fadeIn 0.4s ease-out backwards;
  467. }}
  468. @keyframes fadeIn {{
  469. from {{ opacity: 0; transform: translateY(10px); }}
  470. to {{ opacity: 1; transform: translateY(0); }}
  471. }}
  472. /* Utilities */
  473. .hidden {{ display: none !important; }}
  474. </style>
  475. </head>
  476. <body>
  477. <div class="layout {layout_class}">
  478. {sidebar_html}
  479. <div class="main-content">
  480. {sessions_html}
  481. <footer>
  482. Built with ☤ Hermes Agent • Generated on {generated_at}
  483. </footer>
  484. </div>
  485. </div>
  486. <script nonce="{script_nonce}">
  487. // Session Switching
  488. function showSession(id) {{
  489. // Update Sidebar
  490. document.querySelectorAll('.session-item').forEach(el => {{
  491. el.classList.toggle('active', el.dataset.id === id);
  492. }});
  493. // Update View
  494. document.querySelectorAll('.session-view').forEach(el => {{
  495. el.classList.remove('active');
  496. }});
  497. const activeView = document.getElementById(`view-${{id}}`);
  498. if (activeView) activeView.classList.add('active');
  499. // Store in URL hash
  500. window.location.hash = encodeURIComponent(id);
  501. }}
  502. document.querySelectorAll('.session-item').forEach(item => {{
  503. item.addEventListener('click', (e) => {{
  504. e.preventDefault();
  505. showSession(item.dataset.id || '');
  506. }});
  507. }});
  508. // Search Filter
  509. const searchInput = document.getElementById('session-search');
  510. if (searchInput) {{
  511. searchInput.addEventListener('input', (e) => {{
  512. const term = e.target.value.toLowerCase();
  513. document.querySelectorAll('.session-item').forEach(item => {{
  514. const text = item.innerText.toLowerCase();
  515. if (text.includes(term)) {{
  516. item.classList.remove('hidden');
  517. }} else {{
  518. item.classList.add('hidden');
  519. }}
  520. }});
  521. }});
  522. }}
  523. // Card Toggles
  524. document.addEventListener('click', function(e) {{
  525. const header = e.target.closest('.message-header, .tool-call-header, .reasoning-header, .system-prompt-header');
  526. if (header) {{
  527. header.parentElement.classList.toggle('active');
  528. }}
  529. }});
  530. // Initialization
  531. window.addEventListener('load', () => {{
  532. const hash = decodeURIComponent(window.location.hash.slice(1));
  533. if (hash) {{
  534. showSession(hash);
  535. }} else {{
  536. // Show first session by default if none selected
  537. const first = document.querySelector('.session-item');
  538. if (first) showSession(first.getAttribute('data-id'));
  539. }}
  540. }});
  541. // Intersection Observer for scroll animations
  542. if ('IntersectionObserver' in window) {{
  543. var observer = new IntersectionObserver(function(entries) {{
  544. entries.forEach(function(entry) {{
  545. if (entry.isIntersecting) {{
  546. entry.target.classList.add('fade-in');
  547. observer.unobserve(entry.target);
  548. }}
  549. }});
  550. }}, {{ threshold: 0.1 }});
  551. document.querySelectorAll('.message').forEach(function(m) {{ observer.observe(m); }});
  552. }}
  553. </script>
  554. </body>
  555. </html>
  556. """
  557. def _escape_html(text: Any) -> str:
  558. return (
  559. str(text).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
  560. .replace('"', "&quot;").replace("'", "&#39;")
  561. )
  562. def _format_timestamp(ts: Any) -> str:
  563. # A corrupt cell renders as N/A; never raw text (a TEXT timestamp would otherwise reach an HTML sink).
  564. return datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S") if ts and (ts := coerce_epoch(ts)) else "N/A"
  565. _ROLE_ICONS = {"user": ICON_USER, "assistant": ICON_BOT, "system": ICON_SHIELD}
  566. _CHEVRON_HTML = ICON_CHEVRON_RIGHT.replace('class="', 'class="chevron ')
  567. def _content_text(content: Any) -> str:
  568. """Flatten multimodal/complex content parts into display text."""
  569. if not isinstance(content, list):
  570. return content
  571. parts = []
  572. for part in content:
  573. if not isinstance(part, dict):
  574. parts.append(str(part))
  575. elif part.get("type") == "text":
  576. parts.append(part.get("text", ""))
  577. elif part.get("type") == "image_url":
  578. parts.append("[Image Attachment]")
  579. return "\n".join(parts)
  580. def _collapsible(kind: str, icon: str, title: str, inner: str, indent: str, outer_class: str = "") -> str:
  581. """A chevron-headed collapsible block (tool-call / reasoning / system-prompt)."""
  582. return f"""
  583. {indent}<div class="{outer_class or kind}">
  584. {indent} <div class="{kind}-header">
  585. {indent} {_CHEVRON_HTML}
  586. {indent} {icon} {title}
  587. {indent} </div>
  588. {indent} <div class="{kind}-content">
  589. {indent} {inner}
  590. {indent} </div>
  591. {indent}</div>
  592. {indent}"""
  593. def _generate_messages_html(messages: list[dict[str, Any]]) -> str:
  594. html_list = []
  595. for i, msg in enumerate(messages):
  596. role = msg.get("role", "unknown")
  597. if role == "session_meta": # internal metadata, never rendered
  598. continue
  599. content = _content_text(msg.get("content") or "")
  600. # The role feeds two sinks and is externally influenced for tool/MCP messages: HTML-escape
  601. # the display text; reduce the class token to alnum/-/_ so a crafted role can neither break
  602. # out of the attribute nor split into extra classes (real roles keep matching `.message-<role>`).
  603. role_class = "".join(c if c.isalnum() or c in "-_" else "-" for c in str(role).lower())
  604. delay_style = f' style="animation-delay: {min(i * 0.05, 1.0)}s"' if i < 10 else "" # stagger first items
  605. html = (
  606. f'<div class="message message-{role_class} active"{delay_style}>'
  607. f' <div class="message-header">'
  608. f' <div class="role-badge">{_CHEVRON_HTML} {_ROLE_ICONS.get(role, ICON_TERMINAL)} {_escape_html(role)}</div>'
  609. f' <div class="timestamp">{_format_timestamp(msg.get("timestamp", 0))}</div>'
  610. ' </div>'
  611. ' <div class="message-body">'
  612. )
  613. for tc in msg.get("tool_calls") or ():
  614. fn = tc.get("function", {})
  615. html += _collapsible(
  616. "tool-call", ICON_WRENCH, f"Tool Call: {_escape_html(fn.get('name', 'unknown'))}",
  617. f"<pre><code>{_escape_html(fn.get('arguments', '{}'))}</code></pre>", " " * 16,
  618. )
  619. if content:
  620. escaped = _escape_html(content)
  621. html += f' <div class="content">{f"<pre><code>{escaped}</code></pre>" if role == "tool" else escaped}</div>'
  622. if reasoning := msg.get("reasoning") or msg.get("reasoning_content"):
  623. html += _collapsible(
  624. "reasoning", ICON_SPARKLES, "Reasoning", f'<div class="content">{_escape_html(reasoning)}</div>', " " * 12,
  625. )
  626. html_list.append(html + " </div></div>")
  627. return "\n".join(html_list)
  628. def _sidebar_item_html(s: dict[str, Any]) -> str:
  629. sid = str(s.get("id", "N/A"))
  630. title = s.get("title") or s.get("preview") or "Untitled Session"
  631. title = title[:47] + "..." if len(title) > 50 else title
  632. return f"""
  633. <a class="session-item" data-id="{_escape_html(sid)}" href="#{quote(sid, safe='')}">
  634. <div class="session-item-title">{_escape_html(title)}</div>
  635. <div class="session-item-meta">
  636. <span>{_escape_html(sid[:8])}</span>
  637. <span>{_format_timestamp(s.get("started_at", 0)).split(" ")[0]}</span>
  638. </div>
  639. </a>
  640. """
  641. def _sidebar_html(sessions: list[dict[str, Any]]) -> str:
  642. return f"""
  643. <aside class="sidebar">
  644. <div class="sidebar-header">
  645. <div class="sidebar-brand">
  646. {ICON_HERMES} Hermes History
  647. </div>
  648. <div class="search-container">
  649. {ICON_SEARCH}
  650. <input type="text" id="session-search" placeholder="Search sessions...">
  651. </div>
  652. </div>
  653. <div class="session-list">
  654. {"".join(_sidebar_item_html(s) for s in sessions)}
  655. </div>
  656. </aside>
  657. """
  658. def _session_view_html(s: dict[str, Any], is_multi: bool) -> str:
  659. escaped_sid = _escape_html(str(s.get("id", "N/A")))
  660. system_html = _collapsible(
  661. "system-prompt", ICON_SHIELD, "System Prompt (Persona)",
  662. f'<div class="content">{_escape_html(s["system_prompt"])}</div>', " " * 12,
  663. outer_class="system-prompt-section active",
  664. ) if s.get("system_prompt") else ""
  665. return f"""
  666. <div class="{"session-view" if is_multi else "session-view active"}" id="view-{escaped_sid}">
  667. <header class="fade-in">
  668. <h1>{_escape_html(s.get("title") or "Hermes Session")}</h1>
  669. <div class="meta">
  670. <div class="meta-item"><strong>ID:</strong> {escaped_sid}</div>
  671. <div class="meta-item"><strong>Model:</strong> {_escape_html(s.get("model") or "Unknown")}</div>
  672. <div class="meta-item"><strong>Started:</strong> {_format_timestamp(s.get("started_at", 0))}</div>
  673. </div>
  674. {system_html}
  675. </header>
  676. <main>
  677. {_generate_messages_html(s.get("messages", []))}
  678. </main>
  679. </div>
  680. """
  681. def generate_multi_session_html_export(sessions: list[dict[str, Any]]) -> str:
  682. if not sessions:
  683. return "<html><body><h1>No sessions to export.</h1></body></html>"
  684. is_multi = len(sessions) > 1
  685. return HTML_TEMPLATE.format(
  686. page_title="Hermes Session Export" if is_multi else _escape_html(sessions[0].get("title") or "Hermes Session"),
  687. sidebar_html=_sidebar_html(sessions) if is_multi else "",
  688. sessions_html="\n".join(_session_view_html(s, is_multi) for s in sessions),
  689. main_margin="var(--sidebar-width)" if is_multi else "0",
  690. layout_class="layout-multi" if is_multi else "layout-single",
  691. generated_at=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
  692. script_nonce=secrets.token_urlsafe(16),
  693. )
  694. def generate_html_export(session_data: dict[str, Any]) -> str:
  695. """Single-session export (legacy entry point)."""
  696. return generate_multi_session_html_export([session_data])