@unieai/rabi-experimental-session-inspector 0.0.0-stage → 0.2.2-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +7 -2
  3. package/lib/client.js +4 -0
  4. package/lib/index.js +6 -0
  5. package/lib/types/client/index.d.ts +10 -0
  6. package/lib/types/client/locales.d.ts +399 -0
  7. package/lib/types/client/views/InspectorDetails.d.ts +17 -0
  8. package/lib/types/client/views/InspectorObjectTree.d.ts +26 -0
  9. package/lib/types/client/views/InspectorTable.d.ts +43 -0
  10. package/lib/types/client/views/TypeFilter.d.ts +15 -0
  11. package/lib/types/client/views/View.d.ts +42 -0
  12. package/lib/types/client/views/chat-node/dom.d.ts +28 -0
  13. package/lib/types/client/views/chat-node/highlight.d.ts +20 -0
  14. package/lib/types/client/views/chat-node/model.d.ts +52 -0
  15. package/lib/types/client/views/chat-node/objects.d.ts +24 -0
  16. package/lib/types/client/views/chat-node/pick-match.d.ts +27 -0
  17. package/lib/types/client/views/chat-node/picker.d.ts +43 -0
  18. package/lib/types/client/views/chat-node/reveal-target.d.ts +14 -0
  19. package/lib/types/client/views/chat-node/reveal.d.ts +25 -0
  20. package/lib/types/client/views/format.d.ts +11 -0
  21. package/lib/types/client/views/index.d.ts +8 -0
  22. package/lib/types/client/views/object-value.d.ts +28 -0
  23. package/lib/types/client/views/objects.d.ts +39 -0
  24. package/lib/types/client/views/raw-json.d.ts +11 -0
  25. package/lib/types/client/views/session-log/chat-target.d.ts +16 -0
  26. package/lib/types/client/views/session-log/groups.d.ts +18 -0
  27. package/lib/types/client/views/session-log/model.d.ts +54 -0
  28. package/lib/types/client/views/session-log/stream.d.ts +37 -0
  29. package/lib/types/client/views/table-layout.d.ts +56 -0
  30. package/lib/types/client/views/table-model.d.ts +76 -0
  31. package/lib/types/client/views/type-filter.d.ts +41 -0
  32. package/lib/types/index.d.ts +4 -0
  33. package/locale/de.json +6 -0
  34. package/locale/en.json +6 -0
  35. package/locale/es.json +6 -0
  36. package/locale/fr.json +6 -0
  37. package/locale/ja.json +6 -0
  38. package/locale/pt.json +6 -0
  39. package/locale/ru.json +6 -0
  40. package/locale/zh.json +6 -0
  41. package/package.json +48 -4
  42. package/src/client/index.ts +19 -0
  43. package/src/client/locales.ts +462 -0
  44. package/src/client/views/InspectorDetails.tsx +75 -0
  45. package/src/client/views/InspectorObjectTree.tsx +122 -0
  46. package/src/client/views/InspectorTable.tsx +345 -0
  47. package/src/client/views/TypeFilter.tsx +129 -0
  48. package/src/client/views/View.tsx +98 -0
  49. package/src/client/views/chat-node/dom.ts +87 -0
  50. package/src/client/views/chat-node/highlight.ts +41 -0
  51. package/src/client/views/chat-node/model.ts +212 -0
  52. package/src/client/views/chat-node/objects.ts +90 -0
  53. package/src/client/views/chat-node/pick-match.ts +68 -0
  54. package/src/client/views/chat-node/picker.ts +172 -0
  55. package/src/client/views/chat-node/reveal-target.ts +90 -0
  56. package/src/client/views/chat-node/reveal.ts +178 -0
  57. package/src/client/views/format.ts +33 -0
  58. package/src/client/views/index.ts +80 -0
  59. package/src/client/views/inspector.module.css +181 -0
  60. package/src/client/views/object-value.ts +100 -0
  61. package/src/client/views/objects.ts +42 -0
  62. package/src/client/views/raw-json.ts +44 -0
  63. package/src/client/views/session-log/chat-target.ts +47 -0
  64. package/src/client/views/session-log/groups.ts +47 -0
  65. package/src/client/views/session-log/model.ts +218 -0
  66. package/src/client/views/session-log/stream.ts +78 -0
  67. package/src/client/views/table-layout.ts +110 -0
  68. package/src/client/views/table-model.ts +122 -0
  69. package/src/client/views/type-filter.ts +82 -0
  70. package/src/css-modules.d.ts +5 -0
  71. package/src/index.ts +4 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,8 @@
1
- # Temporary Holding Version
1
+ # @unieai/rabi-experimental-session-inspector
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Experimental virtualized Session log and live Chat group/node inspectors
4
+
5
+ Part of Rabi, the agent harness UnieAI Code runs on. Installed as a dependency of `@unieai/rabi`;
6
+ not meant to be used on its own.
7
+
8
+ See LICENSE for the license and copyright of this package.
package/lib/client.js ADDED
@@ -0,0 +1,4 @@
1
+
2
+ window.__ModuleLoader__.load({id:`@unieai/rabi-experimental-session-inspector`,factory:require=>{var module={exports:{}};var exports=module.exports;Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let _unieai_rabi_client_store=require("@unieai/rabi-client-store");let react_jsx_runtime=require("react/jsx-runtime");let react=require("react");let _tanstack_react_virtual=require("@tanstack/react-virtual");let _unieai_rabi_client_ui_primitives=require("@unieai/rabi-client-ui-primitives");let react_dom=require("react-dom");const NS=`session-inspector`;const zh={"tab.title":`会话数据诊断`,"tab.description":`在侧边栏分析当前会话原始日志和聊天分组数据`,"view.presentation":`展示形式`,"view.sessionLog":`原始数据`,"view.chatNode":`对话分组`,"picker.pick":`在对话面板中选取元素`,"picker.cancel":`取消选取 (Esc)`,"picker.instructions":`在左侧 Chat 中悬停预览,点击选取;Esc 取消。`,"picker.noMatch":`当前表格没有匹配记录,请选择其他元素或按 Esc 取消。`,"picker.noChat":`请先在主区域打开当前 Session 的 Chat。`,"table.id":`序号`,"table.type":`类型`,"filter.title":`筛选类型`,"filter.input":`类型关键词`,"filter.placeholder":`输入类型片段,如 delta`,"filter.help":`默认包含匹配(*关键词*);Enter 确认,Esc 取消。`,"filter.candidates":`类型候选`,"filter.loading":`正在查找候选…`,"filter.failed":`无法获取类型候选。`,"filter.noCandidates":`没有匹配候选,仍可确认当前关键词。`,"filter.clear":`清空`,"filter.cancel":`取消`,"filter.apply":`确认筛选`,"filter.context":`匹配记录的父级上下文`,"table.location":`T/S`,"table.time":`时间 (UTC)`,"table.data":`数据`,"table.older":`加载更早`,"table.loading":`加载中…`,"table.latest":`跟踪最新`,"table.empty":`暂无记录`,"table.raw":`原始数据`,"table.rawError":`无法序列化这条记录,可以选择其他记录继续查看。`,"table.resizeDetails":`调整原始数据面板高度`,"table.close":`关闭`,"table.expand":`展开子行`,"table.collapse":`收起子行`,"table.removed":`该记录已移除或结算,请选择当前记录。`,"object.node":`Node`,"object.nodeData":`Node Data`,"object.group":`Group`,"object.groupData":`Group Data`,"object.turn":`Turn`,"object.turnData":`Turn Data`,"object.step":`Step`,"object.stepData":`Step Data`,"object.accessor":`[Getter / Setter,未执行]`,"object.empty":`空`,"object.absent":`[空槽]`,"object.properties":`其他属性`,"object.more":`显示更多`,"object.navigation":`原始数据导航`};const en={"tab.title":`Session log`,"tab.description":`Analyze raw logs and grouped chat messages for the current session in the sidebar.`,"view.presentation":`Presentation`,"view.sessionLog":`Raw log`,"view.chatNode":`Chat group`,"picker.pick":`Pick an element in the chat view`,"picker.cancel":`Cancel picking (Esc)`,"picker.instructions":`Hover in the main chat to preview, then click to select. Esc cancels.`,"picker.noMatch":`No matching record in this table. Pick another element or press Esc to cancel.`,"picker.noChat":`Open this session in the main chat before picking.`,"table.id":`Index`,"table.type":`Type`,"filter.title":`Filter types`,"filter.input":`Type keyword`,"filter.placeholder":`Type a fragment, e.g. delta`,"filter.help":`Contains matching (*keyword*). Enter confirms; Esc cancels.`,"filter.candidates":`Type suggestions`,"filter.loading":`Finding suggestions…`,"filter.failed":`Type suggestions could not be loaded.`,"filter.noCandidates":`No suggestions. You can still apply this keyword.`,"filter.clear":`Clear`,"filter.cancel":`Cancel`,"filter.apply":`Apply filter`,"filter.context":`Parent context of a matching record`,"table.location":`T/S`,"table.time":`Time (UTC)`,"table.data":`Data`,"table.older":`Load earlier`,"table.loading":`Loading…`,"table.latest":`Follow latest`,"table.empty":`No records`,"table.raw":`Raw data`,"table.rawError":`This record could not be serialized. Select another record to continue.`,"table.resizeDetails":`Resize raw data panel`,"table.close":`Close`,"table.expand":`Expand children`,"table.collapse":`Collapse children`,"table.removed":`This record was removed or settled. Select a current record.`,"object.node":`Node`,"object.nodeData":`Node data`,"object.group":`Group`,"object.groupData":`Group data`,"object.turn":`Turn`,"object.turnData":`Turn data`,"object.step":`Step`,"object.stepData":`Step data`,"object.accessor":`[Getter / setter, not evaluated]`,"object.empty":`Empty`,"object.absent":`[Empty slot]`,"object.properties":`Other properties`,"object.more":`Show more`,"object.navigation":`Raw data navigation`};const ja={"tab.title":`セッションログ`,"tab.description":`サイドバーで現在のセッションの生ログとグループ化されたチャットメッセージを分析します。`,"view.presentation":`表示`,"view.sessionLog":`生ログ`,"view.chatNode":`チャットグループ`,"picker.pick":`チャットビューで要素を選択`,"picker.cancel":`選択をキャンセル (Esc)`,"picker.instructions":`メインチャット上でホバーしてプレビューし、クリックで選択します。Escでキャンセル。`,"picker.noMatch":`このテーブルに一致するレコードはありません。別の要素を選択するか、Escでキャンセルしてください。`,"picker.noChat":`選択する前に、このセッションをメインチャットで開いてください。`,"table.id":`インデックス`,"table.type":`種類`,"filter.title":`種類を絞り込み`,"filter.input":`キーワードを入力`,"filter.placeholder":`断片を入力 (例: delta)`,"filter.help":`部分一致 (*キーワード*)。Enterで確定、Escでキャンセル。`,"filter.candidates":`種類の候補`,"filter.loading":`候補を検索中…`,"filter.failed":`種類の候補を読み込めませんでした。`,"filter.noCandidates":`候補はありません。このキーワードはそのまま適用できます。`,"filter.clear":`クリア`,"filter.cancel":`キャンセル`,"filter.apply":`フィルターを適用`,"filter.context":`一致したレコードの親コンテキスト`,"table.location":`T/S`,"table.time":`時刻 (UTC)`,"table.data":`データ`,"table.older":`以前を読み込む`,"table.loading":`読み込み中…`,"table.latest":`最新を追跡`,"table.empty":`レコードなし`,"table.raw":`生データ`,"table.rawError":`このレコードはシリアライズできませんでした。続行するには別のレコードを選択してください。`,"table.resizeDetails":`生データパネルのサイズ変更`,"table.close":`閉じる`,"table.expand":`子を展開`,"table.collapse":`子を折りたたむ`,"table.removed":`このレコードは削除または確定済みです。現在のレコードを選択してください。`,"object.node":`ノード`,"object.nodeData":`ノードデータ`,"object.group":`グループ`,"object.groupData":`グループデータ`,"object.turn":`ターン`,"object.turnData":`ターンデータ`,"object.step":`ステップ`,"object.stepData":`ステップデータ`,"object.accessor":`[ゲッター / セッター、未評価]`,"object.empty":`空`,"object.absent":`[空のスロット]`,"object.properties":`その他のプロパティ`,"object.more":`さらに表示`,"object.navigation":`生データのナビゲーション`};const es={"tab.title":`Registro de sesión`,"tab.description":`Analice registros sin procesar y mensajes de chat agrupados para la sesión actual en la barra lateral.`,"view.presentation":`Presentación`,"view.sessionLog":`Registro crudo`,"view.chatNode":`grupo de chat`,"picker.pick":`Elige un elemento en la vista de chat`,"picker.cancel":`Cancelar selección (Esc)`,"picker.instructions":`Pase el cursor sobre el chat principal para obtener una vista previa y luego haga clic para seleccionar. Esc se cancela.`,"picker.noMatch":`No hay ningún registro coincidente en esta tabla. Elija otro elemento o presione Esc para cancelar.`,"picker.noChat":`Abre esta sesión en el chat principal antes de elegir.`,"table.id":`índice`,"table.type":`Tipo`,"filter.title":`Tipos de filtro`,"filter.input":`Escriba palabra clave`,"filter.placeholder":`Escriba un fragmento, p. delta`,"filter.help":`Contiene coincidencias (*palabra clave*). Enter confirma; Esc se cancela.`,"filter.candidates":`Escriba sugerencias`,"filter.loading":`Buscando sugerencias...`,"filter.failed":`No se pudieron cargar sugerencias de tipo.`,"filter.noCandidates":`Sin sugerencias. Aún puedes aplicar esta palabra clave.`,"filter.clear":`Borrar`,"filter.cancel":`Cancelar`,"filter.apply":`Aplicar filtro`,"filter.context":`Contexto principal de un registro coincidente`,"table.location":`T/S`,"table.time":`Hora (UTC)`,"table.data":`Datos`,"table.older":`Cargar antes`,"table.loading":`Cargando…`,"table.latest":`Seguir lo último`,"table.empty":`Sin registros`,"table.raw":`Datos sin procesar`,"table.rawError":`Este registro no se pudo serializar. Seleccione otro registro para continuar.`,"table.resizeDetails":`Cambiar el tamaño del panel de datos sin procesar`,"table.close":`Cerrar`,"table.expand":`Ampliar niños`,"table.collapse":`Colapso niños`,"table.removed":`Este registro fue eliminado o liquidado. Seleccione un registro actual.`,"object.node":`Nodo`,"object.nodeData":`Datos de nodo`,"object.group":`grupo`,"object.groupData":`Datos del grupo`,"object.turn":`Turno`,"object.turnData":`Datos del turno`,"object.step":`paso`,"object.stepData":`datos de paso`,"object.accessor":`[Getter/setter, no evaluado]`,"object.empty":`vacio`,"object.absent":`[Ranura vacía]`,"object.properties":`Otras propiedades`,"object.more":`Mostrar más`,"object.navigation":`Navegación de datos sin procesar`};const fr={"tab.title":`Journal de session`,"tab.description":`Analysez les journaux bruts et les messages de discussion groupés pour la session en cours dans la barre latérale.`,"view.presentation":`Présentation`,"view.sessionLog":`Journal brut`,"view.chatNode":`Groupe de discussion`,"picker.pick":`Choisissez un élément dans la vue de discussion`,"picker.cancel":`Annuler le prélèvement (Esc)`,"picker.instructions":`Passez la souris dans le chat principal pour prévisualiser, puis cliquez pour sélectionner. Esc annule.`,"picker.noMatch":`Aucun enregistrement correspondant dans ce tableau. Choisissez un autre élément ou appuyez sur Echap pour annuler.`,"picker.noChat":`Ouvrez cette session dans le chat principal avant de choisir.`,"table.id":`Indice`,"table.type":`Tapez`,"filter.title":`Types de filtres`,"filter.input":`Tapez le mot-clé`,"filter.placeholder":`Tapez un fragment, par ex. delta`,"filter.help":`Contient une correspondance (*mot-clé*). Entrez confirme\xA0; Esc annule.`,"filter.candidates":`Tapez des suggestions`,"filter.loading":`Trouver des suggestions…`,"filter.failed":`Les suggestions de types n'ont pas pu être chargées.`,"filter.noCandidates":`Aucune suggestion. Vous pouvez toujours appliquer ce mot-clé.`,"filter.clear":`Effacer`,"filter.cancel":`Annuler`,"filter.apply":`Appliquer le filtre`,"filter.context":`Contexte parent d'un enregistrement correspondant`,"table.location":`T/S`,"table.time":`Heure (UTC)`,"table.data":`Données`,"table.older":`Charger plus tôt`,"table.loading":`Chargement…`,"table.latest":`Suivre les dernières`,"table.empty":`Aucun enregistrement`,"table.raw":`Données brutes`,"table.rawError":`Cet enregistrement n'a pas pu être sérialisé. Sélectionnez un autre enregistrement pour continuer.`,"table.resizeDetails":`Redimensionner le panneau de données brutes`,"table.close":`Fermer`,"table.expand":`Développer les enfants`,"table.collapse":`Réduire les enfants`,"table.removed":`Cet enregistrement a été supprimé ou réglé. Sélectionnez un enregistrement actuel.`,"object.node":`Nœud`,"object.nodeData":`Données de nœud`,"object.group":`Groupe`,"object.groupData":`Données de groupe`,"object.turn":`Tour`,"object.turnData":`Données du tour`,"object.step":`Étape`,"object.stepData":`Données d'étape`,"object.accessor":`[Getter/setter, non évalué]`,"object.empty":`Vide`,"object.absent":`[Emplacement vide]`,"object.properties":`Autres propriétés`,"object.more":`Afficher plus`,"object.navigation":`Navigation dans les données brutes`};const de={"tab.title":`Sitzungsprotokoll`,"tab.description":`Analysieren Sie Rohprotokolle und gruppierte Chat-Nachrichten für die aktuelle Sitzung in der Seitenleiste.`,"view.presentation":`Präsentation`,"view.sessionLog":`Rohprotokoll`,"view.chatNode":`Chat-Gruppe`,"picker.pick":`Wählen Sie ein Element in der Chat-Ansicht aus`,"picker.cancel":`Kommissionierung abbrechen (Esc)`,"picker.instructions":`Bewegen Sie den Mauszeiger über den Hauptchat, um eine Vorschau anzuzeigen, und klicken Sie dann zum Auswählen. Esc bricht ab.`,"picker.noMatch":`Kein passender Datensatz in dieser Tabelle. Wählen Sie ein anderes Element aus oder drücken Sie Esc, um den Vorgang abzubrechen.`,"picker.noChat":`Öffnen Sie diese Sitzung im Hauptchat, bevor Sie eine Auswahl treffen.`,"table.id":`Index`,"table.type":`Typ`,"filter.title":`Filtertypen`,"filter.input":`Geben Sie das Schlüsselwort ein`,"filter.placeholder":`Geben Sie ein Fragment ein, z.\xA0B. Delta`,"filter.help":`Enthält passendes (*Schlüsselwort*). Enter bestätigt; Esc bricht ab.`,"filter.candidates":`Typvorschläge`,"filter.loading":`Vorschläge finden…`,"filter.failed":`Typvorschläge konnten nicht geladen werden.`,"filter.noCandidates":`Keine Vorschläge. Sie können dieses Schlüsselwort weiterhin anwenden.`,"filter.clear":`Klar`,"filter.cancel":`Abbrechen`,"filter.apply":`Filter anwenden`,"filter.context":`Übergeordneter Kontext eines übereinstimmenden Datensatzes`,"table.location":`T/S`,"table.time":`Zeit (UTC)`,"table.data":`Daten`,"table.older":`Früher laden`,"table.loading":`Laden…`,"table.latest":`Folgen Sie dem neuesten Stand`,"table.empty":`Keine Aufzeichnungen`,"table.raw":`Rohdaten`,"table.rawError":`Dieser Datensatz konnte nicht serialisiert werden. Wählen Sie einen anderen Datensatz aus, um fortzufahren.`,"table.resizeDetails":`Größe des Rohdatenbereichs ändern`,"table.close":`Schließen`,"table.expand":`Erweitern Sie Kinder`,"table.collapse":`Kinder zusammenbrechen lassen`,"table.removed":`Dieser Datensatz wurde entfernt oder erledigt. Wählen Sie einen aktuellen Datensatz aus.`,"object.node":`Knoten`,"object.nodeData":`Knotendaten`,"object.group":`Gruppe`,"object.groupData":`Gruppendaten`,"object.turn":`Runde`,"object.turnData":`Rundendaten`,"object.step":`Schritt`,"object.stepData":`Schrittdaten`,"object.accessor":`[Getter/Setter, nicht ausgewertet]`,"object.empty":`Leer`,"object.absent":`[Leerer Steckplatz]`,"object.properties":`Andere Eigenschaften`,"object.more":`Mehr anzeigen`,"object.navigation":`Rohdatennavigation`};const ru={"tab.title":`Журнал сеанса`,"tab.description":`Анализируйте необработанные журналы и сгруппированные сообщения чата для текущего сеанса на боковой панели.`,"view.presentation":`Презентация`,"view.sessionLog":`Необработанный журнал`,"view.chatNode":`Группа чата`,"picker.pick":`Выберите элемент в представлении чата`,"picker.cancel":`Отменить выбор (Esc)`,"picker.instructions":`Наведите указатель мыши на главный чат, чтобы просмотреть его, затем нажмите, чтобы выбрать. Esc отменяет.`,"picker.noMatch":`В этой таблице нет соответствующей записи. Выберите другой элемент или нажмите Esc для отмены.`,"picker.noChat":`Прежде чем выбирать, откройте эту сессию в главном чате.`,"table.id":`Индекс`,"table.type":`Тип`,"filter.title":`Типы фильтров`,"filter.input":`Введите ключевое слово`,"filter.placeholder":`Введите фрагмент, например. дельта`,"filter.help":`Содержит совпадение (*ключевое слово*). Enter подтверждает; Esc отменяет.`,"filter.candidates":`Введите предложения`,"filter.loading":`Поиск предложений…`,"filter.failed":`Не удалось загрузить предлагаемые типы.`,"filter.noCandidates":`Никаких предложений. Вы все еще можете применить это ключевое слово.`,"filter.clear":`Очистить`,"filter.cancel":`Отмена`,"filter.apply":`Применить фильтр`,"filter.context":`Родительский контекст соответствующей записи`,"table.location":`T/S`,"table.time":`Время (UTC)`,"table.data":`Данные`,"table.older":`Загрузить раньше`,"table.loading":`Загрузка…`,"table.latest":`Следите за последними`,"table.empty":`Нет записей`,"table.raw":`Необработанные данные`,"table.rawError":`Эту запись не удалось сериализовать. Выберите другую запись, чтобы продолжить.`,"table.resizeDetails":`Изменение размера панели необработанных данных`,"table.close":`Закрыть`,"table.expand":`Развернуть детей`,"table.collapse":`Свернуть детей`,"table.removed":`Этот рекорд был удален или погашен. Выберите текущую запись.`,"object.node":`Узел`,"object.nodeData":`Данные узла`,"object.group":`Группа`,"object.groupData":`Групповые данные`,"object.turn":`Ход`,"object.turnData":`Данные хода`,"object.step":`Шаг`,"object.stepData":`Данные шага`,"object.accessor":`[Получатель/сеттер, не оценивается]`,"object.empty":`Пустой`,"object.absent":`[Пустой слот]`,"object.properties":`Другие объекты недвижимости`,"object.more":`Показать больше`,"object.navigation":`Навигация по необработанным данным`};const pt={"tab.title":`Registro da sessão`,"tab.description":`Analise logs brutos e mensagens de bate-papo agrupadas da sessão atual na barra lateral.`,"view.presentation":`Apresentação`,"view.sessionLog":`Registro bruto`,"view.chatNode":`Grupo de bate-papo`,"picker.pick":`Escolha um elemento na visualização do chat`,"picker.cancel":`Cancelar seleção (Esc)`,"picker.instructions":`Passe o mouse no chat principal para visualizar e clique para selecionar. Esc cancela.`,"picker.noMatch":`Nenhum registro correspondente nesta tabela. Escolha outro elemento ou pressione Esc para cancelar.`,"picker.noChat":`Abra esta sessão no chat principal antes de escolher.`,"table.id":`Índice`,"table.type":`Tipo`,"filter.title":`Tipos de filtro`,"filter.input":`Digite palavra-chave`,"filter.placeholder":`Digite um fragmento, por ex. delta`,"filter.help":`Contém correspondência (*palavra-chave*). Digite confirma; Esc cancela.`,"filter.candidates":`Digite sugestões`,"filter.loading":`Encontrando sugestões…`,"filter.failed":`Não foi possível carregar as sugestões de tipo.`,"filter.noCandidates":`Sem sugestões. Você ainda pode aplicar esta palavra-chave.`,"filter.clear":`Limpar`,"filter.cancel":`Cancelar`,"filter.apply":`Aplicar filtro`,"filter.context":`Contexto pai de um registro correspondente`,"table.location":`T/S`,"table.time":`Hora (UTC)`,"table.data":`Dados`,"table.older":`Carregar mais cedo`,"table.loading":`Carregando…`,"table.latest":`Siga as últimas`,"table.empty":`Sem registros`,"table.raw":`Dados brutos`,"table.rawError":`Este registro não pôde ser serializado. Selecione outro registro para continuar.`,"table.resizeDetails":`Redimensionar painel de dados brutos`,"table.close":`Fechar`,"table.expand":`Expandir filhos`,"table.collapse":`Recolher filhos`,"table.removed":`Este registro foi removido ou resolvido. Selecione um registro atual.`,"object.node":`Nó`,"object.nodeData":`Dados do nó`,"object.group":`Grupo`,"object.groupData":`Dados do grupo`,"object.turn":`Turno`,"object.turnData":`Dados do turno`,"object.step":`Passo`,"object.stepData":`Dados da etapa`,"object.accessor":`[Getter/setter, não avaliado]`,"object.empty":`Vazio`,"object.absent":`[Slot vazio]`,"object.properties":`Outras propriedades`,"object.more":`Mostrar mais`,"object.navigation":`Navegação de dados brutos`};function inspectorRowCollapsed(row,choices){const choice=choices.get(row.key);return choice!==void 0&&choice.state===row.disclosure?choice.collapsed:row.disclosure===`closed`}var InspectorTableHierarchy=class{rows;byKey=new Map;branches=new Set;constructor(rows,choices){const visible=[];let hiddenDepth;for(const row of rows){if(row.parent!==void 0)this.branches.add(row.parent);if(row.disclosure!==void 0)this.branches.add(row.key);if(hiddenDepth!==void 0&&row.depth>hiddenDepth)continue;hiddenDepth=inspectorRowCollapsed(row,choices)?row.depth:void 0;this.byKey.set(row.key,visible.length);visible.push(row)}this.rows=visible}isBranch(key){return this.branches.has(key)}stickyIndexes(index){const indexes=[];let row=this.rows[index];if(row!==void 0&&this.isBranch(row.key))indexes.push(index);while(row?.parent!==void 0){const parent=this.byKey.get(row.parent);if(parent===void 0)break;indexes.push(parent);row=this.rows[parent]}return indexes.reverse()}};var InspectorRecordSource=class{source;project;previous;snapshot;constructor(source,project){this.source=source;this.project=project}getSnapshot=()=>{const value=this.source.getSnapshot();if(value!==this.previous){this.previous=value;this.snapshot=value===void 0?void 0:this.project(value)}return this.snapshot};subscribe=listener=>this.source.subscribe(listener)};const INSPECTOR_PREVIEW_LIMIT=240;const DELTA_PREVIEW_FIELDS=new Map([[`tool-call-delta`,[`argumentsDelta`]],[`reasoning-delta`,[`text`]]]);function preview(value,depth,hiddenRootFields){if(typeof value===`string`)return value.slice(0,180);if(value===null||typeof value!==`object`)return String(value);if(depth>1)return Array.isArray(value)?`[${value.length}]`:`{…}`;const fields=`type`in value&&typeof value.type===`string`?DELTA_PREVIEW_FIELDS.get(value.type):void 0;const entries=Object.entries(value).filter(([key])=>!(depth===0&&(key.toLowerCase()===`time`||hiddenRootFields.includes(key)))&&(fields===void 0?![`type`,`seq`,`sequence`].includes(key.toLowerCase()):fields.includes(key)));const[first,second]=entries;if(first!==void 0&&second===void 0)return preview(first[1],depth+1,hiddenRootFields);return entries.slice(0,5).map(([key,item])=>`${key}: ${preview(item,depth+1,hiddenRootFields)}`).join(` · `).slice(0,240)}function inspectorPreview(value,hiddenRootFields=[]){return preview(value,0,hiddenRootFields)}var ChatObjectIndex=class{binding;identities=new WeakMap;indexed=new WeakSet;constructor(binding){this.binding=binding}reference(value){this.refresh();return this.identities.get(value)}chat(){return this.binding.snapshot.getSnapshot().views.get(`chat`)}register(value,reference){if(value!==null&&typeof value===`object`&&!this.identities.has(value))this.identities.set(value,reference)}location(value,step){const turn=value.turn;const identity=step===void 0?String(turn):`${turn}/${step}`;const kind=step===void 0?`turn`:`step`;const read=()=>{const current=this.chat()?.timeline.turns.get(turn);return step===void 0?current:current?.steps.find(value=>value.step===step)};const firstNode=step===void 0?this.chat()?.locations.getTurn(turn)[0]:this.chat()?.locations.getStep(turn,step)[0];const target={turn,...firstNode===void 0?{}:{nodeKey:firstNode}};this.register(value,{id:`${kind}:${identity}`,kind,identity,target,read});this.register(value.data,{id:`${kind}-data:${identity}`,kind:step===void 0?`turnData`:`stepData`,identity,target,read:()=>read()?.data})}refresh(){const chat=this.chat();if(chat===void 0)return;const nodes=chat.nodes.values();if(!this.indexed.has(nodes)){this.indexed.add(nodes);for(const node of nodes){const{key,location}=node;const turn=location.kind===`turn`||location.kind===`step`?location.turn.turn:void 0;const target={nodeKey:key,...turn===void 0?{}:{turn}};this.register(node,{id:`node:${key}`,kind:`node`,identity:key,target,read:()=>this.chat()?.nodes.get(key)});this.register(node.data,{id:`node-data:${key}`,kind:`nodeData`,identity:key,target,read:()=>this.chat()?.nodes.get(key)?.data})}}if(!this.indexed.has(chat.timeline)){this.indexed.add(chat.timeline);for(const turn of chat.timeline.turns.values()){this.location(turn);for(const step of turn.steps)this.location(step,step.step)}}const groups=this.binding.snapshot.getSnapshot().views.grouped(`chat`);for(const entry of groups?.entries??[]){if(entry.kind!==`group`)continue;const key=entry.key;const group=groups.groupSource(key).getSnapshot();if(group===void 0||this.indexed.has(group))continue;this.indexed.add(group);const target={groupKey:key};const read=()=>this.binding.snapshot.getSnapshot().views.grouped(`chat`)?.groupSource(key).getSnapshot();this.register(group,{id:`group:${key}`,kind:`group`,identity:key,target,read});this.register(group.data,{id:`group-data:${key}`,kind:`groupData`,identity:key,target,read:()=>read()?.data});for(const member of group.members){const nodeKey=member.key;this.register(member,{id:`node:${nodeKey}`,kind:`node`,identity:nodeKey,target:{nodeKey,...member.groupPart===void 0?{}:{groupPart:member.groupPart}},read:()=>this.chat()?.nodes.get(nodeKey)})}}}};function displayed(element){if(!element.isConnected||element.closest(`[hidden]`)!==null)return false;for(let parent=element;parent!==null;parent=parent.parentElement){const style=getComputedStyle(parent);if(style.display===`none`||style.visibility===`hidden`)return false}return true}function mainChatRoot(){return[...document.querySelectorAll(`[data-slot="main.conversation"] [data-slot="conversation.view"] [data-chat-flow]`)].find(element=>element.closest(`[data-sidebar-right-session], [data-step-process-body]`)===null&&displayed(element))}function inChat(element,root){return root.contains(element)&&element.closest(`[data-sidebar-right-session]`)===null&&element.closest(`[data-slot="conversation.view"]`)===root.closest(`[data-slot="conversation.view"]`)}function findChatTargets(root,targets){const fields=[`chatCallId`,`chatNodeKey`,`chatGroupKey`,`chatTurn`];const indexed={chatCallId:new Map,chatNodeKey:new Map,chatGroupKey:new Map,chatTurn:new Map};for(const element of root.querySelectorAll(`[data-chat-call-id], [data-chat-node-key], [data-chat-group-key], [data-chat-turn]`)){if(!inChat(element,root))continue;for(const field of fields){const value=element.dataset[field];if(value===void 0)continue;const matches=indexed[field].get(value);if(matches===void 0)indexed[field].set(value,[element]);else matches.push(element)}}const found=new Set;const add=(field,value,part)=>{if(value===void 0)return;for(const element of indexed[field].get(value)??[])if(part===void 0||element.dataset.chatGroupPart===part)found.add(element)};const turns=new Set;const preferredTurn=targets.find(target=>target.turn!==void 0)?.turn;let preferredTurnAdded=false;for(const[index,target]of targets.entries()){if(index>0&&preferredTurn!==void 0&&target.turn!==preferredTurn&&!preferredTurnAdded){add(`chatTurn`,String(preferredTurn));preferredTurnAdded=true}add(`chatCallId`,target.callId);add(`chatNodeKey`,target.nodeKey,target.groupPart);add(`chatNodeKey`,target.nodeKey);add(`chatCallId`,target.rootCallId);add(`chatGroupKey`,target.groupKey);if(target.turn!==void 0)turns.add(target.turn)}for(const turn of turns)if(!preferredTurnAdded||turn!==preferredTurn)add(`chatTurn`,String(turn));return[...found]}function matchChatElement(element,root){if(!inChat(element,root)||!displayed(root)||element.closest(`[hidden]`)!==null)return void 0;const closest=selector=>{const found=element.closest(selector);return found!==null&&inChat(found,root)&&displayed(found)?found:void 0};const node=closest(`[data-chat-node-key]`);const call=closest(`[data-chat-call-id]`);const group=closest(`[data-chat-group-key]`);const turnElement=closest(`[data-chat-turn]`);const box=call??node??group??turnElement;if(box===void 0)return void 0;const turnValue=turnElement?.dataset.chatTurn;const turn=turnValue===void 0||turnValue===``?void 0:Number(turnValue);return{element:box,target:{...node?.dataset.chatNodeKey===void 0?{}:{nodeKey:node.dataset.chatNodeKey},...node?.dataset.chatGroupPart===void 0?{}:{groupPart:node.dataset.chatGroupPart},...node?.dataset.chatFlowKind===void 0?{}:{nodeKind:node.dataset.chatFlowKind},...call?.dataset.chatCallId===void 0?{}:{callId:call.dataset.chatCallId},...group?.dataset.chatGroupKey===void 0?{}:{groupKey:group.dataset.chatGroupKey},...turn!==void 0&&Number.isSafeInteger(turn)&&turn>=0?{turn}:{}}}}function matchChatNodeRow(target,rows){const entries=[...rows];if(target.nodeKey!==void 0){const nodes=entries.filter(([,row])=>row.nodeKey===target.nodeKey);const exact=nodes.find(([,row])=>row.groupPart===target.groupPart)??nodes[0];if(exact!==void 0)return exact[0]}if(target.groupKey!==void 0){const group=entries.find(([,row])=>row.groupKey===target.groupKey&&row.nodeKey===void 0);if(group!==void 0)return group[0]}if(target.turn===void 0)return void 0;const turn=entries.filter(([,row])=>row.turn===target.turn);return(target.step===void 0?turn[0]:turn.find(([,row])=>row.step===target.step)??turn[0])?.[0]}const EMPTY=[];const COLUMN_FIELDS=[`key`,`kind`];function nodeRecord(node){const location=node.location;return{type:node.kind,identity:node.key,location:location.kind===`step`?`${location.turn.turn}/${location.step.step}`:location.kind===`turn`?String(location.turn.turn):location.kind,value:node,summary:inspectorPreview(node,COLUMN_FIELDS)}}var ChatNodeModel=class{binding;rows=(0,_unieai_rabi_client_store.createSnapshotStore)(EMPTY);sources=new Map;groups=new Map;entries;order;keys;anchors;nodeStore;grouped;subscribers=0;disconnect;queued=false;targets=new Map;objectIndex;constructor(binding){this.binding=binding;this.objectIndex=new ChatObjectIndex(binding);this.refresh()}objects(sessionId){const reference=value=>{const found=this.objectIndex.reference(value);if(found===void 0)return void 0;const row=[...this.targets].find(([,target])=>found.target.nodeKey!==void 0?target.nodeKey===found.target.nodeKey&&(found.target.groupPart===void 0||target.groupPart===found.target.groupPart):found.target.groupKey!==void 0&&target.groupKey===found.target.groupKey);return{...found,...row===void 0?{}:{rowKey:row[0]}}};return{sessionId,updates:this.binding.snapshot,reference,row:key=>{const value=this.row(key)?.getSnapshot()?.value;if(value===null||typeof value!==`object`)return void 0;const found=reference(value);const target=this.targets.get(key);return found===void 0||target===void 0?void 0:{...found,rowKey:key,target}}}}getSnapshot=()=>this.rows.getSnapshot();pick(target){this.refresh(true);return matchChatNodeRow(target,this.targets)}subscribe=listener=>{const stop=this.rows.subscribe(listener);if(this.subscribers++===0){this.disconnect=this.binding.snapshot.subscribe(()=>{this.refresh()});this.binding.activate(`chat`);this.refresh(true)}return()=>{stop();if(--this.subscribers===0){this.disconnect?.();this.disconnect=void 0;for(const stop of this.groups.values())stop();this.groups.clear()}}};row=key=>this.sources.get(key);refresh(force=false){const snapshot=this.binding.snapshot.getSnapshot();const chat=snapshot.views.get(`chat`);const grouped=snapshot.views.grouped(`chat`);const nodes=chat?.nodes.values();const sameKeys=nodes===void 0?this.keys===void 0:nodes.length===this.keys?.length&&nodes.every((node,index)=>node.key===this.keys?.[index]&&node.anchorSeq===this.anchors?.[index]);if(!force&&chat?.order===this.order&&chat?.nodes===this.nodeStore&&sameKeys&&grouped===this.grouped&&grouped?.entries===this.entries)return;this.order=chat?.order;this.entries=grouped?.entries;this.keys=nodes?.map(node=>node.key);this.anchors=nodes?.map(node=>node.anchorSeq);if(grouped!==this.grouped){for(const stop of this.groups.values())stop();this.groups.clear();this.sources.clear()}this.grouped=grouped;if(chat?.nodes!==this.nodeStore)this.sources.clear();this.nodeStore=chat?.nodes;const activeGroups=new Set;this.targets.clear();const rows=[];const addNode=(entry,parent)=>{const key=`node:${entry.key}:${entry.groupPart??``}`;const location=chat?.nodes.get(entry.key)?.location;const turn=location?.kind===`turn`||location?.kind===`step`?location.turn.turn:void 0;const step=location?.kind===`step`?location.step.step:void 0;this.targets.set(key,{nodeKey:entry.key,...entry.groupPart===void 0?{}:{groupPart:entry.groupPart},...turn===void 0?{}:{turn},...step===void 0?{}:{step}});rows.push({key,depth:parent===void 0?0:1,...parent===void 0?{}:{parent}});if(!this.sources.has(key)&&chat!==void 0)this.sources.set(key,new InspectorRecordSource(chat.nodes.source(entry.key),node=>{const record=nodeRecord(node);return entry.groupPart===void 0?record:{...record,identity:`${node.key}#${entry.groupPart}`}}))};const entries=grouped?.entries??chat?.order.map(key=>({kind:`node`,key}))??[];const included=new Set;const entryAnchors=entries.map(entry=>{const members=entry.kind===`node`?[entry]:grouped.groupSource(entry.key).getSnapshot()?.members??[];let anchor;for(const member of members){included.add(member.key);const seq=chat?.nodes.get(member.key)?.anchorSeq;if(seq!==void 0)anchor=anchor===void 0?seq:Math.min(anchor,seq)}return anchor});const unlisted=(nodes??[]).filter(node=>!included.has(node.key)).sort((left,right)=>left.anchorSeq-right.anchorSeq||left.key.localeCompare(right.key));let nextUnlisted=0;const addUnlistedBefore=anchor=>{let node=unlisted[nextUnlisted];while(node!==void 0&&node.anchorSeq<=anchor){addNode({key:node.key});node=unlisted[++nextUnlisted]}};for(const[index,entry]of entries.entries()){const anchor=entryAnchors[index];if(anchor!==void 0)addUnlistedBefore(anchor);if(entry.kind===`node`){addNode(entry);continue}activeGroups.add(entry.key);const key=`group:${entry.key}`;this.targets.set(key,{groupKey:entry.key});const source=grouped.groupSource(entry.key);const group=source.getSnapshot();rows.push({key,depth:0});if(!this.sources.has(key))this.sources.set(key,new InspectorRecordSource(source,value=>({type:`group`,identity:value.key,location:``,value,summary:inspectorPreview(value,COLUMN_FIELDS)})));for(const member of group?.members??[])addNode(member,key);if(this.subscribers>0&&!this.groups.has(entry.key)){let members=group?.members;const stop=source.subscribe(()=>{const next=source.getSnapshot()?.members;if(next===members)return;members=next;this.schedule()});this.groups.set(entry.key,stop)}}addUnlistedBefore(Infinity);for(const[key,stop]of this.groups)if(!activeGroups.has(key)){stop();this.groups.delete(key)}const rowKeys=new Set(rows.map(row=>row.key));for(const key of this.sources.keys())if(!rowKeys.has(key))this.sources.delete(key);this.rows.set(rows)}schedule(){if(this.queued)return;this.queued=true;queueMicrotask(()=>{this.queued=false;if(this.subscribers>0)this.refresh(true)})}};const SIMPLE_ESCAPES={'"':`"`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
3
+ `,r:`\r`,t:` `};const CONTENT_ESCAPE=/[\\\u0000-\u001f]/u;function isWhitespace(c){return c===` `||c===`
4
+ `||c===`\r`||c===` `}function isHex(c){return c>=`0`&&c<=`9`||c>=`a`&&c<=`f`||c>=`A`&&c<=`F`}var PartialArguments=class PartialArguments{static EMPTY=PartialArguments.fromObject({});static fromText(text){const view=new PartialArguments;view.append(text);view.sealed=true;return view}static fromObject(value){const view=new PartialArguments;view.object=typeof value===`object`&&value!==null&&!Array.isArray(value)?value:{};view.sealed=true;return view}chunks=[];object;sealed=false;#ends=[];#size=0;#consumed=0;#mode=`root`;#escape=false;#keyStart=0;#keyEscaped=false;#key=``;#current=null;#nestedEnds=[];#nestedInString=false;#invalidAt;#invalidValue=false;#entries=new Map;#order=[];#reads=new Map;get isSealed(){return this.sealed}get invalid(){this.scan();return this.#mode===`invalid`||this.#invalidValue}append(fragment){if(this.sealed)throw new Error(`PartialArguments: cannot append to a sealed view`);if(fragment.length===0)return;this.chunks.push(fragment);this.#size+=fragment.length;this.#ends.push(this.#size)}settle(text){if(this.object!==void 0||text.length!==this.#size)return PartialArguments.fromText(text);let offset=0;for(const chunk of this.chunks){if(!text.startsWith(chunk,offset))return PartialArguments.fromText(text);offset+=chunk.length}this.chunks=text.length===0?[]:[text];this.#ends=text.length===0?[]:[text.length];this.sealed=true;return this}refresh(){if(this.#reads.size===0)return false;this.scan();let changed=false;let completions=false;for(const read of this.#reads.values()){if(read.completion){completions=true;continue}changed=this.refreshRead(read)||changed}if(completions){for(const read of this.#reads.values())if(read.completion)changed=this.refreshRead(read)||changed}if(this.sealed)this.#reads.clear();return changed}refreshRead(read){const now=read.answer();if(Object.is(now,read.last))return false;read.last=now;return true}closed(){return this.remember(`closed`,``,()=>this.closedNow())}keys(){return this.remember(`keys`,``,()=>this.keysNow(),keys=>keys.length)}has(key){return this.remember(`has`,key,()=>this.hasNow(key))}complete(key){return this.remember(`complete`,key,()=>this.completeNow(key))}stringLength(key,options){const step=Math.max(1,Math.floor(options?.step??1));const offset=options?.offset??0;return this.remember(`length:${step}:${offset}`,key,()=>this.lengthNow(key),length=>length===void 0?void 0:Math.ceil((length+offset)/step))}stringExceeds(key,maxLength){const limit=Math.max(0,Math.floor(maxLength));return this.remember(`exceeds:${limit}`,key,()=>(this.lengthNow(key,limit+1)??0)>limit)}text(key){return this.remember(`text`,key,()=>this.textNow(key))}textPrefix(key,maxLength){const limit=Math.max(1,Math.floor(maxLength));return this.remember(`prefix:${limit}`,key,()=>this.textPrefixNow(key,limit))}value(key){return this.remember(`value`,key,()=>this.valueNow(key))}remember(kind,key,read,comparison){this.scan();const result=read();if(!this.sealed){const id=`${kind}/${key}`;if(!this.#reads.has(id))this.#reads.set(id,{completion:kind===`complete`,answer:comparison===void 0?read:()=>comparison(read()),last:comparison===void 0?result:comparison(result)})}return result}closedNow(){return this.sealed||this.#mode===`closed`||this.#mode===`invalid`}keysNow(){return this.object===void 0?this.#order:Object.keys(this.object)}hasNow(key){return this.object===void 0?this.#entries.has(key):Object.hasOwn(this.object,key)}completeNow(key){if(this.object!==void 0)return Object.hasOwn(this.object,key);const entry=this.#entries.get(key);return entry!==void 0&&entry.end>=0&&(entry.kind===`string`?entry.invalidAt===void 0:!entry.invalid)}lengthNow(key,limit=Number.POSITIVE_INFINITY){if(this.object!==void 0){const field=Object.hasOwn(this.object,key)?this.object[key]:void 0;return typeof field===`string`?field.length:void 0}const entry=this.#entries.get(key);if(entry?.kind!==`string`)return void 0;if(entry.text!==void 0&&entry.text.at===entry.end)return entry.text.length;const read=entry.length??={at:entry.start,length:0,text:``};this.readString(entry,read,limit,false);return read.length}textNow(key){if(this.object!==void 0){const field=Object.hasOwn(this.object,key)?this.object[key]:void 0;return typeof field===`string`?field:void 0}const entry=this.#entries.get(key);if(entry?.kind!==`string`)return void 0;if(entry.text===void 0&&entry.end>=0&&entry.needsDecoding&&entry.invalidAt===void 0){let text;try{text=JSON.parse(`"${this.slice(entry.start,entry.end)}"`)}catch(_error){}if(text!==void 0)entry.text={at:entry.end,length:text.length,text}}const read=entry.text??={at:entry.start,length:0,text:``};this.readString(entry,read,Number.POSITIVE_INFINITY,true);return read.text}textPrefixNow(key,maxLength){if(this.object!==void 0){const field=Object.hasOwn(this.object,key)?this.object[key]:void 0;return typeof field===`string`?field.slice(0,maxLength):void 0}const entry=this.#entries.get(key);if(entry?.kind!==`string`)return void 0;const prefixes=entry.prefixes??=new Map;let read=prefixes.get(maxLength);if(read===void 0){read={at:entry.start,length:0,text:``};prefixes.set(maxLength,read)}this.readString(entry,read,maxLength,true);return read.text}valueNow(key){if(this.object!==void 0){if(!Object.hasOwn(this.object,key))return void 0;const field=this.object[key];return typeof field===`string`?void 0:field}const entry=this.#entries.get(key);if(entry?.kind!==`value`||entry.end<0||entry.invalid)return void 0;if(entry.parsed===void 0)try{entry.parsed=JSON.parse(this.slice(entry.start,entry.end))}catch(_error){entry.invalid=true;this.#invalidValue=true}return entry.parsed}chunkAt(at){let low=0;let high=this.#ends.length;while(low<high){const mid=low+high>>>1;if(this.#ends[mid]<=at)low=mid+1;else high=mid}return low}slice(start,end){if(start>=end)return``;const first=this.chunkAt(start);const last=this.chunkAt(end-1);const base=first===0?0:this.#ends[first-1];if(first===last)return this.chunks[first].slice(start-base,end-base);const parts=[this.chunks[first].slice(start-base)];for(let i=first+1;i<last;i++)parts.push(this.chunks[i]);parts.push(this.chunks[last].slice(0,end-this.#ends[last-1]));return parts.join(``)}readString(entry,read,limit,materialize){const end=Math.min(entry.end<0?this.#consumed:entry.end,entry.invalidAt??Number.POSITIVE_INFINITY,this.#invalidAt??Number.POSITIVE_INFINITY);if(!entry.needsDecoding){const length=Math.min(end-read.at,limit-read.length);if(length<=0)return;if(materialize)read.text+=this.slice(read.at,read.at+length);read.at+=length;read.length+=length;return}let chunkIndex=this.chunkAt(read.at);while(read.at<end&&read.length<limit){const base=chunkIndex===0?0:this.#ends[chunkIndex-1];const chunk=this.chunks[chunkIndex];const remaining=chunk.slice(read.at-base,Math.min(chunk.length,end-base));const boundary=remaining.search(CONTENT_ESCAPE);const length=Math.min(boundary<0?remaining.length:boundary,limit-read.length);if(length>0){if(materialize)read.text+=remaining.slice(0,length);read.at+=length;read.length+=length;if(read.at===base+chunk.length)chunkIndex++;continue}const type=remaining.length>1?remaining[1]:read.at+1<end?this.chunks[chunkIndex+1][0]:void 0;let decoded;let width=2;if(remaining[0]===`\\`&&type===void 0&&entry.end<0)return;if(remaining[0]===`\\`&&type===`u`){const hex=this.slice(read.at+2,Math.min(end,read.at+6));let valid=true;for(let i=0;i<hex.length;i++)if(!isHex(hex[i]))valid=false;if(valid){if(hex.length<4&&entry.end<0)return;if(hex.length===4)decoded=String.fromCharCode(Number.parseInt(hex,16))}width=6}else if(remaining[0]===`\\`&&type!==void 0)decoded=SIMPLE_ESCAPES[type];if(decoded===void 0){entry.invalidAt=read.at;this.#invalidValue=true;return}if(materialize)read.text+=decoded;read.length++;read.at+=width;while(chunkIndex<this.chunks.length&&read.at>=this.#ends[chunkIndex])chunkIndex++}}scan(){if(this.object!==void 0||this.#consumed===this.#size)return;for(let i=this.chunkAt(this.#consumed);i<this.chunks.length&&this.#invalidAt===void 0;i++){const pending=this.chunks[i];const base=i===0?0:this.#ends[i-1];for(let index=this.#consumed-base;index<pending.length&&this.#mode!==`invalid`;index++){if(this.#mode===`string`||this.#mode===`nested`&&this.#nestedInString){const end=this.stringBoundary(pending,index);this.#consumed+=end-index;index=end;if(index===pending.length)break}this.step(pending[index],this.#consumed);this.#consumed++}}}stringBoundary(fragment,start){let at=start;while(true){const quote=fragment.indexOf(`"`,at);const end=quote<0?fragment.length:quote;if(this.#mode===`string`){const entry=this.#current;if(!entry.needsDecoding&&CONTENT_ESCAPE.test(fragment.slice(at,end)))entry.needsDecoding=true}let slashStart=end;while(slashStart>at&&fragment[slashStart-1]===`\\`)slashStart--;const escaped=(end-slashStart)%2===1!==(slashStart===at&&this.#escape);this.#escape=quote<0&&escaped;if(quote<0||!escaped)return end;at=quote+1}}step(c,at){switch(this.#mode){case`root`:if(isWhitespace(c))return;if(c===`{`){this.#mode=`key-or-end`;return}this.fail();return;case`key-or-end`:if(isWhitespace(c))return;if(c===`}`){this.#mode=`closed`;return}if(c===`"`){this.beginKey(at);return}this.fail();return;case`key-only`:if(isWhitespace(c))return;if(c===`"`){this.beginKey(at);return}this.fail();return;case`key`:this.stepKey(c,at);return;case`colon`:if(isWhitespace(c))return;if(c===`:`){this.#mode=`value`;return}this.fail();return;case`value`:this.beginValue(c,at);return;case`string`:{const entry=this.#current;entry.end=at;this.#current=null;this.#mode=`comma-or-end`;return}case`scalar`:this.stepScalar(c,at);return;case`nested`:this.stepNested(c,at);return;case`comma-or-end`:if(isWhitespace(c))return;if(c===`,`){this.#mode=`key-only`;return}if(c===`}`){this.#mode=`closed`;return}this.fail();return;case`closed`:if(isWhitespace(c))return;this.fail();return;case`invalid`:return;default:assertNever(this.#mode)}}fail(){this.#invalidAt=this.#consumed;this.#mode=`invalid`;this.#current=null}beginKey(at){this.#mode=`key`;this.#keyStart=at+1;this.#keyEscaped=false;this.#escape=false}stepKey(c,at){if(c<` `){this.fail();return}if(this.#escape){this.#escape=false;return}if(c===`\\`){this.#escape=true;this.#keyEscaped=true;return}if(c!==`"`)return;const raw=this.slice(this.#keyStart,at);if(this.#keyEscaped)try{this.#key=JSON.parse(`"${raw}"`)}catch(_error){this.fail();return}else this.#key=raw;this.#mode=`colon`}open(entry){if(!this.#entries.has(this.#key))this.#order.push(this.#key);this.#entries.set(this.#key,entry);this.#current=entry}beginValue(c,at){if(isWhitespace(c))return;if(c===`"`){this.open({kind:`string`,start:at+1,end:-1,needsDecoding:false,invalidAt:void 0,length:void 0,text:void 0,prefixes:void 0});this.#escape=false;this.#mode=`string`;return}if(c===`}`||c===`,`||c===`:`||c===`]`){this.fail();return}this.open({kind:`value`,start:at,end:-1,parsed:void 0,invalid:false});if(c===`{`||c===`[`){this.#mode=`nested`;this.#nestedEnds=[c===`{`?`}`:`]`];this.#nestedInString=false;this.#escape=false;return}this.#mode=`scalar`}stepScalar(c,at){if(c!==`,`&&c!==`}`&&!isWhitespace(c))return;this.closeValue(at);this.#mode=c===`,`?`key-only`:c===`}`?`closed`:`comma-or-end`}stepNested(c,at){if(this.#nestedInString){this.#nestedInString=false;return}if(c===`"`){this.#nestedInString=true;return}if(c===`{`||c===`[`){this.#nestedEnds.push(c===`{`?`}`:`]`);return}if(c===`}`||c===`]`){if(this.#nestedEnds.pop()!==c){this.fail();return}if(this.#nestedEnds.length===0){this.closeValue(at+1);this.#mode=`comma-or-end`}}}closeValue(end){const entry=this.#current;entry.end=end;this.#current=null}};function assertNever(value,context){const rendered=JSON.stringify(value)??String(value);throw new Error(`unreachable variant${context?` in ${context}`:``}: ${rendered}`)}function hasIntrinsicConstructor(prototype,name){const constructor=Object.getOwnPropertyDescriptor(prototype,`constructor`)?.value;if(typeof constructor!==`function`)return false;try{return constructor.name===name&&constructor.prototype===prototype&&Function.prototype.toString.call(constructor)===Function.prototype.toString.call(name===`Array`?Array:Object)}catch{return false}}function isIntrinsicObjectPrototype(value){return Object.getPrototypeOf(value)===null&&hasIntrinsicConstructor(value,`Object`)}function hasPlainArrayPrototype(value){const prototype=Object.getPrototypeOf(value);if(!Array.isArray(prototype)||!hasIntrinsicConstructor(prototype,`Array`))return false;const objectPrototype=Object.getPrototypeOf(prototype);return typeof objectPrototype===`object`&&objectPrototype!==null&&isIntrinsicObjectPrototype(objectPrototype)}function hasPlainObjectPrototype(value){const prototype=Object.getPrototypeOf(value);return prototype===null||typeof prototype===`object`&&isIntrinsicObjectPrototype(prototype)}function enumerableStringKeys(value){const keys=Reflect.ownKeys(value);if(keys.some(key=>typeof key!==`string`||!Object.prototype.propertyIsEnumerable.call(value,key)))return void 0;return keys}function walkJsonValue(value,detach){const ancestors=new Set;let root;let parent;const assign=item=>{if(parent===void 0){if(detach)root=item}else if(parent.kind===`array`){if(parent.target!==void 0)parent.target[parent.key]=item}else if(parent.target!==void 0)Object.defineProperty(parent.target,parent.key,{value:item,enumerable:true,configurable:true,writable:true})};const frames=[];let current=value;for(;;){if(current===null)assign(null);else if(typeof current===`boolean`||typeof current===`string`)assign(current);else if(typeof current===`number`){if(!Number.isFinite(current)||Object.is(current,-0))return void 0;assign(current)}else{if(typeof current!==`object`)return void 0;if(ancestors.has(current))return void 0;if(Array.isArray(current)){if(!hasPlainArrayPrototype(current))return void 0;const length=current.length;if(Reflect.ownKeys(current).length!==length+1)return void 0;const target=detach?[]:void 0;if(target!==void 0)assign(target);let indices;if(!Number.isInteger(length)){indices=[];for(let index=length-1;index>=0;index--)indices.push(index)}frames.push({kind:`array`,source:current,length:indices?.length??length,index:0,key:0,indices,target})}else{if(!hasPlainObjectPrototype(current))return void 0;const keys=enumerableStringKeys(current);if(keys===void 0)return void 0;const target=detach?{}:void 0;if(target!==void 0)assign(target);frames.push({kind:`object`,source:current,keys,index:0,key:``,target})}ancestors.add(current)}for(;;){const frame=frames.at(-1);if(frame===void 0)return detach?root:true;const length=frame.kind===`array`?frame.length:frame.keys.length;if(frame.index>=length){ancestors.delete(frame.source);frames.pop();continue}const index=frame.index++;parent=frame;if(frame.kind===`array`){const key=frame.indices===void 0?index:frame.indices[frame.indices.length-index-1];if(key===void 0)return void 0;if(!Object.prototype.hasOwnProperty.call(frame.source,key))return void 0;frame.key=key;current=frame.source[key]}else{const key=frame.keys[index];if(key===void 0)return void 0;frame.key=key;current=frame.source[key]}break}}}function snapshotJsonValue(value){return walkJsonValue(value,true)}function deepFreeze(value){const seen=new WeakSet;const pending=[{kind:`visit`,node:value}];while(pending.length>0){const task=pending.pop();if(task===void 0)continue;if(task.kind===`property`){pending.push({kind:`visit`,node:task.source[task.key]});continue}const node=task.node;if(node===null||typeof node!==`object`)continue;if(node instanceof AbortSignal)continue;if(seen.has(node))continue;seen.add(node);Object.freeze(node);const keys=Object.keys(node);for(let index=keys.length-1;index>=0;index--){const key=keys[index];if(key===void 0)continue;pending.push({kind:`property`,source:node,key})}}return value}function safeTime(value){if(!Number.isSafeInteger(value))throw new TypeError(`Assistant stream time must be a safe integer, got ${String(value)}`);return value}function safeIndex(value,label){if(!Number.isSafeInteger(value)||value<0||Object.is(value,-0))throw new TypeError(`${label} index must be a non-negative safe integer`);return value}function snapshotChunk(chunk){const snapshot=snapshotJsonValue(chunk);if(snapshot===void 0)throw new TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return snapshot}function expandAssistantStream(stream){const chunks=[];for(const candidate of stream){const record=validateRecord(candidate);if(record.type===`chunk`){chunks.push({time:record.time,chunk:record.chunk});continue}const members=record.type===`tool-call-chunks`?record.args:record.texts;let time=record.time0;for(let index=0;index<members.length;index+=1){if(index>0)time+=record.dt[index-1];let chunk;if(record.type===`text-chunks`)chunk={type:`text-delta`,index:record.index,text:members[index]};else if(record.type===`reasoning-chunks`)chunk={type:`reasoning-delta`,index:record.index,text:members[index]};else chunk={type:`tool-call-delta`,index:record.index,id:record.id,...Object.hasOwn(record,`name`)?{name:record.name}:{},argumentsDelta:members[index]};chunks.push({time,chunk})}}return chunks}function validateRecord(value){if(typeof value!==`object`||value===null||Array.isArray(value))throw new TypeError(`Assistant stream record must be an object`);const record=value;switch(record.type){case`text-chunks`:case`reasoning-chunks`:{exactKeys(record,[`type`,`time0`,`index`,`dt`,`texts`],record.type);const texts=stringArray(record.texts,`${record.type} texts`);if(texts.length===0)throw new TypeError(`${record.type} texts must be non-empty`);validateRun(record,texts.length,record.type);return record}case`tool-call-chunks`:{exactKeys(record,Object.hasOwn(record,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],record.type);const args=stringArray(record.args,`tool-call-chunks args`);if(args.length===0)throw new TypeError(`tool-call-chunks args must be non-empty`);if(typeof record.id!==`string`||record.id.length===0)throw new TypeError(`tool-call-chunks id must be a non-empty string`);if(record.name!==void 0&&(typeof record.name!==`string`||record.name.length===0))throw new TypeError(`tool-call-chunks name must be a non-empty string`);validateRun(record,args.length,record.type);return record}case`chunk`:{exactKeys(record,[`type`,`time`,`chunk`],`chunk`);const time=safeTime(record.time);if(typeof record.chunk!==`object`||record.chunk===null||Array.isArray(record.chunk))throw new TypeError(`Assistant stream raw chunk must be a lossless JSON object`);let chunk;try{chunk=snapshotChunk(record.chunk)}catch(error){throw new TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:error})}return deepFreeze({type:`chunk`,time,chunk})}default:throw new TypeError(`Unsupported Assistant stream record ${JSON.stringify(record.type)}`)}}function validateRun(record,members,label){safeTime(record.time0);safeIndex(record.index,label);if(!Array.isArray(record.dt)||record.dt.some(value=>!Number.isSafeInteger(value)))throw new TypeError(`${label} dt must contain safe integers`);if(record.dt.length!==members-1)throw new TypeError(`${label} dt length must be one less than its members`);let time=record.time0;for(const gap of record.dt){time+=gap;if(!Number.isSafeInteger(time))throw new TypeError(`${label} member times must stay safe integers`)}}function stringArray(value,label){if(!Array.isArray(value)||value.some(member=>typeof member!==`string`))throw new TypeError(`${label} must be a string array`);return value}function exactKeys(record,keys,label){if(Object.keys(record).length!==keys.length||!keys.every(key=>Object.hasOwn(record,key)))throw new TypeError(`${label} Assistant stream record must contain exactly ${keys.join(`, `)}`)}var AssistantLogStream=class{parent;blocks=new Map;count=0;constructor(parent){this.parent=parent}get length(){return this.count}append(chunk){const index=this.count++;const key=`${this.parent}/chunk:${index}`;let position=index;let row={key,parent:this.parent,depth:1};let header;let block;if(chunk.type===`block-start`){block={row:{...row,disclosure:`open`},offset:index,children:0,...chunk.blockType===`reasoning`?{reasoningText:``}:{}};row=block.row;this.blocks.set(chunk.index,block)}else{block=`index`in chunk?this.blocks.get(chunk.index):void 0;if(block!==void 0){position=block.offset+1+block.children++;row={key,parent:block.row.key,depth:2};for(const following of this.blocks.values())if(following.offset>block.offset)following.offset++;if(chunk.type===`reasoning-delta`&&block.reasoningText!==void 0)block.reasoningText=(block.reasoningText+chunk.text).slice(0,240);if(chunk.type===`block-end`){block.row={...block.row,disclosure:`closed`};header={position:block.offset,row:block.row}}}}return{key,index,position,row,...header===void 0?{}:{header},...block?.reasoningText===void 0?{}:{collapsed:{key:block.row.key,summary:`blockType: reasoning${block.reasoningText===``?``:` · ${block.reasoningText}`}`.slice(0,240)}}}}};var SessionLogGroups=class{turn;step;append(row,event){switch(event.type){case`turn/start`:this.step=void 0;this.turn={...row,disclosure:`open`};return this.turn;case`step/start`:this.step={...this.child(row,this.turn),disclosure:`open`};return this.step;case`step/end`:{const result=this.child(row,this.step??this.turn);this.step=void 0;return result}case`turn/end`:{const result=this.child(row,this.turn);this.step=void 0;this.turn=void 0;return result}default:return this.child(row,this.step??this.turn)}}child(row,parent){return parent===void 0?row:{...row,parent:parent.key,depth:parent.depth+1}}};var SessionLogModel=class{source;rows=(0,_unieai_rabi_client_store.createSnapshotStore)([]);records=new Map;roots=[];attempts=new Map;groups=new SessionLogGroups;settledRoots=new Map;streams=new WeakMap;revision=-1;subscribers=0;disconnect;constructor(source){this.source=source;this.accept(source.getSnapshot())}getSnapshot=()=>this.rows.getSnapshot();chatAnchor(key){this.accept(this.source.getSnapshot());const root=this.roots.find(root=>root.row.key===key||root.stream!==void 0&&key.startsWith(`${root.row.key}/chunk:`));if(root===void 0)return void 0;const record=this.records.get(key)?.getSnapshot();if(record===void 0)return void 0;return{event:root.entry.event,...root.row.key===key?{}:{chunk:record.value}}}pick(target){const window=this.source.getSnapshot();this.accept(window);const entries=window.entries;const sameStep=entry=>{const data=entry.event.data;return target.turn!==void 0&&`turn`in data&&data.turn===target.turn&&(target.step===void 0||`step`in data&&data.step===target.step)};const call=target.callId===void 0?void 0:entries.find(entry=>entry.event.type===`tool/call`&&entry.event.data.callId===target.callId);const anchor=target.anchorSeq===void 0?void 0:entries.find(entry=>entry.event.seq===target.anchorSeq);const assistant=target.nodeKind!==`assistant-step`?void 0:entries.findLast(entry=>sameStep(entry)&&(entry.event.type===`assistant/message`||entry.event.type===`assistant/attempt`||entry.type===`transient`));const step=target.step===void 0?void 0:entries.find(entry=>entry.event.type===`step/start`&&sameStep(entry));const turn=target.turn===void 0?void 0:entries.find(entry=>entry.event.type===`turn/start`&&entry.event.data.turn===target.turn);const entry=call??anchor??assistant??step??turn??entries.find(sameStep);if(entry===void 0)return void 0;const key=entry.type===`transient`?`attempt:${entry.event.data.attemptId}`:this.settledRoots.get(entry.event.seq)??`event:${entry.event.seq}`;if(target.groupPart===`reasoning`){const block=this.rows.getSnapshot().find(row=>{if(row.parent!==key)return false;const value=this.records.get(row.key)?.getSnapshot()?.value;return value!==null&&typeof value===`object`&&`type`in value&&value.type===`block-start`&&`blockType`in value&&value.blockType===`reasoning`});if(block!==void 0)return block.key}return key}subscribe=listener=>{const stop=this.rows.subscribe(listener);if(this.subscribers++===0){this.disconnect=this.source.subscribe(()=>{this.accept(this.source.getSnapshot())});this.accept(this.source.getSnapshot())}return()=>{stop();if(--this.subscribers===0){this.disconnect?.();this.disconnect=void 0}}};row=key=>{let record=this.records.get(key);if(record===void 0){record=(0,_unieai_rabi_client_store.createSnapshotStore)(void 0);this.records.set(key,record)}return record};put(key,record){this.row(key);const source=this.records.get(key);if(source.getSnapshot()?.value!==record.value)source.set(record)}accept(window){if(window.revision===this.revision)return;if(window.change.kind===`settle-assistant`&&window.change.entry!==void 0){const parent=`attempt:${window.change.attemptId}`;if(this.attempts.has(parent))this.settledRoots.set(window.change.entry.event.seq,parent)}const append=window.revision===this.revision+1&&window.change.kind===`append`;if(!append){this.roots.length=0;this.attempts.clear();this.groups=new SessionLogGroups}const next=append?this.rows.getSnapshot().slice():[];const entries=append?window.change.entries:window.entries;for(const entry of entries)this.add(entry,next);this.revision=window.revision;if(!append)this.prune(next);this.rows.set(next)}prune(rows){const retained=new Set(rows.map(row=>row.key));for(const[seq,key]of this.settledRoots)if(!retained.has(key))this.settledRoots.delete(seq);for(const[key,source]of this.records)if(!retained.has(key)){source.set(void 0);this.records.delete(key)}}root(key,entry,rows,stream){const row=this.groups.append({key,depth:0},entry.event);const root={row,entry,stream,ordinal:this.roots.length,offset:rows.length};this.roots.push(root);rows.push(row);return root}add(entry,rows){if(entry.type===`transient`){const event=entry.event;const{attemptId,turn,step,chunk}=entry.event.data;const parent=`attempt:${attemptId}`;let attempt=this.attempts.get(parent);if(attempt===void 0){attempt=this.root(parent,entry,rows,new AssistantLogStream(parent));this.attempts.set(parent,attempt)}const chunks=this.addChunk(attempt,rows,event.time,chunk,`${turn}/${step}`);this.put(parent,{type:`assistant/live`,identity:attemptId,location:`${turn}/${step}`,time:event.time,value:{attemptId,turn,step,chunks}});return}const event=entry.event;const key=this.settledRoots.get(event.seq)??`event:${event.seq}`;const data=event.data;const location=`turn`in data?`${data.turn}${`step`in data?`/${data.step}`:``}`:``;this.put(key,{type:event.type,identity:String(event.seq),time:event.time,location,value:event});if(entry.event.type===`assistant/message`||entry.event.type===`assistant/attempt`){const hierarchy=new AssistantLogStream(key);const root=this.root(key,entry,rows,hierarchy);const stream=entry.event.data.stream;let chunks=this.streams.get(stream);if(chunks===void 0){chunks=expandAssistantStream(stream);this.streams.set(stream,chunks)}for(const item of chunks)this.addChunk(root,rows,item.time,item.chunk,location)}else this.root(key,entry,rows)}addChunk(root,rows,time,chunk,location){const stream=root.stream;const{key,index,position,row,header,collapsed}=stream.append(chunk);rows.splice(root.offset+1+position,0,{...row,depth:row.depth+root.row.depth});if(header!==void 0)rows[root.offset+1+header.position]={...header.row,depth:header.row.depth+root.row.depth};for(let ordinal=root.ordinal+1;ordinal<this.roots.length;ordinal++)this.roots[ordinal].offset++;this.put(key,{type:chunk.type,identity:String(index),time,location,value:chunk});if(collapsed!==void 0){const source=this.records.get(collapsed.key);const previous=source.getSnapshot();if(previous.collapsedSummary!==collapsed.summary)source.set({...previous,collapsedSummary:collapsed.summary})}return stream.length}};function partOf(chunk){if(chunk?.type===`reasoning-delta`)return`reasoning`;if(chunk?.type===`text-delta`)return`response`;const type=chunk?.type===`block-start`?chunk.blockType:chunk?.type===`block-end`?chunk.block.type:void 0;return type===`reasoning`?`reasoning`:type===`text`?`response`:void 0}function sessionLogChatTarget(anchor){const{event,chunk}=anchor;const data=event.data;const turn=`turn`in data&&typeof data.turn===`number`?data.turn:void 0;const step=`step`in data&&typeof data.step===`number`?data.step:void 0;const callId=event.type===`tool/call`?event.data.callId:event.type===`tool/result`?event.data.message.source.callId:`subCallId`in data&&typeof data.subCallId===`string`?data.subCallId:chunk?.type===`tool-call-delta`?chunk.id:chunk?.type===`block-end`&&chunk.block.type===`tool-call`?chunk.block.id:void 0;const rootCallId=`rootCallId`in data&&typeof data.rootCallId===`string`?data.rootCallId:callId;const groupPart=partOf(chunk);return{anchorSeq:event.seq,...event.type===`assistant/message`||event.type===`assistant/attempt`||event.type===`assistant/live-chunk`?{nodeKind:`assistant-step`}:{},...turn===void 0?{}:{turn},...step===void 0?{}:{step},...callId===void 0?{}:{callId},...rootCallId===void 0||rootCallId===callId?{}:{rootCallId},...groupPart===void 0?{}:{groupPart}}}var InspectorJsonWriter=class{ancestors=[];containers=new WeakMap;write(value){const replace=this.replace.bind(this);const result=JSON.stringify(value,function(_key,item){return replace(this,item)},2);return typeof result===`string`?result:``}replace(parent,value){if(typeof value===`bigint`)return`${value}n`;if(value===null||typeof value!==`object`)return value;while(this.ancestors.length>0&&this.ancestors.at(-1)!==parent)this.ancestors.pop();let rendered=value;if(value instanceof Map||value instanceof Set){const container=this.containers.get(value)??(value instanceof Map?Object.fromEntries(value):[...value]);this.containers.set(value,container);rendered=container}if(this.ancestors.includes(rendered))return`[Circular]`;this.ancestors.push(rendered);return rendered}};function inspectorJson(value){try{return{text:new InspectorJsonWriter().write(value),failed:false}}catch(error){return{text:error instanceof Error?error.message:String(error),failed:true}}}const css=`.GTtnTq_root{--rabi-scrollbar-thumb:var(--dsw-alias-scrollbar-bg-l2);--rabi-scrollbar-thumb-hover:var(--dsw-alias-scrollbar-hover-l2);min-width:0;min-height:0;color:var(--dsw-alias-label-primary);flex-direction:column;flex:1 1 0;height:100%;font-size:11px;display:flex;overflow:hidden}.GTtnTq_toolbar{border-bottom:.5px solid var(--dsw-alias-border-l2);flex:none;align-items:center;gap:8px;padding:6px 8px;display:flex}.GTtnTq_toolbar span:first-child{flex:1}.GTtnTq_toolbar button,.GTtnTq_record,.GTtnTq_preview,.GTtnTq_disclosure{color:inherit;font:inherit;cursor:pointer;background:0 0;border:none}.GTtnTq_toolbar button:disabled{color:var(--dsw-alias-label-tertiary);cursor:default}.GTtnTq_scroller{overflow-anchor:none;flex:1;min-height:0;overflow:auto}.GTtnTq_table{table-layout:fixed;border-collapse:collapse;width:100%;min-width:660px;font-family:monospace}.GTtnTq_table th{z-index:10;background:var(--dsw-alias-bg-module-platform);text-align:left;position:sticky;top:0}.GTtnTq_table th,.GTtnTq_table td{box-sizing:border-box;border-bottom:.5px solid var(--dsw-alias-border-l1);white-space:nowrap;text-overflow:ellipsis;height:30px;padding:4px 8px;overflow:hidden}.GTtnTq_idColumn{width:64px}.GTtnTq_typeColumn{width:190px}.GTtnTq_typeHeader{align-items:center;gap:6px;display:flex}.GTtnTq_typeFilterButton{color:inherit;cursor:pointer;background:0 0;border:none;border-radius:3px;padding:2px;display:inline-flex}.GTtnTq_typeFilterButton[aria-pressed=true]{color:var(--dsw-alias-state-business-primary);background:var(--dsw-alias-interactive-bg-hover)}@media (hover:hover){.GTtnTq_typeFilterButton:hover{color:var(--dsw-alias-state-business-primary);background:var(--dsw-alias-interactive-bg-hover)}}.GTtnTq_typeFilterPanel{z-index:1250;box-sizing:border-box;width:290px;max-width:calc(100vw - 24px);max-height:calc(100dvh - 24px);color:var(--dsw-alias-label-primary);position-area:none;top:max(12px, calc(anchor(bottom) + 4px));bottom:12px;left:max(12px, anchor(left));position-try-fallbacks:--rabi-types-window, --rabi-types-opposite, --rabi-types-wide-opposite, --rabi-types-tall, --rabi-types-viewport;place-self:start;height:fit-content;min-height:0;margin:0;padding:10px;font-size:11px;position:fixed;right:12px;overflow:auto}.GTtnTq_typeFilterInput{box-sizing:border-box;border:.5px solid var(--dsw-alias-border-l2);width:100%;color:inherit;font:inherit;background:0 0;border-radius:4px;padding:5px 6px}.GTtnTq_typeFilterHelp{color:var(--dsw-alias-label-secondary);margin:6px 0}.GTtnTq_typeFilterOptions{max-height:180px;overflow:auto}.GTtnTq_typeFilterOptions button{width:100%;color:inherit;font:inherit;text-align:left;text-overflow:ellipsis;white-space:nowrap;cursor:pointer;background:0 0;border:none;padding:4px 6px;display:block;overflow:hidden}.GTtnTq_typeFilterOptions button[aria-selected=true]{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-state-business-primary)}@media (hover:hover){.GTtnTq_typeFilterOptions button:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-state-business-primary)}}.GTtnTq_typeFilterActions{justify-content:flex-end;gap:8px;margin-top:8px;display:flex}.GTtnTq_typeFilterActions button{border:.5px solid var(--dsw-alias-border-l2);color:inherit;font:inherit;cursor:pointer;background:0 0;border-radius:4px;padding:3px 6px}.GTtnTq_contextRow .GTtnTq_record{color:var(--dsw-alias-label-tertiary)}.GTtnTq_locationColumn{width:65px}.GTtnTq_timeColumn{width:100px}.GTtnTq_selected{background:var(--dsw-alias-interactive-bg-hover)}@media (hover:hover){.GTtnTq_table tr:hover{background:var(--dsw-alias-interactive-bg-hover)}}.GTtnTq_sticky{position:sticky}.GTtnTq_table .GTtnTq_sticky{background:var(--dsw-alias-bg-module-platform)}@media (hover:hover){.GTtnTq_table .GTtnTq_sticky:hover{background:var(--dsw-alias-bg-module-platform)}}.GTtnTq_sticky.GTtnTq_selected .GTtnTq_record{color:var(--dsw-alias-state-business-primary)}.GTtnTq_identity{color:var(--dsw-alias-label-tertiary)}.GTtnTq_identityText{text-overflow:ellipsis;display:block;overflow:hidden}.GTtnTq_disclosure{width:16px;padding:0}.GTtnTq_record,.GTtnTq_preview{text-align:left;padding:0}.GTtnTq_preview{text-overflow:ellipsis;width:100%;display:block;overflow:hidden}.GTtnTq_details{flex-direction:column;flex:0 0 40%;min-height:0;max-height:80%;display:flex;overflow:hidden}.GTtnTq_detailsResize{cursor:row-resize;touch-action:none;user-select:none;background:var(--dsw-alias-border-l2);flex:none;height:5px}.GTtnTq_detailsResize:active,.GTtnTq_detailsResize:focus-visible{background:var(--dsw-alias-state-business-primary)}@media (hover:hover){.GTtnTq_detailsResize:hover{background:var(--dsw-alias-state-business-primary)}}.GTtnTq_details pre{min-height:0;font-size:inherit;white-space:pre-wrap;overflow-wrap:anywhere;flex:1;margin:0;padding:8px;overflow:auto}.GTtnTq_modeSelector{background:var(--dsw-alias-bg-module-platform);color:inherit;font:inherit;border:none;padding:2px 4px}.GTtnTq_modeControls{vertical-align:middle;align-items:center;gap:6px;display:inline-flex}.GTtnTq_pickButton{border-radius:4px;justify-content:center;align-items:center;padding:3px;display:inline-flex}.GTtnTq_pickButton[aria-pressed=true]{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-state-business-primary)}@media (hover:hover){.GTtnTq_pickButton:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-state-business-primary)}}.GTtnTq_pickNotice{color:var(--dsw-alias-label-secondary);border-bottom:.5px solid var(--dsw-alias-border-l1);flex:none;padding:4px 8px}.GTtnTq_chatPick{z-index:1201;pointer-events:none;background:color-mix(in srgb, var(--dsw-alias-state-business-primary) 15%, transparent);outline:1px solid var(--dsw-alias-state-business-primary);border-radius:4px;position:fixed}.GTtnTq_chatPickMask{z-index:1200;pointer-events:auto;cursor:crosshair;touch-action:none;background:0 0;position:fixed}.GTtnTq_chatReveal{z-index:1200;pointer-events:none;background:var(--dsw-specific-bubble-highlight);outline:1px solid var(--dsw-alias-state-business-primary);border-radius:6px;position:fixed}.GTtnTq_objectDetails{flex:1;min-height:0;padding:8px;overflow:auto}.GTtnTq_objectTree,.GTtnTq_objectTree ul{margin:0;padding-inline-start:16px;font-family:monospace;list-style:none}.GTtnTq_objectTree li{overflow-wrap:anywhere;white-space:pre-wrap;padding:2px 0}.GTtnTq_objectTree summary{cursor:pointer}.GTtnTq_objectField{color:var(--dsw-alias-label-primary)}.GTtnTq_objectValue{color:var(--dsw-alias-label-secondary)}.GTtnTq_objectMuted{color:var(--dsw-alias-label-tertiary)}.GTtnTq_objectReference,.GTtnTq_objectBreadcrumbs button{color:var(--dsw-alias-state-business-primary);cursor:pointer;font:inherit;text-align:left;background:0 0;border:none;padding:0}@media (hover:hover){.GTtnTq_objectReference:hover{text-decoration:underline}}.GTtnTq_objectBreadcrumbs{z-index:1;background:var(--dsw-alias-bg-module-platform);border-bottom:.5px solid var(--dsw-alias-border-l1);margin:-8px -8px 8px;padding:6px 8px;position:sticky;top:-8px;overflow:auto}.GTtnTq_objectBreadcrumbs ol{align-items:center;gap:6px;margin:0;padding:0;list-style:none;display:flex}.GTtnTq_objectBreadcrumbs li{flex:none;align-items:center;gap:6px;display:flex}.GTtnTq_objectBreadcrumbs button{text-overflow:ellipsis;white-space:nowrap;max-width:180px;overflow:hidden}.GTtnTq_objectBreadcrumbs button:disabled{color:var(--dsw-alias-label-primary);cursor:default}.GTtnTq_empty{color:var(--dsw-alias-label-tertiary);padding:12px}@media (prefers-reduced-motion:reduce){.GTtnTq_table tr{animation:none}}@position-try --rabi-types-window{position-area:none;top:max(12px, calc(anchor(bottom) + 4px));bottom:12px;left:12px;right:12px;margin:0;align-self:safe start;justify-self:safe end}@position-try --rabi-types-opposite{top:max(12px, var(--rabi-frame-overlay-top,12px));bottom:max(12px, calc(anchor(top) + 4px));align-self:end}@position-try --rabi-types-wide-opposite{top:max(12px, var(--rabi-frame-overlay-top,12px));bottom:max(12px, calc(anchor(top) + 4px));left:12px;right:12px;align-self:end;justify-self:safe end}@position-try --rabi-types-tall{position-area:none;top:max(12px, var(--rabi-frame-overlay-top,12px));bottom:12px;left:max(12px, anchor(left));right:12px;margin:0;align-self:safe start;justify-self:start}@position-try --rabi-types-viewport{position-area:none;inset:max(12px, var(--rabi-frame-overlay-top,12px)) 12px 12px;margin:0;align-self:safe start;justify-self:safe end}`;const tagId=`@unieai/rabi-experimental-session-inspector/inspector.module.css`;if(typeof document!==`undefined`&&document.querySelector(`style[data-plugin-css=`+JSON.stringify(tagId)+`]`)===null){const tag=document.createElement(`style`);tag.dataset.plugin=`@unieai/rabi-experimental-session-inspector`;tag.dataset.pluginCss=tagId;tag.textContent=css;document.head.appendChild(tag)}var inspector_module_css_default={"chatPick":`GTtnTq_chatPick`,"chatPickMask":`GTtnTq_chatPickMask`,"chatReveal":`GTtnTq_chatReveal`,"contextRow":`GTtnTq_contextRow`,"details":`GTtnTq_details`,"detailsResize":`GTtnTq_detailsResize`,"disclosure":`GTtnTq_disclosure`,"empty":`GTtnTq_empty`,"idColumn":`GTtnTq_idColumn`,"identity":`GTtnTq_identity`,"identityText":`GTtnTq_identityText`,"locationColumn":`GTtnTq_locationColumn`,"modeControls":`GTtnTq_modeControls`,"modeSelector":`GTtnTq_modeSelector`,"objectBreadcrumbs":`GTtnTq_objectBreadcrumbs`,"objectDetails":`GTtnTq_objectDetails`,"objectField":`GTtnTq_objectField`,"objectMuted":`GTtnTq_objectMuted`,"objectReference":`GTtnTq_objectReference`,"objectTree":`GTtnTq_objectTree`,"objectValue":`GTtnTq_objectValue`,"pickButton":`GTtnTq_pickButton`,"pickNotice":`GTtnTq_pickNotice`,"preview":`GTtnTq_preview`,"record":`GTtnTq_record`,"root":`GTtnTq_root`,"scroller":`GTtnTq_scroller`,"selected":`GTtnTq_selected`,"sticky":`GTtnTq_sticky`,"table":`GTtnTq_table`,"timeColumn":`GTtnTq_timeColumn`,"toolbar":`GTtnTq_toolbar`,"typeColumn":`GTtnTq_typeColumn`,"typeFilterActions":`GTtnTq_typeFilterActions`,"typeFilterButton":`GTtnTq_typeFilterButton`,"typeFilterHelp":`GTtnTq_typeFilterHelp`,"typeFilterInput":`GTtnTq_typeFilterInput`,"typeFilterOptions":`GTtnTq_typeFilterOptions`,"typeFilterPanel":`GTtnTq_typeFilterPanel`,"typeHeader":`GTtnTq_typeHeader`};function clampPercent(value){return Math.max(15,Math.min(80,value))}function InspectorDetails({text,failed,children,close,t}){const id=(0,react.useId)();const panel=(0,react.useRef)(null);const drag=(0,react.useRef)(null);const[percent,setPercent]=(0,react.useState)(40);const resize=event=>{const current=drag.current;if(current===null||current.pointerId!==event.pointerId)return;setPercent(clampPercent((current.height+current.y-event.clientY)/current.available*100))};const stop=event=>{if(drag.current?.pointerId!==event.pointerId)return;drag.current=null;if(event.currentTarget.hasPointerCapture(event.pointerId))event.currentTarget.releasePointerCapture(event.pointerId)};return(0,react_jsx_runtime.jsxs)(`div`,{ref:panel,id,className:inspector_module_css_default.details,style:{flexBasis:`${percent}%`},children:[(0,react_jsx_runtime.jsx)(`div`,{role:`separator`,tabIndex:0,"aria-orientation":`horizontal`,"aria-controls":id,"aria-label":t(`table.resizeDetails`),"aria-valuemin":15,"aria-valuemax":80,"aria-valuenow":Math.round(percent),className:inspector_module_css_default.detailsResize,onPointerDown:event=>{if(event.button!==0||drag.current!==null)return;const element=panel.current;const available=element?.parentElement?.getBoundingClientRect().height??0;if(element===null||available===0)return;event.preventDefault();drag.current={pointerId:event.pointerId,y:event.clientY,height:element.getBoundingClientRect().height,available};event.currentTarget.setPointerCapture(event.pointerId)},onPointerMove:resize,onPointerUp:event=>{resize(event);stop(event)},onPointerCancel:stop,onLostPointerCapture:()=>{drag.current=null},onKeyDown:event=>{switch(event.key){case`ArrowUp`:setPercent(value=>clampPercent(value+5));break;case`ArrowDown`:setPercent(value=>clampPercent(value-5));break;case`Home`:setPercent(15);break;case`End`:setPercent(80);break;default:return}event.preventDefault()}}),(0,react_jsx_runtime.jsxs)(`div`,{className:inspector_module_css_default.toolbar,children:[(0,react_jsx_runtime.jsx)(`span`,{children:t(`table.raw`)}),(0,react_jsx_runtime.jsx)(`button`,{type:`button`,onClick:close,children:t(`table.close`)})]}),children===void 0?(0,react_jsx_runtime.jsx)(`pre`,{role:failed?`alert`:void 0,children:text}):(0,react_jsx_runtime.jsx)(`div`,{className:inspector_module_css_default.objectDetails,children})]})}var CollectionProperties=class{value;length;constructor(value,length){this.value=value;this.length=length}};const typedArrayLength=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),`length`).get;function indexedLength(value){if(Array.isArray(value))return value.length;if(ArrayBuffer.isView(value)&&!(value instanceof DataView))return typedArrayLength.call(value)}function field(value,key,index){const descriptor=Object.getOwnPropertyDescriptor(value,key);return{key:typeof key===`symbol`?`symbol:${index}`:key,name:String(key),value:descriptor?.value,...descriptor===void 0?{absent:true}:`value`in descriptor?{}:{accessor:true}}}var InspectorObjectValue=class{value;label;expandable;constructor(value){this.value=value;this.expandable=value!==null&&typeof value===`object`&&!(value instanceof Date||value instanceof RegExp||value instanceof WeakMap||value instanceof WeakSet);if(value instanceof Map)this.label=`Map(${value.size})`;else if(value instanceof Set)this.label=`Set(${value.size})`;else if(Array.isArray(value))this.label=`Array(${value.length})`;else if(value instanceof Date)this.label=`Date(${Number.isNaN(value.getTime())?`Invalid`:value.toISOString()})`;else if(value instanceof RegExp)this.label=String(value);else if(value instanceof WeakMap)this.label=`WeakMap`;else if(value instanceof WeakSet)this.label=`WeakSet`;else if(value instanceof ArrayBuffer)this.label=`ArrayBuffer(${value.byteLength})`;else if(value instanceof CollectionProperties)this.label=`Object`;else if(value!==null&&typeof value===`object`){const prototype=Object.getPrototypeOf(value);const constructor=prototype===null?void 0:Object.getOwnPropertyDescriptor(prototype,`constructor`)?.value;this.label=typeof constructor===`function`?constructor.name:`Object`}else if(typeof value===`string`)this.label=JSON.stringify(value);else if(typeof value===`bigint`)this.label=`${value}n`;else if(typeof value===`function`)this.label=`[Function ${value.name}]`;else this.label=String(value)}*entries(){const value=this.value;if(value instanceof Map){let index=0;const entries=value;for(const[key,item]of entries)yield{key:String(index),name:String(index++),value:{key,value:item}}}else if(value instanceof Set){let index=0;for(const item of value)yield{key:String(index),name:String(index++),value:item}}else if(value instanceof ArrayBuffer||value instanceof DataView)yield{key:`bytes`,name:`bytes`,value:value instanceof ArrayBuffer?new Uint8Array(value):new Uint8Array(value.buffer,value.byteOffset,value.byteLength)};else if(value!==null&&typeof value===`object`){const length=indexedLength(value);if(length!==void 0){yield{key:`properties`,name:``,properties:true,value:new CollectionProperties(value,length)};for(let index=0;index<length;index++)yield field(value,String(index),index)}else{const target=value instanceof CollectionProperties?value.value:value;for(const[index,key]of Reflect.ownKeys(target).entries()){if(value instanceof CollectionProperties&&typeof key===`string`&&(key===`length`&&Array.isArray(target)||String(Number(key))===key&&Number.isInteger(Number(key))&&Number(key)>=0&&Number(key)<value.length))continue;const entry=field(target,key,index);if(!entry.absent)yield entry}}}}};const PAGE_SIZE=50;function ObjectBranch({value,name,path,ancestors,root,accessor,absent,navigation,t}){const json=navigation===void 0;const objects=navigation?.objects;const revision=navigation?.revision;const[expanded,setExpanded]=(0,react.useState)(root===true||json);const[limit,setLimit]=(0,react.useState)(json?Infinity:PAGE_SIZE);const content=(0,react.useMemo)(()=>{try{const reference=!root&&value!==null&&typeof value===`object`?objects?.reference(value):void 0;const circular=value!==null&&typeof value===`object`?ancestors.get(value):void 0;const display=(reference===void 0||reference.kind===`nodeData`)&&circular===void 0&&!accessor?new InspectorObjectValue(value):void 0;const entries=[];if(expanded&&display?.expandable===true)for(const entry of display.entries()){if(json&&entry.properties)continue;entries.push(entry);if(entries.length>limit)break}return{reference,circular,display,entries,error:void 0}}catch(error){return{error:error instanceof Error?error.message:String(error)}}},[value,root,objects,ancestors,accessor,expanded,limit,revision,json]);const children=(0,react.useMemo)(()=>{const next=new Map(ancestors);if(value!==null&&typeof value===`object`)next.set(value,path);return next},[ancestors,value,path]);const field=(0,react_jsx_runtime.jsxs)(`span`,{className:inspector_module_css_default.objectField,children:[name,`: `]});if(content.error!==void 0)return(0,react_jsx_runtime.jsxs)(`li`,{role:`alert`,children:[field,content.error]});if(absent)return(0,react_jsx_runtime.jsxs)(`li`,{children:[field,(0,react_jsx_runtime.jsx)(`span`,{className:inspector_module_css_default.objectMuted,children:t(`object.absent`)})]});if(accessor)return(0,react_jsx_runtime.jsxs)(`li`,{children:[field,(0,react_jsx_runtime.jsx)(`span`,{className:inspector_module_css_default.objectMuted,children:t(`object.accessor`)})]});const reference=content.reference;const link=reference===void 0||navigation===void 0?void 0:(0,react_jsx_runtime.jsxs)(`button`,{type:`button`,className:inspector_module_css_default.objectReference,onClick:event=>{event.preventDefault();event.stopPropagation();navigation.navigate(reference)},children:[`↗ `,t(`object.${reference.kind}`),` · `,reference.identity]});if(reference!==void 0&&(reference.kind!==`nodeData`||content.circular!==void 0))return(0,react_jsx_runtime.jsxs)(`li`,{children:[field,link]});if(content.circular!==void 0)return(0,react_jsx_runtime.jsxs)(`li`,{children:[field,(0,react_jsx_runtime.jsxs)(`span`,{className:inspector_module_css_default.objectMuted,children:[`↩ `,content.circular]})]});const display=content.display;if(!display.expandable)return(0,react_jsx_runtime.jsxs)(`li`,{children:[field,(0,react_jsx_runtime.jsx)(`span`,{className:inspector_module_css_default.objectValue,children:display.label})]});return(0,react_jsx_runtime.jsx)(`li`,{children:(0,react_jsx_runtime.jsxs)(`details`,{open:expanded,onToggle:event=>{setExpanded(event.currentTarget.open)},children:[(0,react_jsx_runtime.jsxs)(`summary`,{children:[field,link,` `,(0,react_jsx_runtime.jsx)(`span`,{className:inspector_module_css_default.objectMuted,children:display.label})]}),expanded&&(0,react_jsx_runtime.jsxs)(`ul`,{children:[content.entries.slice(0,limit).map(({key,properties,...entry})=>(0,react_jsx_runtime.jsx)(ObjectBranch,{...entry,name:properties?t(`object.properties`):entry.name,path:properties?path:`${path}.${entry.name}`,ancestors:children,navigation,t},key)),content.entries.length===0&&(0,react_jsx_runtime.jsx)(`li`,{className:inspector_module_css_default.objectMuted,children:t(`object.empty`)}),content.entries.length>limit&&(0,react_jsx_runtime.jsx)(`li`,{children:(0,react_jsx_runtime.jsx)(`button`,{type:`button`,className:inspector_module_css_default.objectReference,onClick:()=>{setLimit(value=>value+PAGE_SIZE)},children:t(`object.more`)})})]})]})})}function ValueTree(props){const ancestors=(0,react.useMemo)(()=>new Map,[]);return(0,react_jsx_runtime.jsx)(`ul`,{className:inspector_module_css_default.objectTree,children:(0,react_jsx_runtime.jsx)(ObjectBranch,{...props,name:`$`,path:`$`,ancestors,root:true})})}function InspectorJsonTree({text,t}){return(0,react_jsx_runtime.jsx)(ValueTree,{value:(0,react.useMemo)(()=>text===``?void 0:JSON.parse(text),[text]),t})}function InspectorObjectTree(props){const updates=props.objects.updates;const revision=(0,react.useSyncExternalStore)((0,react.useCallback)(listener=>updates.subscribe(listener),[updates]),(0,react.useCallback)(()=>updates.getSnapshot(),[updates]));return(0,react_jsx_runtime.jsx)(ValueTree,{value:props.value,t:props.t,navigation:{objects:props.objects,navigate:props.navigate,revision}})}const INSPECTOR_ROW_HEIGHT=30;var InspectorTableLayout=class{hierarchy;items;preservedCollapse;bottomPadding;scrollOffset;minimumExtent;rowIndexes=new Map;constructor(hierarchy,previous,viewport={offset:0,height:0},anchor){this.hierarchy=hierarchy;for(const[rowIndex,row]of hierarchy.rows.entries())this.rowIndexes.set(row.key,rowIndex);this.items=hierarchy.rows.map((row,rowIndex)=>({key:row.key,rowIndex,row,size:30}));this.preservedCollapse=previous!==void 0&&hierarchy.rows.length<previous.hierarchy.rows.length&&hierarchy.rows.some(row=>row.disclosure===`closed`&&previous.hierarchy.rows[previous.rowIndexes.get(row.key)??-1]?.disclosure===`open`);const anchorIndex=anchor===void 0?void 0:this.rowIndexes.get(anchor.key);this.scrollOffset=anchor!==void 0&&anchorIndex!==void 0?Math.max(0,(anchorIndex+1)*30-anchor.top):this.preservedCollapse&&previous!==void 0?this.anchorOffset(previous,viewport.offset):void 0;const natural=(this.items.length+1)*30;const minimum=this.scrollOffset===void 0?previous?.minimumExtent??0:Math.max(this.scrollOffset+viewport.height,(previous?.minimumExtent??0)+this.scrollOffset-viewport.offset);this.minimumExtent=minimum>natural?minimum:0;this.bottomPadding=Math.max(0,this.minimumExtent-natural)}stickyIndexes(itemIndex){return this.hierarchy.stickyIndexes(itemIndex)}stickyIndexesAtOffset(offset){const indexes=[];const first=Math.max(0,Math.floor(offset/30));while(indexes.length<this.items.length){const candidate=Math.min(this.items.length-1,first+indexes.length);const ancestors=this.stickyIndexes(candidate);const next=ancestors[indexes.length];if(next===void 0||indexes.some((index,level)=>ancestors[level]!==index))break;indexes.push(next)}return indexes}anchorOffset(previous,offset){const first=Math.max(0,Math.min(previous.items.length-1,Math.floor(offset/30)));const index=Math.min(previous.items.length-1,first+previous.stickyIndexesAtOffset(offset).length);const row=previous.items[index].row;const retained=this.rowIndexes.get(row.key);if(retained!==void 0)return Math.max(0,offset+(retained-index)*30);const ancestors=previous.stickyIndexes(index);for(let level=ancestors.length-1;level>=0;level--){const parent=previous.items[ancestors[level]].row;const next=this.rowIndexes.get(parent.key);if(next!==void 0)return Math.max(0,(next-level)*30)}return 0}};var InspectorTypeFilter=class{query;needle;constructor(query){this.query=query.trim().replace(/^\*+|\*+$/g,``).trim();this.needle=this.query.toLowerCase()}get active(){return this.needle!==``}matches(type){return!this.active||type!==void 0&&type.toLowerCase().includes(this.needle)}apply(rows,typeOf){if(!this.active)return{rows,matches:new Set(rows.map(row=>row.key))};const matches=new Set(rows.filter(row=>this.matches(typeOf(row.key))).map(row=>row.key));const byKey=new Map(rows.map(row=>[row.key,row]));const retained=new Set(matches);for(const key of matches){let parent=byKey.get(key)?.parent;while(parent!==void 0&&!retained.has(parent)){retained.add(parent);parent=byKey.get(parent)?.parent}}const branches=new Set;for(const key of retained){const parent=byKey.get(key)?.parent;if(parent!==void 0)branches.add(parent)}return{matches,rows:rows.filter(row=>retained.has(row.key)).map(row=>{const{disclosure:_disclosure,...plain}=row;return branches.has(row.key)?{...plain,disclosure:`open`}:plain})}}async suggest(rows,typeOf){await Promise.resolve();const types=new Set;for(const row of rows){const type=typeOf(row.key);if(type!==void 0&&this.matches(type))types.add(type)}return[...types].sort()}};function TypeFilter({value,suggest,apply,t}){const[open,setOpen]=(0,react.useState)(false);const[draft,setDraft]=(0,react.useState)(value);const[active,setActive]=(0,react.useState)(-1);const[result,setResult]=(0,react.useState)();const anchor=(0,react.useRef)(null);const panel=(0,react.useRef)(null);const input=(0,react.useRef)(null);const id=(0,react.useId)();const listId=`${id}-types`;const anchorName=`--rabi-type-filter-${id.replaceAll(`:`,``)}`;const close=(0,react.useCallback)(restoreFocus=>{setOpen(false);if(restoreFocus)anchor.current?.focus({preventScroll:true})},[]);const commit=query=>{apply(query);close(true)};(0,react.useEffect)(()=>{if(!open)return;input.current?.focus({preventScroll:true});input.current?.select()},[open]);(0,react.useEffect)(()=>{if(!open)return;const outside=event=>{const target=event.target;if(target instanceof Node&&!panel.current?.contains(target)&&!anchor.current?.contains(target))close(false)};const blur=()=>{close(false)};window.addEventListener(`pointerdown`,outside,true);window.addEventListener(`blur`,blur);return()=>{window.removeEventListener(`pointerdown`,outside,true);window.removeEventListener(`blur`,blur)}},[open,close]);(0,react.useEffect)(()=>{if(!open)return;let current=true;setResult(void 0);setActive(-1);Promise.resolve().then(()=>suggest(draft)).then(items=>{if(current)setResult({query:draft,items})},error=>{if(current)setResult({query:draft,items:[],error:error instanceof Error?error.message:String(error)})});return()=>{current=false}},[open,draft,suggest]);const current=result?.query===draft?result:void 0;const items=current?.items??[];const selected=active>=0&&active<items.length?active:-1;(0,react.useEffect)(()=>{if(selected>=0)panel.current?.querySelectorAll(`[role="option"]`)[selected]?.scrollIntoView({block:`nearest`})},[selected]);return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`button`,{ref:anchor,style:{anchorName},type:`button`,className:inspector_module_css_default.typeFilterButton,"aria-label":t(`filter.title`),title:value===``?t(`filter.title`):`${t(`filter.title`)}: *${value}*`,"aria-haspopup":`dialog`,"aria-expanded":open,"aria-pressed":value!==``,onClick:()=>{if(open){close(true);return}setDraft(value);setResult(void 0);setActive(-1);setOpen(true)},children:(0,react_jsx_runtime.jsx)(`svg`,{width:`13`,height:`13`,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.3`,"aria-hidden":`true`,children:(0,react_jsx_runtime.jsx)(`path`,{d:`M2 3h12L9.5 8v5l-3-1.5V8L2 3Z`})})}),open&&(0,react_dom.createPortal)((0,react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.MenuSurface,{compact:true,ref:panel,className:inspector_module_css_default.typeFilterPanel,role:`dialog`,"aria-label":t(`filter.title`),style:{positionAnchor:anchorName},onKeyDown:event=>{if(event.key===`Escape`){event.preventDefault();event.stopPropagation();close(true)}},onBlur:event=>{if(event.relatedTarget instanceof Node&&!event.currentTarget.contains(event.relatedTarget)&&!anchor.current?.contains(event.relatedTarget))close(false)},children:(0,react_jsx_runtime.jsxs)(`div`,{children:[(0,react_jsx_runtime.jsx)(`input`,{ref:input,className:inspector_module_css_default.typeFilterInput,value:draft,role:`combobox`,"aria-label":t(`filter.input`),"aria-autocomplete":`list`,"aria-expanded":true,"aria-controls":listId,"aria-activedescendant":selected<0?void 0:`${id}-option-${selected}`,placeholder:t(`filter.placeholder`),onChange:event=>{setDraft(event.currentTarget.value);setActive(-1)},onKeyDown:event=>{if(event.nativeEvent.isComposing||event.nativeEvent.keyCode===229)return;if(event.key===`ArrowDown`||event.key===`ArrowUp`){event.preventDefault();setActive(items.length===0?-1:selected<0?event.key===`ArrowDown`?0:items.length-1:(selected+(event.key===`ArrowDown`?1:-1)+items.length)%items.length)}else if(event.key===`Enter`){event.preventDefault();commit(items[selected]??draft)}}}),(0,react_jsx_runtime.jsx)(`div`,{className:inspector_module_css_default.typeFilterHelp,children:t(`filter.help`)}),(0,react_jsx_runtime.jsx)(`div`,{id:listId,role:`listbox`,"aria-label":t(`filter.candidates`),"aria-busy":current===void 0,className:inspector_module_css_default.typeFilterOptions,children:items.map((type,index)=>(0,react_jsx_runtime.jsx)(`button`,{id:`${id}-option-${index}`,type:`button`,role:`option`,"aria-selected":selected===index,tabIndex:-1,title:type,onPointerDown:event=>{event.preventDefault()},onClick:()=>{commit(type)},children:type},type))}),current===void 0&&(0,react_jsx_runtime.jsx)(`div`,{role:`status`,children:t(`filter.loading`)}),current?.error!==void 0?(0,react_jsx_runtime.jsxs)(`div`,{role:`alert`,children:[t(`filter.failed`),` `,current.error]}):current!==void 0&&items.length===0&&(0,react_jsx_runtime.jsx)(`div`,{role:`status`,children:t(`filter.noCandidates`)}),(0,react_jsx_runtime.jsxs)(`div`,{className:inspector_module_css_default.typeFilterActions,children:[(0,react_jsx_runtime.jsx)(`button`,{type:`button`,onClick:()=>{setDraft(``);setActive(-1);input.current?.focus()},children:t(`filter.clear`)}),(0,react_jsx_runtime.jsx)(`button`,{type:`button`,onClick:()=>{close(true)},children:t(`filter.cancel`)}),(0,react_jsx_runtime.jsx)(`button`,{type:`button`,onClick:()=>{commit(draft)},children:t(`filter.apply`)})]})]})}),document.body)]})}const DataRow=(0,react.memo)(function DataRow({row,selected,branch,collapsed,added,stickyLevel,pulse,context,select,toggle,useRecord,flash,showTime,t}){const record=useRecord(row.key);const element=(0,react.useRef)(null);const previous=(0,react.useRef)(record);const previousPulse=(0,react.useRef)(0);(0,react.useEffect)(()=>{const changed=previous.current!==record;previous.current=record;const navigated=pulse>0&&previousPulse.current!==pulse;previousPulse.current=pulse;if(!flash&&!navigated||!changed&&!added&&!navigated||element.current===null||window.matchMedia(`(prefers-reduced-motion: reduce)`).matches)return;const color=getComputedStyle(element.current).getPropertyValue(`--dsw-specific-bubble-highlight`);const animation=element.current.animate([{backgroundColor:color},{backgroundColor:`transparent`}],{duration:700});return()=>{animation.cancel()}},[record,added,flash,pulse]);const summary=(0,react.useMemo)(()=>(collapsed?record?.collapsedSummary:void 0)??record?.summary??inspectorPreview(record?.value),[record,collapsed]);return(0,react_jsx_runtime.jsxs)(`tr`,{ref:element,"aria-selected":selected,"data-inspector-context":context?``:void 0,title:context?t(`filter.context`):void 0,className:[selected&&inspector_module_css_default.selected,stickyLevel!==void 0&&inspector_module_css_default.sticky,context&&inspector_module_css_default.contextRow].filter(Boolean).join(` `),style:stickyLevel===void 0?void 0:{top:(stickyLevel+1)*30,zIndex:9-stickyLevel},children:[(0,react_jsx_runtime.jsx)(`td`,{className:inspector_module_css_default.identity,children:(0,react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.Tooltip,{label:record?.identity??``,side:`right`,portal:true,children:(0,react_jsx_runtime.jsx)(`span`,{className:inspector_module_css_default.identityText,tabIndex:0,children:record?.identity})})}),(0,react_jsx_runtime.jsxs)(`td`,{style:{paddingInlineStart:8+row.depth*20},children:[branch&&(0,react_jsx_runtime.jsx)(`button`,{type:`button`,className:inspector_module_css_default.disclosure,"aria-label":collapsed?t(`table.expand`):t(`table.collapse`),"aria-expanded":!collapsed,onClick:()=>{toggle(row,element.current)},children:collapsed?`▸`:`▾`}),(0,react_jsx_runtime.jsx)(`button`,{type:`button`,className:inspector_module_css_default.record,onClick:()=>{select(row.key)},children:record?.type})]}),(0,react_jsx_runtime.jsx)(`td`,{children:record?.location}),showTime&&(0,react_jsx_runtime.jsx)(`td`,{children:record?.time===void 0?``:new Date(record.time).toISOString().slice(11,23)}),(0,react_jsx_runtime.jsx)(`td`,{children:(0,react_jsx_runtime.jsx)(`button`,{type:`button`,className:inspector_module_css_default.preview,onClick:()=>{select(row.key)},children:summary})})]})});function InspectorTable({title,flash,showTime,modeSelector,objects,navigation,pickedRow,notice,useRows,useRecord,useSession,loadOlder,typeOf,t}){const allRows=useRows(value=>value);const hasMore=useSession(value=>value.hasMore);const loading=useSession(value=>value.loadingOlder);const openError=useSession(value=>value.openError);const[failure,setFailure]=(0,react.useState)(null);const[selected,setSelected]=(0,react.useState)(null);const record=useRecord(selected??``);const rowLabel=`${record?.type??``} · ${record?.identity??selected}`;const[objectHistory,setObjectHistory]=(0,react.useState)(null);const objectTarget=objectHistory?.references.at(-1);const[reveal,setReveal]=(0,react.useState)(null);const appliedReveal=(0,react.useRef)(null);const appliedPick=(0,react.useRef)();const[disclosures,setDisclosures]=(0,react.useState)(new Map);const[typeQuery,setTypeQuery]=(0,react.useState)(``);const typeFilter=(0,react.useMemo)(()=>new InspectorTypeFilter(typeQuery),[typeQuery]);const filtered=(0,react.useMemo)(()=>typeFilter.apply(allRows,typeOf),[allRows,typeOf,typeFilter]);const suggestTypes=(0,react.useCallback)(query=>new InspectorTypeFilter(query).suggest(allRows,typeOf),[allRows,typeOf]);const scroller=(0,react.useRef)(null);const followMode=(0,react.useRef)(`tail`);const viewport=(0,react.useRef)({offset:0,height:600});const disclosureAnchor=(0,react.useRef)();const[spacingGeneration,resetSpacing]=(0,react.useState)(0);const toggle=(0,react.useCallback)((row,element)=>{const host=scroller.current;followMode.current=`manual`;disclosureAnchor.current={key:row.key,top:element.getBoundingClientRect().top-host.getBoundingClientRect().top-host.clientTop};viewport.current={offset:host.scrollTop,height:host.clientHeight};setDisclosures(previous=>{const next=new Map(previous);next.set(row.key,{state:row.disclosure,collapsed:!inspectorRowCollapsed(row,previous)});return next})},[]);const locateChat=(0,react.useCallback)(target=>{navigation?.reveal(target??{})},[navigation]);const select=(0,react.useCallback)(key=>{setSelected(key);setObjectHistory(null);const target=navigation?.target(key);locateChat(target)},[navigation,locateChat]);const revealRow=(0,react.useCallback)(key=>{const clearFilter=typeFilter.active&&!filtered.rows.some(row=>row.key===key);if(clearFilter)setTypeQuery(``);followMode.current=`scroll`;setSelected(key);setDisclosures(previous=>{const next=new Map(previous);const byKey=new Map((clearFilter?allRows:filtered.rows).map(row=>[row.key,row]));let parent=byKey.get(key)?.parent;while(parent!==void 0){const row=byKey.get(parent);if(row===void 0)break;next.set(parent,{state:row.disclosure,collapsed:false});parent=row.parent}return next});setReveal(previous=>({key,pulse:(previous?.pulse??0)+1}))},[allRows,typeFilter,filtered.rows]);const navigate=(0,react.useCallback)(reference=>{setObjectHistory(previous=>({rootKey:previous?.rootKey??selected,rootLabel:previous?.rootLabel??rowLabel,references:[...previous?.references??[],reference]}));locateChat(reference.target);if(reference.rowKey!==void 0)revealRow(reference.rowKey)},[revealRow,locateChat,selected,rowLabel]);const backToObject=index=>{const history=objectHistory;const reference=history.references[index-1];const key=index===0?history.rootKey:reference?.rowKey;const target=index===0?navigation?.target(history.rootKey):reference?.target;setObjectHistory(index===0?null:{...history,references:history.references.slice(0,index)});if(key!==void 0)revealRow(key);locateChat(target)};(0,react.useLayoutEffect)(()=>{if(pickedRow===void 0||appliedPick.current===pickedRow||!allRows.some(row=>row.key===pickedRow.key))return;appliedPick.current=pickedRow;setObjectHistory(null);revealRow(pickedRow.key)},[pickedRow,allRows,revealRow]);const hierarchy=(0,react.useMemo)(()=>new InspectorTableHierarchy(filtered.rows,disclosures),[filtered.rows,disclosures]);const rows=hierarchy.rows;const committed=(0,react.useRef)();const layout=(0,react.useMemo)(()=>new InspectorTableLayout(hierarchy,committed.current?.disclosures===disclosures&&committed.current.spacingGeneration===spacingGeneration?committed.current.layout:void 0,viewport.current,disclosureAnchor.current),[hierarchy,disclosures,spacingGeneration]);const anchoredOffset=committed.current?.layout!==layout?layout.scrollOffset:void 0;const seen=(0,react.useRef)(new Map);const initialized=(0,react.useRef)(false);const arrivals=(0,react.useMemo)(()=>{const now=performance.now();const next=new Map(allRows.map(row=>[row.key,seen.current.get(row.key)??(initialized.current?now:-Infinity)]));if(allRows.length>0)initialized.current=true;seen.current=next;return next},[allRows]);const keyOf=(0,react.useCallback)(index=>layout.items[index].key,[layout]);const sizeOf=(0,react.useCallback)(index=>layout.items[index].size,[layout]);const virtualRef=(0,react.useRef)();const extractRange=(0,react.useCallback)(range=>{const offset=anchoredOffset??virtualRef.current.scrollOffset;const visible=anchoredOffset===void 0?range:{...range,startIndex:Math.max(0,Math.floor(offset/30)-1),endIndex:Math.min(range.count-1,Math.ceil((offset+viewport.current.height)/30)-1)};return[...new Set([...layout.stickyIndexesAtOffset(offset),...(0,_tanstack_react_virtual.defaultRangeExtractor)(visible)])].sort((left,right)=>left-right)},[layout,anchoredOffset]);const virtual=(0,_tanstack_react_virtual.useVirtualizer)({count:layout.items.length,getScrollElement:()=>scroller.current,estimateSize:sizeOf,getItemKey:keyOf,overscan:12,initialRect:{width:0,height:600},anchorTo:layout.scrollOffset!==void 0||followMode.current===`manual`?`start`:`end`,scrollEndThreshold:40,paddingStart:30,scrollPaddingStart:30,rangeExtractor:extractRange,paddingEnd:layout.bottomPadding});virtualRef.current=virtual;const viewportHeight=virtual.scrollRect?.height;const applyTypeFilter=query=>{followMode.current=`scroll`;setTypeQuery(new InspectorTypeFilter(query).query);setDisclosures(new Map);resetSpacing(value=>value+1);setSelected(null);setObjectHistory(null);setReveal(null);virtual.scrollToOffset(0)};(0,react.useLayoutEffect)(()=>{if(anchoredOffset!==void 0)virtual.scrollToOffset(anchoredOffset);else if(followMode.current===`tail`&&layout.bottomPadding===0)virtual.scrollToEnd();viewport.current={offset:scroller.current.scrollTop,height:viewportHeight??600};disclosureAnchor.current=void 0;committed.current={layout,disclosures,spacingGeneration}},[virtual,layout,disclosures,spacingGeneration,viewportHeight,anchoredOffset]);(0,react.useLayoutEffect)(()=>{if(reveal===null||appliedReveal.current===reveal)return;const index=layout.items.findIndex(item=>item.key===reveal.key);if(index===-1)return;virtual.scrollToIndex(index,{align:`center`});appliedReveal.current=reveal},[layout,reveal,virtual]);const items=virtual.getVirtualItems();const sticky=new Map(layout.stickyIndexesAtOffset(anchoredOffset??virtual.scrollOffset).map((index,level)=>[index,level]));const lastItem=items.at(-1);const bottom=lastItem===void 0?0:Math.max(0,virtual.getTotalSize()-lastItem.end);const detail=(0,react.useMemo)(()=>inspectorJson(objects===void 0?record?.value:void 0),[record,objects]);const detailValue=objectTarget===void 0?record?.value:objectTarget.read();const breadcrumbs=[objectHistory?.rootLabel??rowLabel,...objectHistory?.references.map(reference=>`${t(`object.${reference.kind}`)} · ${reference.identity}`)??[]];const columns=showTime?5:4;return(0,react_jsx_runtime.jsxs)(`section`,{className:inspector_module_css_default.root,"aria-label":title,children:[(0,react_jsx_runtime.jsxs)(`div`,{className:inspector_module_css_default.toolbar,children:[(0,react_jsx_runtime.jsxs)(`span`,{children:[modeSelector??title,` · `,typeFilter.active?`${filtered.matches.size} / ${allRows.length}`:allRows.length]}),hasMore&&(0,react_jsx_runtime.jsx)(`button`,{type:`button`,disabled:loading,onClick:()=>{followMode.current=`scroll`;setFailure(null);loadOlder().catch(error=>{setFailure(String(error))})},children:loading?t(`table.loading`):t(`table.older`)}),(0,react_jsx_runtime.jsx)(`button`,{type:`button`,onClick:()=>{followMode.current=`tail`;resetSpacing(value=>value+1)},children:t(`table.latest`)})]}),notice!==void 0&&(0,react_jsx_runtime.jsx)(`div`,{className:inspector_module_css_default.pickNotice,role:`status`,children:notice}),(failure!==null||openError!==null)&&(0,react_jsx_runtime.jsx)(`p`,{role:`alert`,children:failure??openError?.message}),(0,react_jsx_runtime.jsxs)(`div`,{ref:scroller,className:inspector_module_css_default.scroller,onScroll:({currentTarget})=>{viewport.current.offset=currentTarget.scrollTop;if(followMode.current!==`manual`)followMode.current=currentTarget.scrollHeight-currentTarget.clientHeight-currentTarget.scrollTop<=40?`tail`:`scroll`},children:[(0,react_jsx_runtime.jsxs)(`table`,{className:inspector_module_css_default.table,"aria-label":title,"aria-rowcount":rows.length+1,children:[(0,react_jsx_runtime.jsx)(`thead`,{children:(0,react_jsx_runtime.jsxs)(`tr`,{children:[(0,react_jsx_runtime.jsx)(`th`,{className:inspector_module_css_default.idColumn,children:t(`table.id`)}),(0,react_jsx_runtime.jsx)(`th`,{className:inspector_module_css_default.typeColumn,children:(0,react_jsx_runtime.jsxs)(`span`,{className:inspector_module_css_default.typeHeader,children:[t(`table.type`),(0,react_jsx_runtime.jsx)(TypeFilter,{value:typeQuery,suggest:suggestTypes,apply:applyTypeFilter,t})]})}),(0,react_jsx_runtime.jsx)(`th`,{className:inspector_module_css_default.locationColumn,children:t(`table.location`)}),showTime&&(0,react_jsx_runtime.jsx)(`th`,{className:inspector_module_css_default.timeColumn,children:t(`table.time`)}),(0,react_jsx_runtime.jsx)(`th`,{children:t(`table.data`)})]})}),(0,react_jsx_runtime.jsxs)(`tbody`,{children:[items.map((item,position)=>{const gap=item.start-(items[position-1]?.end??30);const entry=layout.items[item.index];const arrival=arrivals.get(entry.row.key);return(0,react_jsx_runtime.jsxs)(react.Fragment,{children:[gap>0&&(0,react_jsx_runtime.jsx)(`tr`,{"aria-hidden":`true`,children:(0,react_jsx_runtime.jsx)(`td`,{colSpan:columns,style:{height:gap,padding:0}})}),(0,react_jsx_runtime.jsx)(DataRow,{row:entry.row,selected:entry.row.key===selected,context:typeFilter.active&&!filtered.matches.has(entry.row.key),branch:hierarchy.isBranch(entry.row.key),collapsed:inspectorRowCollapsed(entry.row,disclosures),stickyLevel:sticky.get(item.index),pulse:reveal?.key===entry.row.key?reveal.pulse:0,added:performance.now()-arrival<700,useRecord,select,toggle,flash,showTime,t})]},item.key)}),bottom>0&&(0,react_jsx_runtime.jsx)(`tr`,{"aria-hidden":`true`,"data-inspector-fold-space":layout.bottomPadding>0?``:void 0,children:(0,react_jsx_runtime.jsx)(`td`,{colSpan:columns,style:{height:bottom,padding:0}})})]})]}),rows.length===0&&(0,react_jsx_runtime.jsx)(`p`,{className:inspector_module_css_default.empty,children:t(`table.empty`)})]}),selected!==null&&(0,react_jsx_runtime.jsx)(InspectorDetails,{failed:detail.failed,text:record===void 0?t(`table.removed`):detail.failed?`${t(`table.rawError`)}\n${detail.text}`:detail.text,close:()=>{setSelected(null);setObjectHistory(null)},t,children:objects===void 0?record===void 0||detail.failed?void 0:(0,react_jsx_runtime.jsx)(InspectorJsonTree,{text:detail.text,t},selected):(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`nav`,{className:inspector_module_css_default.objectBreadcrumbs,"aria-label":t(`object.navigation`),children:(0,react_jsx_runtime.jsx)(`ol`,{children:breadcrumbs.map((label,index)=>(0,react_jsx_runtime.jsxs)(`li`,{children:[index>0&&(0,react_jsx_runtime.jsx)(`span`,{"aria-hidden":`true`,children:`›`}),(0,react_jsx_runtime.jsx)(`button`,{type:`button`,title:label,disabled:index===breadcrumbs.length-1,"aria-current":index===breadcrumbs.length-1?`page`:void 0,onClick:()=>{backToObject(index)},children:label})]},index))})}),(0,react_jsx_runtime.jsx)(InspectorObjectTree,{value:detailValue,objects,navigate,t},objectTarget?.id??selected)]})})]})}function visibleChatRect(element){const rect=element.getBoundingClientRect();let left=Math.max(0,rect.left),right=Math.min(window.innerWidth,rect.right);let top=Math.max(0,rect.top),bottom=Math.min(window.innerHeight,rect.bottom);for(let parent=element.parentElement;parent!==null;parent=parent.parentElement){if(!parent.matches(`[data-conversation-scroll], [data-step-process-body]`))continue;const bounds=parent.getBoundingClientRect();left=Math.max(left,bounds.left);right=Math.min(right,bounds.right);top=Math.max(top,bounds.top);bottom=Math.min(bottom,bounds.bottom);if(parent.hasAttribute(`data-conversation-scroll`)){const composer=parent.querySelector(`:scope > [data-composer-seat]`)?.getBoundingClientRect();if(composer!==void 0&&composer.height>0)bottom=Math.min(bottom,composer.top)}}return bottom<=top||right<=left?void 0:{left,top,width:right-left,height:bottom-top}}function placeChatHighlight(overlay,element){const rect=visibleChatRect(element);if(rect===void 0)return false;Object.assign(overlay.style,{left:`${rect.left}px`,top:`${rect.top}px`,width:`${rect.width}px`,height:`${rect.height}px`});return true}const SCROLL_QUIET_MS=150;const SCROLL_KEYS=new Set([`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `,`Escape`]);function hasRenderedBox(element){if(!displayed(element))return false;const box=element.getBoundingClientRect();return box.width>0&&box.height>0}var InspectorChatRevealer=class{getRoot;frame;overlay;animation;cancelScroll;constructor(getRoot){this.getRoot=getRoot}reveal(targets){this.dispose();this.frame=requestAnimationFrame(()=>{this.frame=void 0;const root=this.getRoot();if(root===void 0)return;for(const initial of findChatTargets(root,targets)){if(!root.contains(initial))continue;const hidden=[];for(let element=initial;element!==null&&element!==root;element=element.parentElement)if(element.getAttribute(`hidden`)===`until-found`)hidden.push(element);if(hidden.length>0||visibleChatRect(initial)===void 0)root.closest(`[data-conversation-scroll]`)?.dispatchEvent(new Event(`beforematch`));for(const element of hidden.reverse())(0,react_dom.flushSync)(()=>{element.dispatchEvent(new Event(`beforematch`))});if(this.getRoot()!==root)return;const row=root.contains(initial)?initial:findChatTargets(root,targets).find(hasRenderedBox);if(row===void 0||!hasRenderedBox(row))continue;if(visibleChatRect(row)===void 0){if(!window.matchMedia(`(prefers-reduced-motion: reduce)`).matches){this.smoothScroll(row,root,targets);return}row.scrollIntoView({behavior:`instant`,block:`center`,inline:`nearest`})}this.queueFlash(row,root,targets);return}if(displayed(root)&&visibleChatRect(root)!==void 0)this.queueFlash(root,root,targets)})}dispose(){if(this.frame!==void 0)cancelAnimationFrame(this.frame);this.frame=void 0;this.cancelScroll?.();if(this.animation!==void 0){this.animation.onfinish=null;this.animation.cancel()}this.animation=void 0;this.overlay?.remove();this.overlay=void 0}queueFlash(row,root,targets){this.frame=requestAnimationFrame(()=>{this.frame=void 0;if(this.getRoot()!==root){this.dispose();return}if(this.flash(row))return;for(const candidate of findChatTargets(root,targets))if(candidate!==row&&this.flash(candidate))return;if(row!==root&&this.flash(root))return;this.dispose()})}smoothScroll(row,root,targets){const parents=new Set;for(let element=row.parentElement;element!==null;element=element.parentElement)parents.add(element);const moving=new Set;let pending=true;let quiet;let settledFrame;const targetOf=event=>{const target=event.target===document?document.scrollingElement:event.target;return target instanceof Element&&parents.has(target)?target:void 0};const cleanup=()=>{pending=false;window.clearTimeout(quiet);if(settledFrame!==void 0)cancelAnimationFrame(settledFrame);window.removeEventListener(`scroll`,onScroll,true);window.removeEventListener(`scrollend`,onEnd,true);for(const type of[`wheel`,`touchstart`,`pointerdown`,`keydown`])window.removeEventListener(type,interrupt,true);this.cancelScroll=void 0};const finish=()=>{if(!pending)return;cleanup();this.queueFlash(row,root,targets)};const awaitQuiet=()=>{window.clearTimeout(quiet);quiet=window.setTimeout(finish,SCROLL_QUIET_MS)};const onScroll=event=>{const target=targetOf(event);if(target===void 0)return;moving.add(target);awaitQuiet()};const onEnd=event=>{const target=targetOf(event);if(target===void 0||!moving.delete(target)||moving.size>0||settledFrame!==void 0)return;settledFrame=requestAnimationFrame(()=>{settledFrame=void 0;if(moving.size===0)finish()})};const cancel=()=>{if(!pending)return;cleanup();for(const element of parents)if(element.isConnected&&(element.scrollHeight>element.clientHeight||element.scrollWidth>element.clientWidth))element.scrollTo({top:element.scrollTop,left:element.scrollLeft,behavior:`instant`})};const interrupt=event=>{if(event instanceof KeyboardEvent&&!SCROLL_KEYS.has(event.key))return;cancel();this.dispose()};this.cancelScroll=cancel;window.addEventListener(`scroll`,onScroll,{capture:true,passive:true});window.addEventListener(`scrollend`,onEnd,{capture:true,passive:true});for(const type of[`wheel`,`touchstart`,`pointerdown`,`keydown`])window.addEventListener(type,interrupt,{capture:true,passive:true});awaitQuiet();row.scrollIntoView({behavior:`smooth`,block:`center`,inline:`nearest`})}flash(row){if(window.matchMedia(`(prefers-reduced-motion: reduce)`).matches){this.dispose();return true}if(!displayed(row))return false;const overlay=document.createElement(`div`);if(!placeChatHighlight(overlay,row))return false;overlay.className=inspector_module_css_default.chatReveal;overlay.dataset.sessionInspectorHighlight=`reveal`;overlay.setAttribute(`aria-hidden`,`true`);document.body.append(overlay);this.overlay=overlay;const animation=overlay.animate([{opacity:.65},{opacity:.1},{opacity:.5},{opacity:0}],{duration:700});this.animation=animation;animation.onfinish=()=>{if(this.animation===animation)this.dispose()};return true}};function SessionInspectorView(props){const[mode,setMode]=(0,react.useState)(`session-log`);const[picking,setPicking]=(0,react.useState)(false);const[pickFailed,setPickFailed]=(0,react.useState)(false);const[pickedRow,setPickedRow]=(0,react.useState)();const pickButton=(0,react.useRef)(null);const chat=mode===`chat-node`;const revealer=(0,react.useMemo)(()=>new InspectorChatRevealer(props.chatRoot),[props.chatRoot]);(0,react.useEffect)(()=>()=>{revealer.dispose()},[revealer,mode]);const typeOf=(0,react.useCallback)(key=>props.recordType(key,mode),[props.recordType,mode]);const revealChat=(0,react.useCallback)(target=>{revealer.reveal(props.resolveChatTargets(target))},[revealer,props.resolveChatTargets]);const navigation=(0,react.useMemo)(()=>({reveal:revealChat,target:chat?key=>props.objects.row(key)?.target:props.logChatTarget}),[chat,props.objects,props.logChatTarget,revealChat]);(0,react.useEffect)(()=>{if(!picking||pickButton.current===null)return;revealer.dispose();const stopPicking=props.pickChat(pickButton.current,target=>{const key=props.pickRow(target,mode);if(key===void 0){setPickFailed(true);return false}setPickedRow({key});setPicking(false);setPickFailed(false);return true},()=>{setPicking(false);setPickFailed(false)});if(stopPicking===void 0){setPicking(false);setPickFailed(true)}return stopPicking},[picking,mode,props.pickChat,props.pickRow,revealer]);const selector=(0,react_jsx_runtime.jsxs)(`span`,{className:inspector_module_css_default.modeControls,children:[(0,react_jsx_runtime.jsxs)(`select`,{className:inspector_module_css_default.modeSelector,"aria-label":props.t(`view.presentation`),value:mode,onChange:event=>{setPicking(false);setPickFailed(false);setPickedRow(void 0);setMode(event.currentTarget.value===`chat-node`?`chat-node`:`session-log`)},children:[(0,react_jsx_runtime.jsx)(`option`,{value:`session-log`,children:props.t(`view.sessionLog`)}),(0,react_jsx_runtime.jsx)(`option`,{value:`chat-node`,children:props.t(`view.chatNode`)})]}),(0,react_jsx_runtime.jsx)(`button`,{ref:pickButton,type:`button`,className:inspector_module_css_default.pickButton,"aria-pressed":picking,"aria-label":props.t(`picker.pick`),title:props.t(picking?`picker.cancel`:`picker.pick`),onClick:()=>{setPickFailed(false);setPicking(value=>!value)},children:(0,react_jsx_runtime.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.3`,"aria-hidden":`true`,children:[(0,react_jsx_runtime.jsx)(`circle`,{cx:`8`,cy:`8`,r:`4.5`}),(0,react_jsx_runtime.jsx)(`path`,{d:`M8 0v5M8 11v5M0 8h5M11 8h5`})]})})]});return(0,react_jsx_runtime.jsx)(InspectorTable,{title:props.t(chat?`view.chatNode`:`view.sessionLog`),modeSelector:selector,pickedRow,notice:picking?props.t(pickFailed?`picker.noMatch`:`picker.instructions`):pickFailed?props.t(`picker.noChat`):void 0,useRows:chat?props.useChatRows:props.useLogRows,useRecord:chat?props.useChatRecord:props.useLogRecord,useSession:props.useSession,loadOlder:props.loadOlder,typeOf,t:props.t,flash:chat,showTime:!chat,navigation,...chat?{objects:props.objects}:{}},mode)}function nearest(nodes,seq){let best;for(const node of nodes)if(best===void 0||Math.abs(node.anchorSeq-seq)<Math.abs(best.anchorSeq-seq))best=node;return best}function primaryTarget(target,visible){if(target.nodeKey!==void 0||target.anchorSeq===void 0)return target;const inTurn=target.turn===void 0?visible:visible.filter(node=>(node.location.kind===`turn`||node.location.kind===`step`)&&node.location.turn.turn===target.turn);const inStep=target.step===void 0?inTurn:inTurn.filter(node=>node.location.kind===`step`&&node.location.step.step===target.step);const rootCallId=target.rootCallId??target.callId;const tool=rootCallId===void 0?void 0:visible.find(node=>node.kind===`tool-call`&&node.data.root.callId===rootCallId);const exact=inStep.find(node=>node.anchorSeq===target.anchorSeq);const kind=target.nodeKind===void 0?void 0:inStep.find(node=>node.kind===target.nodeKind);const node=tool??exact??kind??nearest(inStep,target.anchorSeq)??nearest(inTurn,target.anchorSeq);if(node===void 0)return target;const turn=target.turn??(node.location.kind===`turn`||node.location.kind===`step`?node.location.turn.turn:void 0);return{...target,nodeKey:node.key,...turn===void 0?{}:{turn}}}function nodeTarget(node){const location=node.location;return{nodeKey:node.key,anchorSeq:node.anchorSeq,...location.kind===`turn`||location.kind===`step`?{turn:location.turn.turn}:{},...location.kind===`step`?{step:location.step.step}:{}}}function targetKey(target){return JSON.stringify([target.anchorSeq,target.callId,target.rootCallId,target.nodeKey,target.nodeKind,target.groupKey,target.groupPart,target.turn,target.step])}function resolveChatRevealTargets(target,nodes){const visible=nodes.filter(node=>node.visibility===`visible`);const explicit=target.nodeKey===void 0?void 0:nodes.find(node=>node.key===target.nodeKey);const position=explicit===void 0?void 0:nodeTarget(explicit);const referenceSeq=target.anchorSeq??position?.anchorSeq;const turn=target.turn??position?.turn;const step=target.step??position?.step;const primary=position===void 0?primaryTarget(target,visible):{...target,anchorSeq:target.anchorSeq??position.anchorSeq,...turn===void 0?{}:{turn},...step===void 0?{}:{step}};if(referenceSeq===void 0)return[primary];const rank=candidate=>{const sameTurn=turn===void 0||candidate.turn===turn;if(sameTurn&&step!==void 0&&candidate.step===step)return 0;return sameTurn&&turn!==void 0?1:2};const neighbors=visible.map(nodeTarget).sort((left,right)=>rank(left)-rank(right)||Math.abs(left.anchorSeq-referenceSeq)-Math.abs(right.anchorSeq-referenceSeq));const candidates=[primary];const seen=new Set([targetKey(primary)]);for(const candidate of neighbors){const key=targetKey(candidate);if(seen.has(key))continue;seen.add(key);candidates.push(candidate)}return candidates}const POINTER_ACTIONS=[`pointerdown`,`pointerup`,`mousedown`,`mouseup`,`auxclick`,`dblclick`,`contextmenu`];var InspectorChatPicker=class{getRoot;owner;picked;cancelled;released;mask;overlay;root;observing;resizing;constructor(getRoot,owner,picked,cancelled,released){this.getRoot=getRoot;this.owner=owner;this.picked=picked;this.cancelled=cancelled;this.released=released}start(){const root=this.getRoot();if(root===void 0||!displayed(root)||!displayed(this.owner))return false;const mask=document.createElement(`div`);if(!placeChatHighlight(mask,root))return false;mask.className=inspector_module_css_default.chatPickMask;mask.dataset.sessionInspectorPicker=``;mask.setAttribute(`aria-hidden`,`true`);this.root=root;this.mask=mask;mask.addEventListener(`pointermove`,this.move);mask.addEventListener(`pointerleave`,this.hide);mask.addEventListener(`click`,this.click);mask.addEventListener(`wheel`,this.wheel,{passive:false});for(const type of POINTER_ACTIONS)mask.addEventListener(type,this.suppress);document.body.append(mask);window.addEventListener(`keydown`,this.keydown,true);window.addEventListener(`blur`,this.cancel);window.addEventListener(`scroll`,this.position,true);window.addEventListener(`resize`,this.position);this.observing=new MutationObserver(this.verify);for(const start of[this.owner,root])for(let element=start;element!==null;element=element.parentElement)this.observing.observe(element,{attributes:true,attributeFilter:[`hidden`,`style`,`class`],childList:true});if(typeof ResizeObserver!==`undefined`){this.resizing=new ResizeObserver(this.position);this.resizing.observe(root)}return true}dispose(){const mask=this.mask;if(mask!==void 0){mask.removeEventListener(`pointermove`,this.move);mask.removeEventListener(`pointerleave`,this.hide);mask.removeEventListener(`click`,this.click);mask.removeEventListener(`wheel`,this.wheel);for(const type of POINTER_ACTIONS)mask.removeEventListener(type,this.suppress);mask.remove()}this.mask=void 0;this.root=void 0;window.removeEventListener(`keydown`,this.keydown,true);window.removeEventListener(`blur`,this.cancel);window.removeEventListener(`scroll`,this.position,true);window.removeEventListener(`resize`,this.position);this.observing?.disconnect();this.observing=void 0;this.resizing?.disconnect();this.resizing=void 0;this.hide();this.released()}currentRoot(){const root=this.root;return root!==void 0&&this.getRoot()===root&&displayed(root)&&displayed(this.owner)?root:void 0}position=()=>{this.hide();this.verify()};verify=()=>{if(this.mask===void 0)return;const root=this.currentRoot();if(root===void 0||!placeChatHighlight(this.mask,root))this.cancel()};hit(event){if(this.mask===void 0)return void 0;const root=this.currentRoot();if(root===void 0){this.cancel();return}const element=document.elementsFromPoint(event.clientX,event.clientY).find(element=>element!==this.mask&&element!==this.overlay);return element!==void 0&&inChat(element,root)?{element,root}:void 0}hide=()=>{this.overlay?.remove();this.overlay=void 0};cancel=()=>{if(this.mask===void 0)return;this.dispose();this.cancelled()};move=event=>{const hit=this.hit(event);const match=hit===void 0?void 0:matchChatElement(hit.element,hit.root);if(match===void 0){this.hide();return}const overlay=this.overlay??document.createElement(`div`);overlay.className=inspector_module_css_default.chatPick;overlay.dataset.sessionInspectorHighlight=`pick`;overlay.setAttribute(`aria-hidden`,`true`);if(!placeChatHighlight(overlay,match.element)){this.hide();return}if(this.overlay===void 0){document.body.append(overlay);this.overlay=overlay}};suppress=event=>{event.preventDefault();event.stopImmediatePropagation()};click=event=>{this.suppress(event);if(event.button!==0)return;const hit=this.hit(event);const match=hit===void 0?void 0:matchChatElement(hit.element,hit.root);if(match!==void 0&&this.picked(match.target))this.dispose()};wheel=event=>{this.suppress(event);const hit=this.hit(event);for(let element=hit?.element??null;element!==null;element=element.parentElement){if(!(element instanceof HTMLElement)||!element.matches(`[data-conversation-scroll], [data-step-process-body]`))continue;const vertical=event.deltaY<0?element.scrollTop>0:element.scrollTop+element.clientHeight<element.scrollHeight;const horizontal=event.deltaX<0?element.scrollLeft>0:element.scrollLeft+element.clientWidth<element.scrollWidth;if(!(event.deltaY!==0&&vertical||event.deltaX!==0&&horizontal))continue;const style=getComputedStyle(element);const scale=event.deltaMode===WheelEvent.DOM_DELTA_PAGE?element.clientHeight:event.deltaMode===WheelEvent.DOM_DELTA_LINE?Number.parseFloat(style.lineHeight)||Number.parseFloat(style.fontSize)||1:1;element.scrollBy({top:event.deltaY*scale,left:event.deltaX*scale,behavior:`instant`});break}};keydown=event=>{if(event.key!==`Escape`)return;this.suppress(event);this.cancel()}};function registerInspectorTab(ctx){let activePicker;let disposed=false;ctx.effect(()=>()=>{disposed=true;activePicker?.dispose()},`session-inspector: chat picker`);const t=ctx.locale.bind(NS);const id=`@unieai/rabi-experimental-session-inspector`;ctx.effect(()=>ctx.sidebarRightTabs.register({id,kind:`session-inspector-log`,title:()=>t(`tab.title`),guide:[{id:`open`,order:60,title:()=>t(`tab.title`),description:()=>t(`tab.description`)}]}),`session-inspector: sidebar tab`);const models=new WeakMap;ctx.slots.inject(`sidebar.right.pane.tab`,()=>ctx.slots.register({name:`sidebar.right.pane.tab`,key:id,locale:NS,inject:sessionId=>{const binding=ctx.sessions.binding(sessionId);if(binding===void 0)throw new Error(`session-inspector: unknown Session ${sessionId}`);let sources=models.get(binding);if(sources===void 0){const conversation=ctx.uiConversation.binding(binding);const chat=new ChatNodeModel(conversation);const log=new SessionLogModel(binding.eventSource);const chatRoot=()=>ctx.uiSession.adapter.current.getSnapshot().key===sessionId?mainChatRoot():void 0;sources={hooks:{chatRows:chat,logRows:log},keyedHooks:{chatRecord:chat.row,logRecord:log.row},chatRoot,pickChat:(owner,picked,cancelled)=>{if(disposed)return void 0;activePicker?.cancel();const picker=new InspectorChatPicker(chatRoot,owner,picked,cancelled,()=>{if(activePicker===picker)activePicker=void 0});if(!picker.start())return void 0;activePicker=picker;return()=>{picker.dispose()}},resolveChatTargets:target=>resolveChatRevealTargets(target,conversation.snapshot.getSnapshot().views.get(`chat`)?.nodes.values()??[]),recordType:(key,mode)=>(mode===`chat-node`?chat.row(key):log.row(key))?.getSnapshot()?.type,loadOlder:()=>binding.session.loadOlder(),objects:chat.objects(sessionId),logChatTarget:key=>{const anchor=log.chatAnchor(key);if(anchor===void 0)return void 0;return sessionLogChatTarget(anchor)},pickRow:(target,mode)=>{if(mode===`chat-node`)return chat.pick(target);const snapshot=conversation.snapshot.getSnapshot();const groups=snapshot.views.grouped(`chat`);const reference=target.groupKey===void 0?void 0:groups?.entries.find(entry=>entry.kind===`group`&&entry.key===target.groupKey);const group=reference?.kind===`group`?groups?.groupSource(reference.key).getSnapshot():void 0;const nodeKey=target.nodeKey??group?.members[0]?.key;const node=nodeKey===void 0?void 0:snapshot.views.get(`chat`)?.nodes.get(nodeKey);const location=node?.location;return log.pick({...target,...node===void 0?{}:{anchorSeq:node.anchorSeq,nodeKind:node.kind},...location?.kind===`turn`||location?.kind===`step`?{turn:location.turn.turn}:{},...location?.kind===`step`?{step:location.step.step}:{}})}};models.set(binding,sources)}return sources}},SessionInspectorView))}const inject=[`slots`,`locale`,`sessions`,`uiSession`,`uiConversation`,`sidebarRightTabs`];function apply(ctx){ctx.effect(()=>ctx.locale.register(NS,{en,zh,ja,es,fr,de,ru,pt}),`session-inspector: dictionaries`);registerInspectorTab(ctx)}exports.apply=apply;exports.inject=inject;return module.exports}});
package/lib/index.js ADDED
@@ -0,0 +1,6 @@
1
+ //#region lib/types/index.js
2
+ /** Host discovery entry for the Session Inspector browser plugin. */
3
+ /** Mount the inert Host half; Session inspection belongs to the Client. */
4
+ function apply() {}
5
+ //#endregion
6
+ export { apply };
@@ -0,0 +1,10 @@
1
+ /** Browser plugin contributing the Session Inspector Log sidebar tab. */
2
+ import type { Context } from '@unieai/cordis';
3
+ /** Services required to register the localized Session-bound sidebar tab. */
4
+ export declare const inject: string[];
5
+ /**
6
+ * Register the Inspector tab for this plugin's lifetime.
7
+ * @param ctx - Client plugin context owning the dictionaries and registrations.
8
+ */
9
+ export declare function apply(ctx: Context): void;
10
+ //# sourceMappingURL=index.d.ts.map