@unieai/rabi-experimental-session-inspector 0.2.1-rc.3 → 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 (41) hide show
  1. package/lib/client.js +3 -4243
  2. package/lib/types/client/locales.d.ts +330 -0
  3. package/lib/types/client/views/InspectorObjectTree.d.ts +2 -2
  4. package/locale/de.json +6 -0
  5. package/locale/en.json +1 -1
  6. package/locale/es.json +6 -0
  7. package/locale/fr.json +6 -0
  8. package/locale/ja.json +6 -0
  9. package/locale/pt.json +6 -0
  10. package/locale/ru.json +6 -0
  11. package/package.json +5 -2
  12. package/src/client/index.ts +19 -0
  13. package/src/client/locales.ts +462 -0
  14. package/src/client/views/InspectorDetails.tsx +75 -0
  15. package/src/client/views/InspectorObjectTree.tsx +122 -0
  16. package/src/client/views/InspectorTable.tsx +345 -0
  17. package/src/client/views/TypeFilter.tsx +129 -0
  18. package/src/client/views/View.tsx +98 -0
  19. package/src/client/views/chat-node/dom.ts +87 -0
  20. package/src/client/views/chat-node/highlight.ts +41 -0
  21. package/src/client/views/chat-node/model.ts +212 -0
  22. package/src/client/views/chat-node/objects.ts +90 -0
  23. package/src/client/views/chat-node/pick-match.ts +68 -0
  24. package/src/client/views/chat-node/picker.ts +172 -0
  25. package/src/client/views/chat-node/reveal-target.ts +90 -0
  26. package/src/client/views/chat-node/reveal.ts +178 -0
  27. package/src/client/views/format.ts +33 -0
  28. package/src/client/views/index.ts +80 -0
  29. package/src/client/views/inspector.module.css +181 -0
  30. package/src/client/views/object-value.ts +100 -0
  31. package/src/client/views/objects.ts +42 -0
  32. package/src/client/views/raw-json.ts +44 -0
  33. package/src/client/views/session-log/chat-target.ts +47 -0
  34. package/src/client/views/session-log/groups.ts +47 -0
  35. package/src/client/views/session-log/model.ts +218 -0
  36. package/src/client/views/session-log/stream.ts +78 -0
  37. package/src/client/views/table-layout.ts +110 -0
  38. package/src/client/views/table-model.ts +122 -0
  39. package/src/client/views/type-filter.ts +82 -0
  40. package/src/css-modules.d.ts +5 -0
  41. package/src/index.ts +4 -0
package/lib/client.js CHANGED
@@ -1,4244 +1,4 @@
1
- window.__ModuleLoader__.load({
2
- id: "@unieai/rabi-experimental-session-inspector",
3
- factory: (require) => {
4
- var module = { exports: {} };
5
- var exports = module.exports;
6
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
- let _unieai_rabi_client_store = require("@unieai/rabi-client-store");
8
- let react_jsx_runtime = require("react/jsx-runtime");
9
- let react = require("react");
10
- let _tanstack_react_virtual = require("@tanstack/react-virtual");
11
- let _unieai_rabi_client_ui_primitives = require("@unieai/rabi-client-ui-primitives");
12
- let react_dom = require("react-dom");
13
- //#region lib/types/client/locales.js
14
- /** Session Inspector tab, table controls, and object navigation labels. */
15
- /** Namespace owned by the Session Inspector plugin. */
16
- const NS = "session-inspector";
17
- /** Simplified Chinese labels and dictionary keys. */
18
- const zh = {
19
- "tab.title": "会话数据诊断",
20
- "tab.description": "在侧边栏分析当前会话原始日志和聊天分组数据",
21
- "view.presentation": "展示形式",
22
- "view.sessionLog": "原始数据",
23
- "view.chatNode": "对话分组",
24
- "picker.pick": "在对话面板中选取元素",
25
- "picker.cancel": "取消选取 (Esc)",
26
- "picker.instructions": "在左侧 Chat 中悬停预览,点击选取;Esc 取消。",
27
- "picker.noMatch": "当前表格没有匹配记录,请选择其他元素或按 Esc 取消。",
28
- "picker.noChat": "请先在主区域打开当前 Session 的 Chat。",
29
- "table.id": "序号",
30
- "table.type": "类型",
31
- "filter.title": "筛选类型",
32
- "filter.input": "类型关键词",
33
- "filter.placeholder": "输入类型片段,如 delta",
34
- "filter.help": "默认包含匹配(*关键词*);Enter 确认,Esc 取消。",
35
- "filter.candidates": "类型候选",
36
- "filter.loading": "正在查找候选…",
37
- "filter.failed": "无法获取类型候选。",
38
- "filter.noCandidates": "没有匹配候选,仍可确认当前关键词。",
39
- "filter.clear": "清空",
40
- "filter.cancel": "取消",
41
- "filter.apply": "确认筛选",
42
- "filter.context": "匹配记录的父级上下文",
43
- "table.location": "T/S",
44
- "table.time": "时间 (UTC)",
45
- "table.data": "数据",
46
- "table.older": "加载更早",
47
- "table.loading": "加载中…",
48
- "table.latest": "跟踪最新",
49
- "table.empty": "暂无记录",
50
- "table.raw": "原始数据",
51
- "table.rawError": "无法序列化这条记录,可以选择其他记录继续查看。",
52
- "table.resizeDetails": "调整原始数据面板高度",
53
- "table.close": "关闭",
54
- "table.expand": "展开子行",
55
- "table.collapse": "收起子行",
56
- "table.removed": "该记录已移除或结算,请选择当前记录。",
57
- "object.node": "Node",
58
- "object.nodeData": "Node Data",
59
- "object.group": "Group",
60
- "object.groupData": "Group Data",
61
- "object.turn": "Turn",
62
- "object.turnData": "Turn Data",
63
- "object.step": "Step",
64
- "object.stepData": "Step Data",
65
- "object.accessor": "[Getter / Setter,未执行]",
66
- "object.empty": "空",
67
- "object.absent": "[空槽]",
68
- "object.properties": "其他属性",
69
- "object.more": "显示更多",
70
- "object.navigation": "原始数据导航"
71
- };
72
- /** English labels, checked against the Chinese key set. */
73
- const en = {
74
- "tab.title": "Session Log",
75
- "tab.description": "Analyze raw logs and grouped chat messages for the current session in the sidebar.",
76
- "view.presentation": "Presentation",
77
- "view.sessionLog": "Raw Log",
78
- "view.chatNode": "Chat Group",
79
- "picker.pick": "Pick an element in Chat View",
80
- "picker.cancel": "Cancel picking (Esc)",
81
- "picker.instructions": "Hover in the main Chat to preview, then click to select. Esc cancels.",
82
- "picker.noMatch": "No matching record in this table. Pick another element or press Esc to cancel.",
83
- "picker.noChat": "Open this Session in the main Chat before picking.",
84
- "table.id": "Index",
85
- "table.type": "Type",
86
- "filter.title": "Filter types",
87
- "filter.input": "Type keyword",
88
- "filter.placeholder": "Type a fragment, e.g. delta",
89
- "filter.help": "Contains matching (*keyword*). Enter confirms; Esc cancels.",
90
- "filter.candidates": "Type suggestions",
91
- "filter.loading": "Finding suggestions…",
92
- "filter.failed": "Type suggestions could not be loaded.",
93
- "filter.noCandidates": "No suggestions. You can still apply this keyword.",
94
- "filter.clear": "Clear",
95
- "filter.cancel": "Cancel",
96
- "filter.apply": "Apply filter",
97
- "filter.context": "Parent context of a matching record",
98
- "table.location": "T/S",
99
- "table.time": "Time (UTC)",
100
- "table.data": "Data",
101
- "table.older": "Load earlier",
102
- "table.loading": "Loading…",
103
- "table.latest": "Follow Latest",
104
- "table.empty": "No records",
105
- "table.raw": "Raw data",
106
- "table.rawError": "This record could not be serialized. Select another record to continue.",
107
- "table.resizeDetails": "Resize raw data panel",
108
- "table.close": "Close",
109
- "table.expand": "Expand children",
110
- "table.collapse": "Collapse children",
111
- "table.removed": "This record was removed or settled. Select a current record.",
112
- "object.node": "Node",
113
- "object.nodeData": "Node Data",
114
- "object.group": "Group",
115
- "object.groupData": "Group Data",
116
- "object.turn": "Turn",
117
- "object.turnData": "Turn Data",
118
- "object.step": "Step",
119
- "object.stepData": "Step Data",
120
- "object.accessor": "[Getter / Setter, not evaluated]",
121
- "object.empty": "Empty",
122
- "object.absent": "[Empty slot]",
123
- "object.properties": "Other properties",
124
- "object.more": "Show more",
125
- "object.navigation": "Raw data navigation"
126
- };
127
- //#endregion
128
- //#region lib/types/client/views/table-model.js
129
- /** Row identities and raw values shared by the two virtual inspector tables. */
130
- /**
131
- * Resolve a manual choice or the block lifecycle default.
132
- * @param row - Current row metadata.
133
- * @param choices - Table-local user choices.
134
- * @returns Whether the row's descendants are hidden.
135
- */
136
- function inspectorRowCollapsed(row, choices) {
137
- const choice = choices.get(row.key);
138
- return choice !== void 0 && choice.state === row.disclosure ? choice.collapsed : row.disclosure === "closed";
139
- }
140
- /** Table-local hierarchy index for disclosure and virtualized sticky ancestors. */
141
- var InspectorTableHierarchy = class {
142
- /** Depth-first row order with folded descendants omitted. */
143
- rows;
144
- byKey = /* @__PURE__ */ new Map();
145
- branches = /* @__PURE__ */ new Set();
146
- /**
147
- * @param rows - Complete depth-first row order.
148
- * @param choices - Table-local disclosure overrides.
149
- */
150
- constructor(rows, choices) {
151
- const visible = [];
152
- let hiddenDepth;
153
- for (const row of rows) {
154
- if (row.parent !== void 0) this.branches.add(row.parent);
155
- if (row.disclosure !== void 0) this.branches.add(row.key);
156
- if (hiddenDepth !== void 0 && row.depth > hiddenDepth) continue;
157
- hiddenDepth = inspectorRowCollapsed(row, choices) ? row.depth : void 0;
158
- this.byKey.set(row.key, visible.length);
159
- visible.push(row);
160
- }
161
- this.rows = visible;
162
- }
163
- /**
164
- * Identify rows that own descendants or an explicit disclosure state.
165
- * @param key - Row identity.
166
- * @returns Whether this row owns a disclosure.
167
- */
168
- isBranch(key) {
169
- return this.branches.has(key);
170
- }
171
- /**
172
- * Find the current row's visible parent headers, including itself when it is a header.
173
- * @param index - First row at the viewport's scroll offset.
174
- * @returns Ordered indexes retained above the virtual viewport.
175
- */
176
- stickyIndexes(index) {
177
- const indexes = [];
178
- let row = this.rows[index];
179
- if (row !== void 0 && this.isBranch(row.key)) indexes.push(index);
180
- while (row?.parent !== void 0) {
181
- const parent = this.byKey.get(row.parent);
182
- if (parent === void 0) break;
183
- indexes.push(parent);
184
- row = this.rows[parent];
185
- }
186
- return indexes.reverse();
187
- }
188
- };
189
- /** Converts a keyed source without changing snapshot identity on unchanged input. */
190
- var InspectorRecordSource = class {
191
- source;
192
- project;
193
- previous;
194
- snapshot;
195
- /**
196
- * @param source - Existing keyed business source.
197
- * @param project - Raw metadata projection, evaluated only after its input changes.
198
- */
199
- constructor(source, project) {
200
- this.source = source;
201
- this.project = project;
202
- }
203
- /** @returns Stable metadata for the current raw value. */
204
- getSnapshot = () => {
205
- const value = this.source.getSnapshot();
206
- if (value !== this.previous) {
207
- this.previous = value;
208
- this.snapshot = value === void 0 ? void 0 : this.project(value);
209
- }
210
- return this.snapshot;
211
- };
212
- /** @param listener - Row invalidation callback. @returns Its disposer. */
213
- subscribe = (listener) => this.source.subscribe(listener);
214
- };
215
- const DELTA_PREVIEW_FIELDS = new Map([["tool-call-delta", ["argumentsDelta"]], ["reasoning-delta", ["text"]]]);
216
- function preview(value, depth, hiddenRootFields) {
217
- if (typeof value === "string") return value.slice(0, 180);
218
- if (value === null || typeof value !== "object") return String(value);
219
- if (depth > 1) return Array.isArray(value) ? `[${value.length}]` : "{…}";
220
- const fields = "type" in value && typeof value.type === "string" ? DELTA_PREVIEW_FIELDS.get(value.type) : void 0;
221
- const entries = Object.entries(value).filter(([key]) => !(depth === 0 && (key.toLowerCase() === "time" || hiddenRootFields.includes(key))) && (fields === void 0 ? ![
222
- "type",
223
- "seq",
224
- "sequence"
225
- ].includes(key.toLowerCase()) : fields.includes(key)));
226
- const [first, second] = entries;
227
- if (first !== void 0 && second === void 0) return preview(first[1], depth + 1, hiddenRootFields);
228
- return entries.slice(0, 5).map(([key, item]) => `${key}: ${preview(item, depth + 1, hiddenRootFields)}`).join(" · ").slice(0, 240);
229
- }
230
- /**
231
- * Format horizontal data with type-specific delta fields and bounded nesting.
232
- * @param value - Original row data, which remains unchanged for JSON inspection.
233
- * @param hiddenRootFields - Additional top-level metadata already displayed in the owning table's columns.
234
- * @returns A bounded preview omitting type, sequence, top-level time, and singleton field names.
235
- */
236
- function inspectorPreview(value, hiddenRootFields = []) {
237
- return preview(value, 0, hiddenRootFields);
238
- }
239
- //#endregion
240
- //#region lib/types/client/views/chat-node/objects.js
241
- /** Weak identity index for materialized Nodes, Groups, Turn/Step locations, and their Data readers. */
242
- /** Indexes each immutable publication once, without retaining its objects or node arrays. */
243
- var ChatObjectIndex = class {
244
- binding;
245
- identities = /* @__PURE__ */ new WeakMap();
246
- indexed = /* @__PURE__ */ new WeakSet();
247
- /** @param binding - Existing Session-owned Conversation reader. */
248
- constructor(binding) {
249
- this.binding = binding;
250
- }
251
- /**
252
- * Resolve an original object without retaining replaced publications.
253
- * @param value - Original object identity.
254
- * @returns Its named reference, including older identities, or undefined when unregistered.
255
- */
256
- reference(value) {
257
- this.refresh();
258
- return this.identities.get(value);
259
- }
260
- chat() {
261
- return this.binding.snapshot.getSnapshot().views.get("chat");
262
- }
263
- register(value, reference) {
264
- if (value !== null && typeof value === "object" && !this.identities.has(value)) this.identities.set(value, reference);
265
- }
266
- location(value, step) {
267
- const turn = value.turn;
268
- const identity = step === void 0 ? String(turn) : `${turn}/${step}`;
269
- const kind = step === void 0 ? "turn" : "step";
270
- const read = () => {
271
- const current = this.chat()?.timeline.turns.get(turn);
272
- return step === void 0 ? current : current?.steps.find((value) => value.step === step);
273
- };
274
- const firstNode = step === void 0 ? this.chat()?.locations.getTurn(turn)[0] : this.chat()?.locations.getStep(turn, step)[0];
275
- const target = {
276
- turn,
277
- ...firstNode === void 0 ? {} : { nodeKey: firstNode }
278
- };
279
- this.register(value, {
280
- id: `${kind}:${identity}`,
281
- kind,
282
- identity,
283
- target,
284
- read
285
- });
286
- this.register(value.data, {
287
- id: `${kind}-data:${identity}`,
288
- kind: step === void 0 ? "turnData" : "stepData",
289
- identity,
290
- target,
291
- read: () => read()?.data
292
- });
293
- }
294
- refresh() {
295
- const chat = this.chat();
296
- if (chat === void 0) return;
297
- const nodes = chat.nodes.values();
298
- if (!this.indexed.has(nodes)) {
299
- this.indexed.add(nodes);
300
- for (const node of nodes) {
301
- const { key, location } = node;
302
- const turn = location.kind === "turn" || location.kind === "step" ? location.turn.turn : void 0;
303
- const target = {
304
- nodeKey: key,
305
- ...turn === void 0 ? {} : { turn }
306
- };
307
- this.register(node, {
308
- id: `node:${key}`,
309
- kind: "node",
310
- identity: key,
311
- target,
312
- read: () => this.chat()?.nodes.get(key)
313
- });
314
- this.register(node.data, {
315
- id: `node-data:${key}`,
316
- kind: "nodeData",
317
- identity: key,
318
- target,
319
- read: () => this.chat()?.nodes.get(key)?.data
320
- });
321
- }
322
- }
323
- if (!this.indexed.has(chat.timeline)) {
324
- this.indexed.add(chat.timeline);
325
- for (const turn of chat.timeline.turns.values()) {
326
- this.location(turn);
327
- for (const step of turn.steps) this.location(step, step.step);
328
- }
329
- }
330
- const groups = this.binding.snapshot.getSnapshot().views.grouped("chat");
331
- for (const entry of groups?.entries ?? []) {
332
- if (entry.kind !== "group") continue;
333
- const key = entry.key;
334
- const group = groups.groupSource(key).getSnapshot();
335
- if (group === void 0 || this.indexed.has(group)) continue;
336
- this.indexed.add(group);
337
- const target = { groupKey: key };
338
- const read = () => this.binding.snapshot.getSnapshot().views.grouped("chat")?.groupSource(key).getSnapshot();
339
- this.register(group, {
340
- id: `group:${key}`,
341
- kind: "group",
342
- identity: key,
343
- target,
344
- read
345
- });
346
- this.register(group.data, {
347
- id: `group-data:${key}`,
348
- kind: "groupData",
349
- identity: key,
350
- target,
351
- read: () => read()?.data
352
- });
353
- for (const member of group.members) {
354
- const nodeKey = member.key;
355
- this.register(member, {
356
- id: `node:${nodeKey}`,
357
- kind: "node",
358
- identity: nodeKey,
359
- target: {
360
- nodeKey,
361
- ...member.groupPart === void 0 ? {} : { groupPart: member.groupPart }
362
- },
363
- read: () => this.chat()?.nodes.get(nodeKey)
364
- });
365
- }
366
- }
367
- }
368
- };
369
- //#endregion
370
- //#region lib/types/client/views/chat-node/dom.js
371
- /** DOM lookups owned by the experimental Inspector, using existing Slot and Chat attributes. */
372
- /**
373
- * Check an existing element's mounted and ancestor visibility without revealing it.
374
- * @param element - Candidate element.
375
- * @returns Whether CSS and hidden ancestors allow it to be displayed.
376
- */
377
- function displayed(element) {
378
- if (!element.isConnected || element.closest("[hidden]") !== null) return false;
379
- for (let parent = element; parent !== null; parent = parent.parentElement) {
380
- const style = getComputedStyle(parent);
381
- if (style.display === "none" || style.visibility === "hidden") return false;
382
- }
383
- return true;
384
- }
385
- /**
386
- * Find the displayed main Chat's outer flow column without entering a Sidebar or nested View.
387
- * @returns The current Chat column, or undefined while another View is selected.
388
- */
389
- function mainChatRoot() {
390
- 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));
391
- }
392
- /**
393
- * Restrict a DOM match to the selected Chat column and its own Conversation View.
394
- * @param element - Candidate node, including SVG children.
395
- * @param root - Main Chat column.
396
- * @returns Whether the candidate belongs to that occurrence.
397
- */
398
- function inChat(element, root) {
399
- return root.contains(element) && element.closest("[data-sidebar-right-session]") === null && element.closest("[data-slot=\"conversation.view\"]") === root.closest("[data-slot=\"conversation.view\"]");
400
- }
401
- /**
402
- * Enumerate exact and approximate occurrences without changing their display state.
403
- * @param root - Current main Chat column.
404
- * @param targets - Exact identities followed by nearby loaded Node identities.
405
- * @returns Unique candidates, with the requested Turn's occurrences before other Turns.
406
- */
407
- function findChatTargets(root, targets) {
408
- const fields = [
409
- "chatCallId",
410
- "chatNodeKey",
411
- "chatGroupKey",
412
- "chatTurn"
413
- ];
414
- const indexed = {
415
- chatCallId: /* @__PURE__ */ new Map(),
416
- chatNodeKey: /* @__PURE__ */ new Map(),
417
- chatGroupKey: /* @__PURE__ */ new Map(),
418
- chatTurn: /* @__PURE__ */ new Map()
419
- };
420
- for (const element of root.querySelectorAll("[data-chat-call-id], [data-chat-node-key], [data-chat-group-key], [data-chat-turn]")) {
421
- if (!inChat(element, root)) continue;
422
- for (const field of fields) {
423
- const value = element.dataset[field];
424
- if (value === void 0) continue;
425
- const matches = indexed[field].get(value);
426
- if (matches === void 0) indexed[field].set(value, [element]);
427
- else matches.push(element);
428
- }
429
- }
430
- const found = /* @__PURE__ */ new Set();
431
- const add = (field, value, part) => {
432
- if (value === void 0) return;
433
- for (const element of indexed[field].get(value) ?? []) if (part === void 0 || element.dataset.chatGroupPart === part) found.add(element);
434
- };
435
- const turns = /* @__PURE__ */ new Set();
436
- const preferredTurn = targets.find((target) => target.turn !== void 0)?.turn;
437
- let preferredTurnAdded = false;
438
- for (const [index, target] of targets.entries()) {
439
- if (index > 0 && preferredTurn !== void 0 && target.turn !== preferredTurn && !preferredTurnAdded) {
440
- add("chatTurn", String(preferredTurn));
441
- preferredTurnAdded = true;
442
- }
443
- add("chatCallId", target.callId);
444
- add("chatNodeKey", target.nodeKey, target.groupPart);
445
- add("chatNodeKey", target.nodeKey);
446
- add("chatCallId", target.rootCallId);
447
- add("chatGroupKey", target.groupKey);
448
- if (target.turn !== void 0) turns.add(target.turn);
449
- }
450
- for (const turn of turns) if (!preferredTurnAdded || turn !== preferredTurn) add("chatTurn", String(turn));
451
- return [...found];
452
- }
453
- //#endregion
454
- //#region lib/types/client/views/chat-node/pick-match.js
455
- /** Replaceable element-to-record matching rules for the Inspector's Chat picker. */
456
- /**
457
- * Match tool-call boxes and Node parts before Group or Turn containers; never compare rendered text.
458
- * @param element - Pointer target in the main Chat.
459
- * @param root - Inspected Session's displayed main Chat column.
460
- * @returns Candidate identities and the box to preview, or undefined outside matching content.
461
- */
462
- function matchChatElement(element, root) {
463
- if (!inChat(element, root) || !displayed(root) || element.closest("[hidden]") !== null) return void 0;
464
- const closest = (selector) => {
465
- const found = element.closest(selector);
466
- return found !== null && inChat(found, root) && displayed(found) ? found : void 0;
467
- };
468
- const node = closest("[data-chat-node-key]");
469
- const call = closest("[data-chat-call-id]");
470
- const group = closest("[data-chat-group-key]");
471
- const turnElement = closest("[data-chat-turn]");
472
- const box = call ?? node ?? group ?? turnElement;
473
- if (box === void 0) return void 0;
474
- const turnValue = turnElement?.dataset.chatTurn;
475
- const turn = turnValue === void 0 || turnValue === "" ? void 0 : Number(turnValue);
476
- return {
477
- element: box,
478
- target: {
479
- ...node?.dataset.chatNodeKey === void 0 ? {} : { nodeKey: node.dataset.chatNodeKey },
480
- ...node?.dataset.chatGroupPart === void 0 ? {} : { groupPart: node.dataset.chatGroupPart },
481
- ...node?.dataset.chatFlowKind === void 0 ? {} : { nodeKind: node.dataset.chatFlowKind },
482
- ...call?.dataset.chatCallId === void 0 ? {} : { callId: call.dataset.chatCallId },
483
- ...group?.dataset.chatGroupKey === void 0 ? {} : { groupKey: group.dataset.chatGroupKey },
484
- ...turn !== void 0 && Number.isSafeInteger(turn) && turn >= 0 ? { turn } : {}
485
- }
486
- };
487
- }
488
- /**
489
- * Prefer an exact Node part, then its Node, Group, Step, or Turn table row.
490
- * @param target - Picked identities.
491
- * @param rows - Current row identities, including members of folded Inspector groups.
492
- * @returns The closest materialized table row, or undefined when none matches.
493
- */
494
- function matchChatNodeRow(target, rows) {
495
- const entries = [...rows];
496
- if (target.nodeKey !== void 0) {
497
- const nodes = entries.filter(([, row]) => row.nodeKey === target.nodeKey);
498
- const exact = nodes.find(([, row]) => row.groupPart === target.groupPart) ?? nodes[0];
499
- if (exact !== void 0) return exact[0];
500
- }
501
- if (target.groupKey !== void 0) {
502
- const group = entries.find(([, row]) => row.groupKey === target.groupKey && row.nodeKey === void 0);
503
- if (group !== void 0) return group[0];
504
- }
505
- if (target.turn === void 0) return void 0;
506
- const turn = entries.filter(([, row]) => row.turn === target.turn);
507
- return (target.step === void 0 ? turn[0] : turn.find(([, row]) => row.step === target.step) ?? turn[0])?.[0];
508
- }
509
- //#endregion
510
- //#region lib/types/client/views/chat-node/model.js
511
- /** Chat table order follows root references and group membership, independently of row data. */
512
- const EMPTY = [];
513
- const COLUMN_FIELDS = ["key", "kind"];
514
- function nodeRecord(node) {
515
- const location = node.location;
516
- return {
517
- type: node.kind,
518
- identity: node.key,
519
- location: location.kind === "step" ? `${location.turn.turn}/${location.step.step}` : location.kind === "turn" ? String(location.turn.turn) : location.kind,
520
- value: node,
521
- summary: inspectorPreview(node, COLUMN_FIELDS)
522
- };
523
- }
524
- /** Observes structural Chat changes while visible rows observe their own Node or Group. */
525
- var ChatNodeModel = class {
526
- binding;
527
- rows = (0, _unieai_rabi_client_store.createSnapshotStore)(EMPTY);
528
- sources = /* @__PURE__ */ new Map();
529
- groups = /* @__PURE__ */ new Map();
530
- entries;
531
- order;
532
- keys;
533
- anchors;
534
- nodeStore;
535
- grouped;
536
- subscribers = 0;
537
- disconnect;
538
- queued = false;
539
- targets = /* @__PURE__ */ new Map();
540
- objectIndex;
541
- /** @param binding - Existing target-neutral Conversation binding for the inspected Session. */
542
- constructor(binding) {
543
- this.binding = binding;
544
- this.objectIndex = new ChatObjectIndex(binding);
545
- this.refresh();
546
- }
547
- /**
548
- * Bind object references and publication updates to the inspected Session.
549
- * @param sessionId - Session displayed by this model.
550
- * @returns Weak object lookup and row navigation for its details.
551
- */
552
- objects(sessionId) {
553
- const reference = (value) => {
554
- const found = this.objectIndex.reference(value);
555
- if (found === void 0) return void 0;
556
- 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);
557
- return {
558
- ...found,
559
- ...row === void 0 ? {} : { rowKey: row[0] }
560
- };
561
- };
562
- return {
563
- sessionId,
564
- updates: this.binding.snapshot,
565
- reference,
566
- row: (key) => {
567
- const value = this.row(key)?.getSnapshot()?.value;
568
- if (value === null || typeof value !== "object") return void 0;
569
- const found = reference(value);
570
- const target = this.targets.get(key);
571
- return found === void 0 || target === void 0 ? void 0 : {
572
- ...found,
573
- rowKey: key,
574
- target
575
- };
576
- }
577
- };
578
- }
579
- /** @returns Stable flattened group/node order. */
580
- getSnapshot = () => this.rows.getSnapshot();
581
- /**
582
- * Match a picked Chat object against the current table, including folded children.
583
- * @param target - Picked Chat identities.
584
- * @returns Closest current Node or Group row, or undefined without a match.
585
- */
586
- pick(target) {
587
- this.refresh(true);
588
- return matchChatNodeRow(target, this.targets);
589
- }
590
- /** @param listener - Structural invalidation callback. @returns Its disposer. */
591
- subscribe = (listener) => {
592
- const stop = this.rows.subscribe(listener);
593
- if (this.subscribers++ === 0) {
594
- this.disconnect = this.binding.snapshot.subscribe(() => {
595
- this.refresh();
596
- });
597
- this.binding.activate("chat");
598
- this.refresh(true);
599
- }
600
- return () => {
601
- stop();
602
- if (--this.subscribers === 0) {
603
- this.disconnect?.();
604
- this.disconnect = void 0;
605
- for (const stop of this.groups.values()) stop();
606
- this.groups.clear();
607
- }
608
- };
609
- };
610
- /**
611
- * Read a loaded row without adding a subscription.
612
- * @param key - Stable table position.
613
- * @returns Cached Node or Group metadata source, or undefined outside the loaded rows.
614
- */
615
- row = (key) => this.sources.get(key);
616
- refresh(force = false) {
617
- const snapshot = this.binding.snapshot.getSnapshot();
618
- const chat = snapshot.views.get("chat");
619
- const grouped = snapshot.views.grouped("chat");
620
- const nodes = chat?.nodes.values();
621
- 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]);
622
- if (!force && chat?.order === this.order && chat?.nodes === this.nodeStore && sameKeys && grouped === this.grouped && grouped?.entries === this.entries) return;
623
- this.order = chat?.order;
624
- this.entries = grouped?.entries;
625
- this.keys = nodes?.map((node) => node.key);
626
- this.anchors = nodes?.map((node) => node.anchorSeq);
627
- if (grouped !== this.grouped) {
628
- for (const stop of this.groups.values()) stop();
629
- this.groups.clear();
630
- this.sources.clear();
631
- }
632
- this.grouped = grouped;
633
- if (chat?.nodes !== this.nodeStore) this.sources.clear();
634
- this.nodeStore = chat?.nodes;
635
- const activeGroups = /* @__PURE__ */ new Set();
636
- this.targets.clear();
637
- const rows = [];
638
- const addNode = (entry, parent) => {
639
- const key = `node:${entry.key}:${entry.groupPart ?? ""}`;
640
- const location = chat?.nodes.get(entry.key)?.location;
641
- const turn = location?.kind === "turn" || location?.kind === "step" ? location.turn.turn : void 0;
642
- const step = location?.kind === "step" ? location.step.step : void 0;
643
- this.targets.set(key, {
644
- nodeKey: entry.key,
645
- ...entry.groupPart === void 0 ? {} : { groupPart: entry.groupPart },
646
- ...turn === void 0 ? {} : { turn },
647
- ...step === void 0 ? {} : { step }
648
- });
649
- rows.push({
650
- key,
651
- depth: parent === void 0 ? 0 : 1,
652
- ...parent === void 0 ? {} : { parent }
653
- });
654
- if (!this.sources.has(key) && chat !== void 0) this.sources.set(key, new InspectorRecordSource(chat.nodes.source(entry.key), (node) => {
655
- const record = nodeRecord(node);
656
- return entry.groupPart === void 0 ? record : {
657
- ...record,
658
- identity: `${node.key}#${entry.groupPart}`
659
- };
660
- }));
661
- };
662
- const entries = grouped?.entries ?? chat?.order.map((key) => ({
663
- kind: "node",
664
- key
665
- })) ?? [];
666
- const included = /* @__PURE__ */ new Set();
667
- const entryAnchors = entries.map((entry) => {
668
- const members = entry.kind === "node" ? [entry] : grouped.groupSource(entry.key).getSnapshot()?.members ?? [];
669
- let anchor;
670
- for (const member of members) {
671
- included.add(member.key);
672
- const seq = chat?.nodes.get(member.key)?.anchorSeq;
673
- if (seq !== void 0) anchor = anchor === void 0 ? seq : Math.min(anchor, seq);
674
- }
675
- return anchor;
676
- });
677
- const unlisted = (nodes ?? []).filter((node) => !included.has(node.key)).sort((left, right) => left.anchorSeq - right.anchorSeq || left.key.localeCompare(right.key));
678
- let nextUnlisted = 0;
679
- const addUnlistedBefore = (anchor) => {
680
- let node = unlisted[nextUnlisted];
681
- while (node !== void 0 && node.anchorSeq <= anchor) {
682
- addNode({ key: node.key });
683
- node = unlisted[++nextUnlisted];
684
- }
685
- };
686
- for (const [index, entry] of entries.entries()) {
687
- const anchor = entryAnchors[index];
688
- if (anchor !== void 0) addUnlistedBefore(anchor);
689
- if (entry.kind === "node") {
690
- addNode(entry);
691
- continue;
692
- }
693
- activeGroups.add(entry.key);
694
- const key = `group:${entry.key}`;
695
- this.targets.set(key, { groupKey: entry.key });
696
- const source = grouped.groupSource(entry.key);
697
- const group = source.getSnapshot();
698
- rows.push({
699
- key,
700
- depth: 0
701
- });
702
- if (!this.sources.has(key)) this.sources.set(key, new InspectorRecordSource(source, (value) => ({
703
- type: "group",
704
- identity: value.key,
705
- location: "",
706
- value,
707
- summary: inspectorPreview(value, COLUMN_FIELDS)
708
- })));
709
- for (const member of group?.members ?? []) addNode(member, key);
710
- if (this.subscribers > 0 && !this.groups.has(entry.key)) {
711
- let members = group?.members;
712
- const stop = source.subscribe(() => {
713
- const next = source.getSnapshot()?.members;
714
- if (next === members) return;
715
- members = next;
716
- this.schedule();
717
- });
718
- this.groups.set(entry.key, stop);
719
- }
720
- }
721
- addUnlistedBefore(Infinity);
722
- for (const [key, stop] of this.groups) if (!activeGroups.has(key)) {
723
- stop();
724
- this.groups.delete(key);
725
- }
726
- const rowKeys = new Set(rows.map((row) => row.key));
727
- for (const key of this.sources.keys()) if (!rowKeys.has(key)) this.sources.delete(key);
728
- this.rows.set(rows);
729
- }
730
- schedule() {
731
- if (this.queued) return;
732
- this.queued = true;
733
- queueMicrotask(() => {
734
- this.queued = false;
735
- if (this.subscribers > 0) this.refresh(true);
736
- });
737
- }
738
- };
739
- //#endregion
740
- //#region ../../util/values/src/partial-json.ts
741
- /**
742
- * Lazily scanned view of one JSON object's top-level fields, built from text
743
- * that may still be streaming or from an already parsed object. Nothing is
744
- * scanned until a reader asks; the view remembers every question it answered
745
- * and reports changed answers when the owner refreshes for publication.
746
- * Used for model tool-call arguments: a row reads the fields it
747
- * cares about at whatever granularity it displays, at every stage of the call.
748
- * @module @unieai/rabi-util-values/src/partial-json
749
- */
750
- const SIMPLE_ESCAPES = {
751
- "\"": "\"",
752
- "\\": "\\",
753
- "/": "/",
754
- b: "\b",
755
- f: "\f",
756
- n: "\n",
757
- r: "\r",
758
- t: " "
759
- };
760
- const CONTENT_ESCAPE = /[\\\u0000-\u001f]/u;
761
- function isWhitespace(c) {
762
- return c === " " || c === "\n" || c === "\r" || c === " ";
763
- }
764
- function isHex(c) {
765
- return c >= "0" && c <= "9" || c >= "a" && c <= "f" || c >= "A" && c <= "F";
766
- }
767
- (class PartialArguments {
768
- /** The view of a call with no arguments available. */
769
- static EMPTY = PartialArguments.fromObject({});
770
- /**
771
- * View finished argument text without scanning it until a reader asks.
772
- * @param text - the complete argument JSON text.
773
- * @returns a sealed view.
774
- */
775
- static fromText(text) {
776
- const view = new PartialArguments();
777
- view.append(text);
778
- view.sealed = true;
779
- return view;
780
- }
781
- /**
782
- * View an already parsed argument payload, such as a PTC dispatch object.
783
- * @param value - the parsed argument value.
784
- * @returns a sealed view; a non-object payload has no fields.
785
- */
786
- static fromObject(value) {
787
- const view = new PartialArguments();
788
- view.object = typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
789
- view.sealed = true;
790
- return view;
791
- }
792
- /**
793
- * The source: text so far or a parsed object, plus whether it can still grow.
794
- * These are the only enumerable fields, so two views over the same source
795
- * compare equal structurally however far each has been read.
796
- */
797
- chunks = [];
798
- object;
799
- sealed = false;
800
- #ends = [];
801
- #size = 0;
802
- #consumed = 0;
803
- #mode = "root";
804
- #escape = false;
805
- #keyStart = 0;
806
- #keyEscaped = false;
807
- #key = "";
808
- #current = null;
809
- #nestedEnds = [];
810
- #nestedInString = false;
811
- #invalidAt;
812
- #invalidValue = false;
813
- #entries = /* @__PURE__ */ new Map();
814
- #order = [];
815
- #reads = /* @__PURE__ */ new Map();
816
- /** Whether this view rejects further appends; does not scan text or register reads. */
817
- get isSealed() {
818
- return this.sealed;
819
- }
820
- /** Whether indexing or a content read found invalid JSON; unread value contents are not validated. */
821
- get invalid() {
822
- this.scan();
823
- return this.#mode === "invalid" || this.#invalidValue;
824
- }
825
- /**
826
- * Retain streamed argument text without scanning or comparing observed answers.
827
- * @param fragment - the text following every fragment appended before.
828
- */
829
- append(fragment) {
830
- if (this.sealed) throw new Error("PartialArguments: cannot append to a sealed view");
831
- if (fragment.length === 0) return;
832
- this.chunks.push(fragment);
833
- this.#size += fragment.length;
834
- this.#ends.push(this.#size);
835
- }
836
- /**
837
- * Reconcile a streamed prefix with authoritative complete text without joining the fragments.
838
- * @param text - the final argument text, which replaces missing or conflicting deltas.
839
- * @returns this view sealed with its caches retained when every character matches; otherwise a new sealed view.
840
- */
841
- settle(text) {
842
- if (this.object !== void 0 || text.length !== this.#size) return PartialArguments.fromText(text);
843
- let offset = 0;
844
- for (const chunk of this.chunks) {
845
- if (!text.startsWith(chunk, offset)) return PartialArguments.fromText(text);
846
- offset += chunk.length;
847
- }
848
- this.chunks = text.length === 0 ? [] : [text];
849
- this.#ends = text.length === 0 ? [] : [text.length];
850
- this.sealed = true;
851
- return this;
852
- }
853
- /**
854
- * Compare observed answers and advance their publication baseline. Unread views remain unscanned.
855
- * @returns whether any observed answer changed since its first read or the preceding refresh.
856
- */
857
- refresh() {
858
- if (this.#reads.size === 0) return false;
859
- this.scan();
860
- let changed = false;
861
- let completions = false;
862
- for (const read of this.#reads.values()) {
863
- if (read.completion) {
864
- completions = true;
865
- continue;
866
- }
867
- changed = this.refreshRead(read) || changed;
868
- }
869
- if (completions) {
870
- for (const read of this.#reads.values()) if (read.completion) changed = this.refreshRead(read) || changed;
871
- }
872
- if (this.sealed) this.#reads.clear();
873
- return changed;
874
- }
875
- refreshRead(read) {
876
- const now = read.answer();
877
- if (Object.is(now, read.last)) return false;
878
- read.last = now;
879
- return true;
880
- }
881
- /**
882
- * Check whether no further fields can arrive.
883
- * @returns whether the outer object closed, indexing failed, or the view is sealed; unread values are not validated.
884
- */
885
- closed() {
886
- return this.remember("closed", "", () => this.closedNow());
887
- }
888
- /**
889
- * List discovered fields in first-appearance order.
890
- * @returns top-level keys seen so far, in first-appearance order.
891
- */
892
- keys() {
893
- return this.remember("keys", "", () => this.keysNow(), (keys) => keys.length);
894
- }
895
- /**
896
- * Check whether a top-level field has appeared.
897
- * @param key - argument name.
898
- * @returns whether the field has appeared (a string opened or another value began).
899
- */
900
- has(key) {
901
- return this.remember("has", key, () => this.hasNow(key));
902
- }
903
- /**
904
- * Check whether a field's closing delimiter has arrived, without validating its contents.
905
- * @param key - argument name.
906
- * @returns whether its delimiter arrived and no content reader has reported an error for this value.
907
- */
908
- complete(key) {
909
- return this.remember("complete", key, () => this.completeNow(key));
910
- }
911
- /**
912
- * Read string length without materializing its text.
913
- * @param key - argument name.
914
- * @param options - change granularity for a streaming string.
915
- * @returns decoded UTF-16 length of the string field so far; undefined when absent or not a string.
916
- */
917
- stringLength(key, options) {
918
- const step = Math.max(1, Math.floor(options?.step ?? 1));
919
- const offset = options?.offset ?? 0;
920
- return this.remember(`length:${step}:${offset}`, key, () => this.lengthNow(key), (length) => length === void 0 ? void 0 : Math.ceil((length + offset) / step));
921
- }
922
- /**
923
- * Check a string against a decoded UTF-16 length limit without materializing it.
924
- * @param key - argument name.
925
- * @param maxLength - decoded UTF-16 limit, floored to at least zero.
926
- * @returns whether the string is longer than the limit; false when absent or not a string.
927
- */
928
- stringExceeds(key, maxLength) {
929
- const limit = Math.max(0, Math.floor(maxLength));
930
- return this.remember(`exceeds:${limit}`, key, () => (this.lengthNow(key, limit + 1) ?? 0) > limit);
931
- }
932
- /**
933
- * Read a decoded string, including a streaming prefix.
934
- * @param key - argument name.
935
- * @returns the string field's decoded text so far; undefined when absent or not a string.
936
- */
937
- text(key) {
938
- return this.remember("text", key, () => this.textNow(key));
939
- }
940
- /**
941
- * Read at most the first decoded UTF-16 units of a string.
942
- * @param key - argument name.
943
- * @param maxLength - maximum decoded UTF-16 length, floored to at least one.
944
- * @returns the bounded string prefix; undefined when absent or not a string.
945
- */
946
- textPrefix(key, maxLength) {
947
- const limit = Math.max(1, Math.floor(maxLength));
948
- return this.remember(`prefix:${limit}`, key, () => this.textPrefixNow(key, limit));
949
- }
950
- /**
951
- * Read a completed non-string argument.
952
- * @param key - argument name.
953
- * @returns the parsed non-string value once it closed; undefined while open, absent, or a string.
954
- */
955
- value(key) {
956
- return this.remember("value", key, () => this.valueNow(key));
957
- }
958
- /** Answer a question and, on a streaming view, remember it for change detection. */
959
- remember(kind, key, read, comparison) {
960
- this.scan();
961
- const result = read();
962
- if (!this.sealed) {
963
- const id = `${kind}/${key}`;
964
- if (!this.#reads.has(id)) this.#reads.set(id, {
965
- completion: kind === "complete",
966
- answer: comparison === void 0 ? read : () => comparison(read()),
967
- last: comparison === void 0 ? result : comparison(result)
968
- });
969
- }
970
- return result;
971
- }
972
- closedNow() {
973
- return this.sealed || this.#mode === "closed" || this.#mode === "invalid";
974
- }
975
- keysNow() {
976
- return this.object === void 0 ? this.#order : Object.keys(this.object);
977
- }
978
- hasNow(key) {
979
- return this.object === void 0 ? this.#entries.has(key) : Object.hasOwn(this.object, key);
980
- }
981
- completeNow(key) {
982
- if (this.object !== void 0) return Object.hasOwn(this.object, key);
983
- const entry = this.#entries.get(key);
984
- return entry !== void 0 && entry.end >= 0 && (entry.kind === "string" ? entry.invalidAt === void 0 : !entry.invalid);
985
- }
986
- lengthNow(key, limit = Number.POSITIVE_INFINITY) {
987
- if (this.object !== void 0) {
988
- const field = Object.hasOwn(this.object, key) ? this.object[key] : void 0;
989
- return typeof field === "string" ? field.length : void 0;
990
- }
991
- const entry = this.#entries.get(key);
992
- if (entry?.kind !== "string") return void 0;
993
- if (entry.text !== void 0 && entry.text.at === entry.end) return entry.text.length;
994
- const read = entry.length ??= {
995
- at: entry.start,
996
- length: 0,
997
- text: ""
998
- };
999
- this.readString(entry, read, limit, false);
1000
- return read.length;
1001
- }
1002
- textNow(key) {
1003
- if (this.object !== void 0) {
1004
- const field = Object.hasOwn(this.object, key) ? this.object[key] : void 0;
1005
- return typeof field === "string" ? field : void 0;
1006
- }
1007
- const entry = this.#entries.get(key);
1008
- if (entry?.kind !== "string") return void 0;
1009
- if (entry.text === void 0 && entry.end >= 0 && entry.needsDecoding && entry.invalidAt === void 0) {
1010
- let text;
1011
- try {
1012
- text = JSON.parse(`"${this.slice(entry.start, entry.end)}"`);
1013
- } catch (_error) {}
1014
- if (text !== void 0) entry.text = {
1015
- at: entry.end,
1016
- length: text.length,
1017
- text
1018
- };
1019
- }
1020
- const read = entry.text ??= {
1021
- at: entry.start,
1022
- length: 0,
1023
- text: ""
1024
- };
1025
- this.readString(entry, read, Number.POSITIVE_INFINITY, true);
1026
- return read.text;
1027
- }
1028
- textPrefixNow(key, maxLength) {
1029
- if (this.object !== void 0) {
1030
- const field = Object.hasOwn(this.object, key) ? this.object[key] : void 0;
1031
- return typeof field === "string" ? field.slice(0, maxLength) : void 0;
1032
- }
1033
- const entry = this.#entries.get(key);
1034
- if (entry?.kind !== "string") return void 0;
1035
- const prefixes = entry.prefixes ??= /* @__PURE__ */ new Map();
1036
- let read = prefixes.get(maxLength);
1037
- if (read === void 0) {
1038
- read = {
1039
- at: entry.start,
1040
- length: 0,
1041
- text: ""
1042
- };
1043
- prefixes.set(maxLength, read);
1044
- }
1045
- this.readString(entry, read, maxLength, true);
1046
- return read.text;
1047
- }
1048
- valueNow(key) {
1049
- if (this.object !== void 0) {
1050
- if (!Object.hasOwn(this.object, key)) return void 0;
1051
- const field = this.object[key];
1052
- return typeof field === "string" ? void 0 : field;
1053
- }
1054
- const entry = this.#entries.get(key);
1055
- if (entry?.kind !== "value" || entry.end < 0 || entry.invalid) return void 0;
1056
- if (entry.parsed === void 0) try {
1057
- entry.parsed = JSON.parse(this.slice(entry.start, entry.end));
1058
- } catch (_error) {
1059
- entry.invalid = true;
1060
- this.#invalidValue = true;
1061
- }
1062
- return entry.parsed;
1063
- }
1064
- chunkAt(at) {
1065
- let low = 0;
1066
- let high = this.#ends.length;
1067
- while (low < high) {
1068
- const mid = low + high >>> 1;
1069
- if (this.#ends[mid] <= at) low = mid + 1;
1070
- else high = mid;
1071
- }
1072
- return low;
1073
- }
1074
- /** Materialize only a requested range, never the cumulative source. */
1075
- slice(start, end) {
1076
- if (start >= end) return "";
1077
- const first = this.chunkAt(start);
1078
- const last = this.chunkAt(end - 1);
1079
- const base = first === 0 ? 0 : this.#ends[first - 1];
1080
- if (first === last) return this.chunks[first].slice(start - base, end - base);
1081
- const parts = [this.chunks[first].slice(start - base)];
1082
- for (let i = first + 1; i < last; i++) parts.push(this.chunks[i]);
1083
- parts.push(this.chunks[last].slice(0, end - this.#ends[last - 1]));
1084
- return parts.join("");
1085
- }
1086
- readString(entry, read, limit, materialize) {
1087
- const end = Math.min(entry.end < 0 ? this.#consumed : entry.end, entry.invalidAt ?? Number.POSITIVE_INFINITY, this.#invalidAt ?? Number.POSITIVE_INFINITY);
1088
- if (!entry.needsDecoding) {
1089
- const length = Math.min(end - read.at, limit - read.length);
1090
- if (length <= 0) return;
1091
- if (materialize) read.text += this.slice(read.at, read.at + length);
1092
- read.at += length;
1093
- read.length += length;
1094
- return;
1095
- }
1096
- let chunkIndex = this.chunkAt(read.at);
1097
- while (read.at < end && read.length < limit) {
1098
- const base = chunkIndex === 0 ? 0 : this.#ends[chunkIndex - 1];
1099
- const chunk = this.chunks[chunkIndex];
1100
- const remaining = chunk.slice(read.at - base, Math.min(chunk.length, end - base));
1101
- const boundary = remaining.search(CONTENT_ESCAPE);
1102
- const length = Math.min(boundary < 0 ? remaining.length : boundary, limit - read.length);
1103
- if (length > 0) {
1104
- if (materialize) read.text += remaining.slice(0, length);
1105
- read.at += length;
1106
- read.length += length;
1107
- if (read.at === base + chunk.length) chunkIndex++;
1108
- continue;
1109
- }
1110
- const type = remaining.length > 1 ? remaining[1] : read.at + 1 < end ? this.chunks[chunkIndex + 1][0] : void 0;
1111
- let decoded;
1112
- let width = 2;
1113
- if (remaining[0] === "\\" && type === void 0 && entry.end < 0) return;
1114
- if (remaining[0] === "\\" && type === "u") {
1115
- const hex = this.slice(read.at + 2, Math.min(end, read.at + 6));
1116
- let valid = true;
1117
- for (let i = 0; i < hex.length; i++) if (!isHex(hex[i])) valid = false;
1118
- if (valid) {
1119
- if (hex.length < 4 && entry.end < 0) return;
1120
- if (hex.length === 4) decoded = String.fromCharCode(Number.parseInt(hex, 16));
1121
- }
1122
- width = 6;
1123
- } else if (remaining[0] === "\\" && type !== void 0) decoded = SIMPLE_ESCAPES[type];
1124
- if (decoded === void 0) {
1125
- entry.invalidAt = read.at;
1126
- this.#invalidValue = true;
1127
- return;
1128
- }
1129
- if (materialize) read.text += decoded;
1130
- read.length++;
1131
- read.at += width;
1132
- while (chunkIndex < this.chunks.length && read.at >= this.#ends[chunkIndex]) chunkIndex++;
1133
- }
1134
- }
1135
- /** Locate new field ranges without decoding or parsing their contents. */
1136
- scan() {
1137
- if (this.object !== void 0 || this.#consumed === this.#size) return;
1138
- for (let i = this.chunkAt(this.#consumed); i < this.chunks.length && this.#invalidAt === void 0; i++) {
1139
- const pending = this.chunks[i];
1140
- const base = i === 0 ? 0 : this.#ends[i - 1];
1141
- for (let index = this.#consumed - base; index < pending.length && this.#mode !== "invalid"; index++) {
1142
- if (this.#mode === "string" || this.#mode === "nested" && this.#nestedInString) {
1143
- const end = this.stringBoundary(pending, index);
1144
- this.#consumed += end - index;
1145
- index = end;
1146
- if (index === pending.length) break;
1147
- }
1148
- this.step(pending[index], this.#consumed);
1149
- this.#consumed++;
1150
- }
1151
- }
1152
- }
1153
- /** Only raw quotes and their preceding backslash runs can terminate a string. */
1154
- stringBoundary(fragment, start) {
1155
- let at = start;
1156
- while (true) {
1157
- const quote = fragment.indexOf("\"", at);
1158
- const end = quote < 0 ? fragment.length : quote;
1159
- if (this.#mode === "string") {
1160
- const entry = this.#current;
1161
- if (!entry.needsDecoding && CONTENT_ESCAPE.test(fragment.slice(at, end))) entry.needsDecoding = true;
1162
- }
1163
- let slashStart = end;
1164
- while (slashStart > at && fragment[slashStart - 1] === "\\") slashStart--;
1165
- const escaped = (end - slashStart) % 2 === 1 !== (slashStart === at && this.#escape);
1166
- this.#escape = quote < 0 && escaped;
1167
- if (quote < 0 || !escaped) return end;
1168
- at = quote + 1;
1169
- }
1170
- }
1171
- step(c, at) {
1172
- switch (this.#mode) {
1173
- case "root":
1174
- if (isWhitespace(c)) return;
1175
- if (c === "{") {
1176
- this.#mode = "key-or-end";
1177
- return;
1178
- }
1179
- this.fail();
1180
- return;
1181
- case "key-or-end":
1182
- if (isWhitespace(c)) return;
1183
- if (c === "}") {
1184
- this.#mode = "closed";
1185
- return;
1186
- }
1187
- if (c === "\"") {
1188
- this.beginKey(at);
1189
- return;
1190
- }
1191
- this.fail();
1192
- return;
1193
- case "key-only":
1194
- if (isWhitespace(c)) return;
1195
- if (c === "\"") {
1196
- this.beginKey(at);
1197
- return;
1198
- }
1199
- this.fail();
1200
- return;
1201
- case "key":
1202
- this.stepKey(c, at);
1203
- return;
1204
- case "colon":
1205
- if (isWhitespace(c)) return;
1206
- if (c === ":") {
1207
- this.#mode = "value";
1208
- return;
1209
- }
1210
- this.fail();
1211
- return;
1212
- case "value":
1213
- this.beginValue(c, at);
1214
- return;
1215
- case "string": {
1216
- const entry = this.#current;
1217
- entry.end = at;
1218
- this.#current = null;
1219
- this.#mode = "comma-or-end";
1220
- return;
1221
- }
1222
- case "scalar":
1223
- this.stepScalar(c, at);
1224
- return;
1225
- case "nested":
1226
- this.stepNested(c, at);
1227
- return;
1228
- case "comma-or-end":
1229
- if (isWhitespace(c)) return;
1230
- if (c === ",") {
1231
- this.#mode = "key-only";
1232
- return;
1233
- }
1234
- if (c === "}") {
1235
- this.#mode = "closed";
1236
- return;
1237
- }
1238
- this.fail();
1239
- return;
1240
- case "closed":
1241
- if (isWhitespace(c)) return;
1242
- this.fail();
1243
- return;
1244
- /* v8 ignore next 2 -- scan() stops stepping once the view is invalid. */
1245
- case "invalid": return;
1246
- /* v8 ignore next 2 -- Every scanner mode has a handler above. */
1247
- default: assertNever(this.#mode);
1248
- }
1249
- }
1250
- fail() {
1251
- this.#invalidAt = this.#consumed;
1252
- this.#mode = "invalid";
1253
- this.#current = null;
1254
- }
1255
- beginKey(at) {
1256
- this.#mode = "key";
1257
- this.#keyStart = at + 1;
1258
- this.#keyEscaped = false;
1259
- this.#escape = false;
1260
- }
1261
- stepKey(c, at) {
1262
- if (c < " ") {
1263
- this.fail();
1264
- return;
1265
- }
1266
- if (this.#escape) {
1267
- this.#escape = false;
1268
- return;
1269
- }
1270
- if (c === "\\") {
1271
- this.#escape = true;
1272
- this.#keyEscaped = true;
1273
- return;
1274
- }
1275
- if (c !== "\"") return;
1276
- const raw = this.slice(this.#keyStart, at);
1277
- if (this.#keyEscaped) try {
1278
- this.#key = JSON.parse(`"${raw}"`);
1279
- } catch (_error) {
1280
- this.fail();
1281
- return;
1282
- }
1283
- else this.#key = raw;
1284
- this.#mode = "colon";
1285
- }
1286
- open(entry) {
1287
- if (!this.#entries.has(this.#key)) this.#order.push(this.#key);
1288
- this.#entries.set(this.#key, entry);
1289
- this.#current = entry;
1290
- }
1291
- beginValue(c, at) {
1292
- if (isWhitespace(c)) return;
1293
- if (c === "\"") {
1294
- this.open({
1295
- kind: "string",
1296
- start: at + 1,
1297
- end: -1,
1298
- needsDecoding: false,
1299
- invalidAt: void 0,
1300
- length: void 0,
1301
- text: void 0,
1302
- prefixes: void 0
1303
- });
1304
- this.#escape = false;
1305
- this.#mode = "string";
1306
- return;
1307
- }
1308
- if (c === "}" || c === "," || c === ":" || c === "]") {
1309
- this.fail();
1310
- return;
1311
- }
1312
- this.open({
1313
- kind: "value",
1314
- start: at,
1315
- end: -1,
1316
- parsed: void 0,
1317
- invalid: false
1318
- });
1319
- if (c === "{" || c === "[") {
1320
- this.#mode = "nested";
1321
- this.#nestedEnds = [c === "{" ? "}" : "]"];
1322
- this.#nestedInString = false;
1323
- this.#escape = false;
1324
- return;
1325
- }
1326
- this.#mode = "scalar";
1327
- }
1328
- stepScalar(c, at) {
1329
- if (c !== "," && c !== "}" && !isWhitespace(c)) return;
1330
- this.closeValue(at);
1331
- this.#mode = c === "," ? "key-only" : c === "}" ? "closed" : "comma-or-end";
1332
- }
1333
- stepNested(c, at) {
1334
- if (this.#nestedInString) {
1335
- this.#nestedInString = false;
1336
- return;
1337
- }
1338
- if (c === "\"") {
1339
- this.#nestedInString = true;
1340
- return;
1341
- }
1342
- if (c === "{" || c === "[") {
1343
- this.#nestedEnds.push(c === "{" ? "}" : "]");
1344
- return;
1345
- }
1346
- if (c === "}" || c === "]") {
1347
- if (this.#nestedEnds.pop() !== c) {
1348
- this.fail();
1349
- return;
1350
- }
1351
- if (this.#nestedEnds.length === 0) {
1352
- this.closeValue(at + 1);
1353
- this.#mode = "comma-or-end";
1354
- }
1355
- }
1356
- }
1357
- closeValue(end) {
1358
- const entry = this.#current;
1359
- entry.end = end;
1360
- this.#current = null;
1361
- }
1362
- });
1363
- //#endregion
1364
- //#region ../../util/values/src/index.ts
1365
- /**
1366
- * Mark an unreachable closed-union branch.
1367
- * @param value - impossible value; an unhandled typed variant fails at the call site.
1368
- * @param context - optional switch-site label included in the failure message.
1369
- * @returns never; a runtime value that escaped its type always throws.
1370
- */
1371
- function assertNever(value, context) {
1372
- const rendered = JSON.stringify(value) ?? String(value);
1373
- throw new Error(`unreachable variant${context ? ` in ${context}` : ""}: ${rendered}`);
1374
- }
1375
- /** Whether a realm-owned intrinsic prototype has a native constructor matching this engine's representation. */
1376
- function hasIntrinsicConstructor(prototype, name) {
1377
- const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
1378
- if (typeof constructor !== "function") return false;
1379
- try {
1380
- return constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === Function.prototype.toString.call(name === "Array" ? Array : Object);
1381
- } catch {
1382
- return false;
1383
- }
1384
- }
1385
- /** Whether a candidate is one realm's intrinsic `Object.prototype`. */
1386
- function isIntrinsicObjectPrototype(value) {
1387
- return Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, "Object");
1388
- }
1389
- /** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */
1390
- function hasPlainArrayPrototype(value) {
1391
- const prototype = Object.getPrototypeOf(value);
1392
- if (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, "Array")) return false;
1393
- const objectPrototype = Object.getPrototypeOf(prototype);
1394
- return typeof objectPrototype === "object" && objectPrototype !== null && isIntrinsicObjectPrototype(objectPrototype);
1395
- }
1396
- /** Whether an object is a plain or null-prototype record from any JavaScript realm. */
1397
- function hasPlainObjectPrototype(value) {
1398
- const prototype = Object.getPrototypeOf(value);
1399
- return prototype === null || typeof prototype === "object" && isIntrinsicObjectPrototype(prototype);
1400
- }
1401
- /** Return every JSON-visible object key, or reject own data JSON would discard. */
1402
- function enumerableStringKeys(value) {
1403
- const keys = Reflect.ownKeys(value);
1404
- if (keys.some((key) => typeof key !== "string" || !Object.prototype.propertyIsEnumerable.call(value, key))) return void 0;
1405
- return keys;
1406
- }
1407
- /** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */
1408
- function walkJsonValue(value, detach) {
1409
- const ancestors = /* @__PURE__ */ new Set();
1410
- let root;
1411
- const assign = (destination, item) => {
1412
- if (destination === void 0) return;
1413
- if (destination.kind === "root") root = item;
1414
- else if (destination.kind === "array") destination.target[destination.index] = item;
1415
- else Object.defineProperty(destination.target, destination.key, {
1416
- value: item,
1417
- enumerable: true,
1418
- configurable: true,
1419
- writable: true
1420
- });
1421
- };
1422
- const tasks = [{
1423
- kind: "visit",
1424
- value,
1425
- ...detach ? { destination: { kind: "root" } } : {}
1426
- }];
1427
- for (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {
1428
- if (task.kind === "leave") {
1429
- ancestors.delete(task.source);
1430
- continue;
1431
- }
1432
- if (task.kind === "array-item") {
1433
- if (!Object.prototype.hasOwnProperty.call(task.source, task.index)) return void 0;
1434
- tasks.push({
1435
- kind: "visit",
1436
- value: task.source[task.index],
1437
- ...task.target === void 0 ? {} : { destination: {
1438
- kind: "array",
1439
- target: task.target,
1440
- index: task.index
1441
- } }
1442
- });
1443
- continue;
1444
- }
1445
- if (task.kind === "object-property") {
1446
- tasks.push({
1447
- kind: "visit",
1448
- value: task.source[task.key],
1449
- ...task.target === void 0 ? {} : { destination: {
1450
- kind: "object",
1451
- target: task.target,
1452
- key: task.key
1453
- } }
1454
- });
1455
- continue;
1456
- }
1457
- const current = task.value;
1458
- if (current === null) {
1459
- assign(task.destination, null);
1460
- continue;
1461
- }
1462
- if (typeof current === "boolean" || typeof current === "string") {
1463
- assign(task.destination, current);
1464
- continue;
1465
- }
1466
- if (typeof current === "number") {
1467
- if (!Number.isFinite(current) || Object.is(current, -0)) return void 0;
1468
- assign(task.destination, current);
1469
- continue;
1470
- }
1471
- if (typeof current !== "object") return void 0;
1472
- if (ancestors.has(current)) return void 0;
1473
- if (Array.isArray(current)) {
1474
- if (!hasPlainArrayPrototype(current)) return void 0;
1475
- const length = current.length;
1476
- if (Reflect.ownKeys(current).length !== length + 1) return void 0;
1477
- const target = detach ? [] : void 0;
1478
- if (target !== void 0) assign(task.destination, target);
1479
- ancestors.add(current);
1480
- tasks.push({
1481
- kind: "leave",
1482
- source: current
1483
- });
1484
- for (let index = length - 1; index >= 0; index--) tasks.push({
1485
- kind: "array-item",
1486
- source: current,
1487
- index,
1488
- ...target === void 0 ? {} : { target }
1489
- });
1490
- continue;
1491
- }
1492
- if (!hasPlainObjectPrototype(current)) return void 0;
1493
- const keys = enumerableStringKeys(current);
1494
- if (keys === void 0) return void 0;
1495
- const target = detach ? {} : void 0;
1496
- if (target !== void 0) assign(task.destination, target);
1497
- ancestors.add(current);
1498
- tasks.push({
1499
- kind: "leave",
1500
- source: current
1501
- });
1502
- for (let index = keys.length - 1; index >= 0; index--) {
1503
- const key = keys[index];
1504
- /* v8 ignore next -- the loop is bounded by the captured key count. */
1505
- if (key === void 0) return void 0;
1506
- tasks.push({
1507
- kind: "object-property",
1508
- source: current,
1509
- key,
1510
- ...target === void 0 ? {} : { target }
1511
- });
1512
- }
1513
- }
1514
- return detach ? root : true;
1515
- }
1516
- /**
1517
- * Validate and detach lossless JSON in one read per property.
1518
- * @param value - candidate value to validate and detach.
1519
- * @returns the detached snapshot, or `undefined` when the value is not losslessly JSON-serializable.
1520
- */
1521
- function snapshotJsonValue(value) {
1522
- return walkJsonValue(value, true);
1523
- }
1524
- /**
1525
- * Deep-freeze an object graph in place while leaving live AbortSignal objects mutable.
1526
- * @param value - value to freeze.
1527
- * @returns the same value after every reachable enumerable child is frozen.
1528
- */
1529
- function deepFreeze(value) {
1530
- const seen = /* @__PURE__ */ new WeakSet();
1531
- const pending = [{
1532
- kind: "visit",
1533
- node: value
1534
- }];
1535
- while (pending.length > 0) {
1536
- const task = pending.pop();
1537
- /* v8 ignore next -- the loop condition guarantees one pending task. */
1538
- if (task === void 0) continue;
1539
- if (task.kind === "property") {
1540
- pending.push({
1541
- kind: "visit",
1542
- node: task.source[task.key]
1543
- });
1544
- continue;
1545
- }
1546
- const node = task.node;
1547
- if (node === null || typeof node !== "object") continue;
1548
- if (node instanceof AbortSignal) continue;
1549
- if (seen.has(node)) continue;
1550
- seen.add(node);
1551
- Object.freeze(node);
1552
- const keys = Object.keys(node);
1553
- for (let index = keys.length - 1; index >= 0; index--) {
1554
- const key = keys[index];
1555
- /* v8 ignore next -- the loop is bounded by the captured key count. */
1556
- if (key === void 0) continue;
1557
- pending.push({
1558
- kind: "property",
1559
- source: node,
1560
- key
1561
- });
1562
- }
1563
- }
1564
- return value;
1565
- }
1566
- //#endregion
1567
- //#region ../../llm/llm/src/assistant-stream.ts
1568
- /**
1569
- * Lossless compact representation of one model-stream attempt, plus record-level
1570
- * readers that answer common consumer questions without materializing members.
1571
- * Readers trust the static record type; expandAssistantStream is the validating
1572
- * path for records read at a durable boundary.
1573
- */
1574
- function safeTime(value) {
1575
- if (!Number.isSafeInteger(value)) throw new TypeError(`Assistant stream time must be a safe integer, got ${String(value)}`);
1576
- return value;
1577
- }
1578
- function safeIndex(value, label) {
1579
- if (!Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) throw new TypeError(`${label} index must be a non-negative safe integer`);
1580
- return value;
1581
- }
1582
- function snapshotChunk(chunk) {
1583
- const snapshot = snapshotJsonValue(chunk);
1584
- if (snapshot === void 0) throw new TypeError("Assistant stream chunk must be losslessly JSON-serializable");
1585
- return snapshot;
1586
- }
1587
- /**
1588
- * Expand compact records into the exact timed chunk sequence.
1589
- * @param stream - compact records from one durable Assistant settlement.
1590
- * @returns detached timed chunks with every original delta boundary preserved.
1591
- * @throws {TypeError} when a record or reconstructed timestamp is invalid.
1592
- */
1593
- function expandAssistantStream(stream) {
1594
- const chunks = [];
1595
- for (const candidate of stream) {
1596
- const record = validateRecord(candidate);
1597
- if (record.type === "chunk") {
1598
- chunks.push({
1599
- time: record.time,
1600
- chunk: record.chunk
1601
- });
1602
- continue;
1603
- }
1604
- const members = record.type === "tool-call-chunks" ? record.args : record.texts;
1605
- let time = record.time0;
1606
- for (let index = 0; index < members.length; index += 1) {
1607
- if (index > 0) time += record.dt[index - 1];
1608
- let chunk;
1609
- if (record.type === "text-chunks") chunk = {
1610
- type: "text-delta",
1611
- index: record.index,
1612
- text: members[index]
1613
- };
1614
- else if (record.type === "reasoning-chunks") chunk = {
1615
- type: "reasoning-delta",
1616
- index: record.index,
1617
- text: members[index]
1618
- };
1619
- else chunk = {
1620
- type: "tool-call-delta",
1621
- index: record.index,
1622
- id: record.id,
1623
- ...Object.hasOwn(record, "name") ? { name: record.name } : {},
1624
- argumentsDelta: members[index]
1625
- };
1626
- chunks.push({
1627
- time,
1628
- chunk
1629
- });
1630
- }
1631
- }
1632
- return chunks;
1633
- }
1634
- function validateRecord(value) {
1635
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("Assistant stream record must be an object");
1636
- const record = value;
1637
- switch (record.type) {
1638
- case "text-chunks":
1639
- case "reasoning-chunks": {
1640
- exactKeys(record, [
1641
- "type",
1642
- "time0",
1643
- "index",
1644
- "dt",
1645
- "texts"
1646
- ], record.type);
1647
- const texts = stringArray(record.texts, `${record.type} texts`);
1648
- if (texts.length === 0) throw new TypeError(`${record.type} texts must be non-empty`);
1649
- validateRun(record, texts.length, record.type);
1650
- return record;
1651
- }
1652
- case "tool-call-chunks": {
1653
- exactKeys(record, Object.hasOwn(record, "name") ? [
1654
- "type",
1655
- "time0",
1656
- "index",
1657
- "dt",
1658
- "id",
1659
- "name",
1660
- "args"
1661
- ] : [
1662
- "type",
1663
- "time0",
1664
- "index",
1665
- "dt",
1666
- "id",
1667
- "args"
1668
- ], record.type);
1669
- const args = stringArray(record.args, "tool-call-chunks args");
1670
- if (args.length === 0) throw new TypeError("tool-call-chunks args must be non-empty");
1671
- if (typeof record.id !== "string" || record.id.length === 0) throw new TypeError("tool-call-chunks id must be a non-empty string");
1672
- 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");
1673
- validateRun(record, args.length, record.type);
1674
- return record;
1675
- }
1676
- case "chunk": {
1677
- exactKeys(record, [
1678
- "type",
1679
- "time",
1680
- "chunk"
1681
- ], "chunk");
1682
- const time = safeTime(record.time);
1683
- 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");
1684
- let chunk;
1685
- try {
1686
- chunk = snapshotChunk(record.chunk);
1687
- } catch (error) {
1688
- throw new TypeError("Assistant stream raw chunk must be a lossless JSON object", { cause: error });
1689
- }
1690
- return deepFreeze({
1691
- type: "chunk",
1692
- time,
1693
- chunk
1694
- });
1695
- }
1696
- default: throw new TypeError(`Unsupported Assistant stream record ${JSON.stringify(record.type)}`);
1697
- }
1698
- }
1699
- function validateRun(record, members, label) {
1700
- safeTime(record.time0);
1701
- safeIndex(record.index, label);
1702
- if (!Array.isArray(record.dt) || record.dt.some((value) => !Number.isSafeInteger(value))) throw new TypeError(`${label} dt must contain safe integers`);
1703
- if (record.dt.length !== members - 1) throw new TypeError(`${label} dt length must be one less than its members`);
1704
- let time = record.time0;
1705
- for (const gap of record.dt) {
1706
- time += gap;
1707
- if (!Number.isSafeInteger(time)) throw new TypeError(`${label} member times must stay safe integers`);
1708
- }
1709
- }
1710
- function stringArray(value, label) {
1711
- if (!Array.isArray(value) || value.some((member) => typeof member !== "string")) throw new TypeError(`${label} must be a string array`);
1712
- return value;
1713
- }
1714
- function exactKeys(record, keys, label) {
1715
- 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(", ")}`);
1716
- }
1717
- //#endregion
1718
- //#region lib/types/client/views/session-log/stream.js
1719
- /** Block-indexed hierarchy for one live or durable Assistant stream. */
1720
- /** Keeps original delta rows under their blocks and a bounded reasoning prefix for folded headers. */
1721
- var AssistantLogStream = class {
1722
- parent;
1723
- blocks = /* @__PURE__ */ new Map();
1724
- count = 0;
1725
- /** @param parent - Stable Assistant event or live-attempt row identity. */
1726
- constructor(parent) {
1727
- this.parent = parent;
1728
- }
1729
- /**
1730
- * Count all received chunks, including children of folded blocks.
1731
- * @returns Number of original chunks received by this stream.
1732
- */
1733
- get length() {
1734
- return this.count;
1735
- }
1736
- /**
1737
- * Add one original chunk and update the matching block's disclosure state.
1738
- * Chunks without a loaded block-start remain direct Assistant children.
1739
- * @param chunk - Original chunk, correlated by block index.
1740
- * @returns One row insertion, an optional replaced block header, and its folded preview.
1741
- */
1742
- append(chunk) {
1743
- const index = this.count++;
1744
- const key = `${this.parent}/chunk:${index}`;
1745
- let position = index;
1746
- let row = {
1747
- key,
1748
- parent: this.parent,
1749
- depth: 1
1750
- };
1751
- let header;
1752
- let block;
1753
- if (chunk.type === "block-start") {
1754
- block = {
1755
- row: {
1756
- ...row,
1757
- disclosure: "open"
1758
- },
1759
- offset: index,
1760
- children: 0,
1761
- ...chunk.blockType === "reasoning" ? { reasoningText: "" } : {}
1762
- };
1763
- row = block.row;
1764
- this.blocks.set(chunk.index, block);
1765
- } else {
1766
- block = "index" in chunk ? this.blocks.get(chunk.index) : void 0;
1767
- if (block !== void 0) {
1768
- position = block.offset + 1 + block.children++;
1769
- row = {
1770
- key,
1771
- parent: block.row.key,
1772
- depth: 2
1773
- };
1774
- for (const following of this.blocks.values()) if (following.offset > block.offset) following.offset++;
1775
- if (chunk.type === "reasoning-delta" && block.reasoningText !== void 0) block.reasoningText = (block.reasoningText + chunk.text).slice(0, 240);
1776
- if (chunk.type === "block-end") {
1777
- block.row = {
1778
- ...block.row,
1779
- disclosure: "closed"
1780
- };
1781
- header = {
1782
- position: block.offset,
1783
- row: block.row
1784
- };
1785
- }
1786
- }
1787
- }
1788
- return {
1789
- key,
1790
- index,
1791
- position,
1792
- row,
1793
- ...header === void 0 ? {} : { header },
1794
- ...block?.reasoningText === void 0 ? {} : { collapsed: {
1795
- key: block.row.key,
1796
- summary: `blockType: reasoning${block.reasoningText === "" ? "" : ` · ${block.reasoningText}`}`.slice(0, 240)
1797
- } }
1798
- };
1799
- }
1800
- };
1801
- //#endregion
1802
- //#region lib/types/client/views/session-log/groups.js
1803
- /** Turn and Step start/end ranges add ancestry without inventing or reordering log records. */
1804
- /** One ordered pass over the loaded log; missing starts do not create synthetic headers. */
1805
- var SessionLogGroups = class {
1806
- turn;
1807
- step;
1808
- /**
1809
- * Place a record inside its open Step or Turn, retaining end records as the final children.
1810
- * Turn and Step headers remain expanded after their end; manual folding stays table-local.
1811
- * @param row - Ungrouped event row.
1812
- * @param event - Original event.
1813
- * @returns The same row identity with range ancestry and depth.
1814
- */
1815
- append(row, event) {
1816
- switch (event.type) {
1817
- case "turn/start":
1818
- this.step = void 0;
1819
- this.turn = {
1820
- ...row,
1821
- disclosure: "open"
1822
- };
1823
- return this.turn;
1824
- case "step/start":
1825
- this.step = {
1826
- ...this.child(row, this.turn),
1827
- disclosure: "open"
1828
- };
1829
- return this.step;
1830
- case "step/end": {
1831
- const result = this.child(row, this.step ?? this.turn);
1832
- this.step = void 0;
1833
- return result;
1834
- }
1835
- case "turn/end": {
1836
- const result = this.child(row, this.turn);
1837
- this.step = void 0;
1838
- this.turn = void 0;
1839
- return result;
1840
- }
1841
- default: return this.child(row, this.step ?? this.turn);
1842
- }
1843
- }
1844
- child(row, parent) {
1845
- return parent === void 0 ? row : {
1846
- ...row,
1847
- parent: parent.key,
1848
- depth: parent.depth + 1
1849
- };
1850
- }
1851
- };
1852
- //#endregion
1853
- //#region lib/types/client/views/session-log/model.js
1854
- /** Incremental raw Session rows with lossless Assistant stream children. */
1855
- /** Session-owned log projection; subscriptions exist only while the table is observed. */
1856
- var SessionLogModel = class {
1857
- source;
1858
- rows = (0, _unieai_rabi_client_store.createSnapshotStore)([]);
1859
- records = /* @__PURE__ */ new Map();
1860
- roots = [];
1861
- attempts = /* @__PURE__ */ new Map();
1862
- groups = new SessionLogGroups();
1863
- /** Preserve live-to-durable row identities only while their rows remain in the loaded window. */
1864
- settledRoots = /* @__PURE__ */ new Map();
1865
- streams = /* @__PURE__ */ new WeakMap();
1866
- revision = -1;
1867
- subscribers = 0;
1868
- disconnect;
1869
- /**
1870
- * @param source - The existing Session window, shared with Chat and Trajectory.
1871
- */
1872
- constructor(source) {
1873
- this.source = source;
1874
- this.accept(source.getSnapshot());
1875
- }
1876
- /** @returns Stable table order; row contents have independent sources. */
1877
- getSnapshot = () => this.rows.getSnapshot();
1878
- /**
1879
- * Recover an event's placement without interpreting formatted table cells.
1880
- * @param key - Selected root or delta row.
1881
- * @returns The owning event and chunk, or undefined if the row is unavailable.
1882
- */
1883
- chatAnchor(key) {
1884
- this.accept(this.source.getSnapshot());
1885
- const root = this.roots.find((root) => root.row.key === key || root.stream !== void 0 && key.startsWith(`${root.row.key}/chunk:`));
1886
- if (root === void 0) return void 0;
1887
- const record = this.records.get(key)?.getSnapshot();
1888
- if (record === void 0) return void 0;
1889
- return {
1890
- event: root.entry.event,
1891
- ...root.row.key === key ? {} : { chunk: record.value }
1892
- };
1893
- }
1894
- /**
1895
- * Resolve a picked Chat object in the loaded log, without creating synthetic records.
1896
- * @param target - DOM identity enriched with the owning Chat Node's sequence and Turn/Step.
1897
- * @returns Tool call, exact anchor, Assistant, Step, or Turn row; reasoning parts prefer a block-start child.
1898
- */
1899
- pick(target) {
1900
- const window = this.source.getSnapshot();
1901
- this.accept(window);
1902
- const entries = window.entries;
1903
- const sameStep = (entry) => {
1904
- const data = entry.event.data;
1905
- return target.turn !== void 0 && "turn" in data && data.turn === target.turn && (target.step === void 0 || "step" in data && data.step === target.step);
1906
- };
1907
- const call = target.callId === void 0 ? void 0 : entries.find((entry) => entry.event.type === "tool/call" && entry.event.data.callId === target.callId);
1908
- const anchor = target.anchorSeq === void 0 ? void 0 : entries.find((entry) => entry.event.seq === target.anchorSeq);
1909
- 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"));
1910
- const step = target.step === void 0 ? void 0 : entries.find((entry) => entry.event.type === "step/start" && sameStep(entry));
1911
- const turn = target.turn === void 0 ? void 0 : entries.find((entry) => entry.event.type === "turn/start" && entry.event.data.turn === target.turn);
1912
- const entry = call ?? anchor ?? assistant ?? step ?? turn ?? entries.find(sameStep);
1913
- if (entry === void 0) return void 0;
1914
- const key = entry.type === "transient" ? `attempt:${entry.event.data.attemptId}` : this.settledRoots.get(entry.event.seq) ?? `event:${entry.event.seq}`;
1915
- if (target.groupPart === "reasoning") {
1916
- const block = this.rows.getSnapshot().find((row) => {
1917
- if (row.parent !== key) return false;
1918
- const value = this.records.get(row.key)?.getSnapshot()?.value;
1919
- return value !== null && typeof value === "object" && "type" in value && value.type === "block-start" && "blockType" in value && value.blockType === "reasoning";
1920
- });
1921
- if (block !== void 0) return block.key;
1922
- }
1923
- return key;
1924
- }
1925
- /** @param listener - Structural invalidation callback. @returns Subscription disposer. */
1926
- subscribe = (listener) => {
1927
- const stop = this.rows.subscribe(listener);
1928
- if (this.subscribers++ === 0) {
1929
- this.disconnect = this.source.subscribe(() => {
1930
- this.accept(this.source.getSnapshot());
1931
- });
1932
- this.accept(this.source.getSnapshot());
1933
- }
1934
- return () => {
1935
- stop();
1936
- if (--this.subscribers === 0) {
1937
- this.disconnect?.();
1938
- this.disconnect = void 0;
1939
- }
1940
- };
1941
- };
1942
- /**
1943
- * Obtain a cached row source, initially empty when its record is unavailable.
1944
- * @param key - Stable table row identity.
1945
- * @returns Its independently observable raw data.
1946
- */
1947
- row = (key) => {
1948
- let record = this.records.get(key);
1949
- if (record === void 0) {
1950
- record = (0, _unieai_rabi_client_store.createSnapshotStore)(void 0);
1951
- this.records.set(key, record);
1952
- }
1953
- return record;
1954
- };
1955
- put(key, record) {
1956
- this.row(key);
1957
- const source = this.records.get(key);
1958
- if (source.getSnapshot()?.value !== record.value) source.set(record);
1959
- }
1960
- accept(window) {
1961
- if (window.revision === this.revision) return;
1962
- if (window.change.kind === "settle-assistant" && window.change.entry !== void 0) {
1963
- const parent = `attempt:${window.change.attemptId}`;
1964
- if (this.attempts.has(parent)) this.settledRoots.set(window.change.entry.event.seq, parent);
1965
- }
1966
- const append = window.revision === this.revision + 1 && window.change.kind === "append";
1967
- if (!append) {
1968
- this.roots.length = 0;
1969
- this.attempts.clear();
1970
- this.groups = new SessionLogGroups();
1971
- }
1972
- const next = append ? this.rows.getSnapshot().slice() : [];
1973
- const entries = append ? window.change.entries : window.entries;
1974
- for (const entry of entries) this.add(entry, next);
1975
- this.revision = window.revision;
1976
- if (!append) this.prune(next);
1977
- this.rows.set(next);
1978
- }
1979
- prune(rows) {
1980
- const retained = new Set(rows.map((row) => row.key));
1981
- for (const [seq, key] of this.settledRoots) if (!retained.has(key)) this.settledRoots.delete(seq);
1982
- for (const [key, source] of this.records) if (!retained.has(key)) {
1983
- source.set(void 0);
1984
- this.records.delete(key);
1985
- }
1986
- }
1987
- root(key, entry, rows, stream) {
1988
- const row = this.groups.append({
1989
- key,
1990
- depth: 0
1991
- }, entry.event);
1992
- const root = {
1993
- row,
1994
- entry,
1995
- stream,
1996
- ordinal: this.roots.length,
1997
- offset: rows.length
1998
- };
1999
- this.roots.push(root);
2000
- rows.push(row);
2001
- return root;
2002
- }
2003
- add(entry, rows) {
2004
- if (entry.type === "transient") {
2005
- const event = entry.event;
2006
- const { attemptId, turn, step, chunk } = entry.event.data;
2007
- const parent = `attempt:${attemptId}`;
2008
- let attempt = this.attempts.get(parent);
2009
- if (attempt === void 0) {
2010
- attempt = this.root(parent, entry, rows, new AssistantLogStream(parent));
2011
- this.attempts.set(parent, attempt);
2012
- }
2013
- const chunks = this.addChunk(attempt, rows, event.time, chunk, `${turn}/${step}`);
2014
- this.put(parent, {
2015
- type: "assistant/live",
2016
- identity: attemptId,
2017
- location: `${turn}/${step}`,
2018
- time: event.time,
2019
- value: {
2020
- attemptId,
2021
- turn,
2022
- step,
2023
- chunks
2024
- }
2025
- });
2026
- return;
2027
- }
2028
- const event = entry.event;
2029
- const key = this.settledRoots.get(event.seq) ?? `event:${event.seq}`;
2030
- const data = event.data;
2031
- const location = "turn" in data ? `${data.turn}${"step" in data ? `/${data.step}` : ""}` : "";
2032
- this.put(key, {
2033
- type: event.type,
2034
- identity: String(event.seq),
2035
- time: event.time,
2036
- location,
2037
- value: event
2038
- });
2039
- if (entry.event.type === "assistant/message" || entry.event.type === "assistant/attempt") {
2040
- const hierarchy = new AssistantLogStream(key);
2041
- const root = this.root(key, entry, rows, hierarchy);
2042
- const stream = entry.event.data.stream;
2043
- let chunks = this.streams.get(stream);
2044
- if (chunks === void 0) {
2045
- chunks = expandAssistantStream(stream);
2046
- this.streams.set(stream, chunks);
2047
- }
2048
- for (const item of chunks) this.addChunk(root, rows, item.time, item.chunk, location);
2049
- } else this.root(key, entry, rows);
2050
- }
2051
- addChunk(root, rows, time, chunk, location) {
2052
- const stream = root.stream;
2053
- const { key, index, position, row, header, collapsed } = stream.append(chunk);
2054
- rows.splice(root.offset + 1 + position, 0, {
2055
- ...row,
2056
- depth: row.depth + root.row.depth
2057
- });
2058
- if (header !== void 0) rows[root.offset + 1 + header.position] = {
2059
- ...header.row,
2060
- depth: header.row.depth + root.row.depth
2061
- };
2062
- for (let ordinal = root.ordinal + 1; ordinal < this.roots.length; ordinal++) this.roots[ordinal].offset++;
2063
- this.put(key, {
2064
- type: chunk.type,
2065
- identity: String(index),
2066
- time,
2067
- location,
2068
- value: chunk
2069
- });
2070
- if (collapsed !== void 0) {
2071
- const source = this.records.get(collapsed.key);
2072
- const previous = source.getSnapshot();
2073
- if (previous.collapsedSummary !== collapsed.summary) source.set({
2074
- ...previous,
2075
- collapsedSummary: collapsed.summary
2076
- });
2077
- }
2078
- return stream.length;
2079
- }
2080
- };
2081
- //#endregion
2082
- //#region lib/types/client/views/session-log/chat-target.js
2083
- /** Original log coordinates submitted for target-owned Chat reveal. */
2084
- function partOf(chunk) {
2085
- if (chunk?.type === "reasoning-delta") return "reasoning";
2086
- if (chunk?.type === "text-delta") return "response";
2087
- const type = chunk?.type === "block-start" ? chunk.blockType : chunk?.type === "block-end" ? chunk.block.type : void 0;
2088
- return type === "reasoning" ? "reasoning" : type === "text" ? "response" : void 0;
2089
- }
2090
- /**
2091
- * Describe a log record without reading another View's model or DOM.
2092
- * @param anchor - Original log event and optional selected delta.
2093
- * @returns Original event coordinates and any tool-call or Assistant-part identity.
2094
- */
2095
- function sessionLogChatTarget(anchor) {
2096
- const { event, chunk } = anchor;
2097
- const data = event.data;
2098
- const turn = "turn" in data && typeof data.turn === "number" ? data.turn : void 0;
2099
- const step = "step" in data && typeof data.step === "number" ? data.step : void 0;
2100
- 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;
2101
- const rootCallId = "rootCallId" in data && typeof data.rootCallId === "string" ? data.rootCallId : callId;
2102
- const groupPart = partOf(chunk);
2103
- return {
2104
- anchorSeq: event.seq,
2105
- ...event.type === "assistant/message" || event.type === "assistant/attempt" || event.type === "assistant/live-chunk" ? { nodeKind: "assistant-step" } : {},
2106
- ...turn === void 0 ? {} : { turn },
2107
- ...step === void 0 ? {} : { step },
2108
- ...callId === void 0 ? {} : { callId },
2109
- ...rootCallId === void 0 || rootCallId === callId ? {} : { rootCallId },
2110
- ...groupPart === void 0 ? {} : { groupPart }
2111
- };
2112
- }
2113
- //#endregion
2114
- //#region lib/types/client/views/raw-json.js
2115
- /** JSON inspection of live objects, including cyclic Location stores. */
2116
- var InspectorJsonWriter = class {
2117
- ancestors = [];
2118
- containers = /* @__PURE__ */ new WeakMap();
2119
- write(value) {
2120
- const replace = this.replace.bind(this);
2121
- const result = JSON.stringify(value, function(_key, item) {
2122
- return replace(this, item);
2123
- }, 2);
2124
- return typeof result === "string" ? result : "";
2125
- }
2126
- replace(parent, value) {
2127
- if (typeof value === "bigint") return `${value}n`;
2128
- if (value === null || typeof value !== "object") return value;
2129
- while (this.ancestors.length > 0 && this.ancestors.at(-1) !== parent) this.ancestors.pop();
2130
- let rendered = value;
2131
- if (value instanceof Map || value instanceof Set) {
2132
- const container = this.containers.get(value) ?? (value instanceof Map ? Object.fromEntries(value) : [...value]);
2133
- this.containers.set(value, container);
2134
- rendered = container;
2135
- }
2136
- if (this.ancestors.includes(rendered)) return "[Circular]";
2137
- this.ancestors.push(rendered);
2138
- return rendered;
2139
- }
2140
- };
2141
- /**
2142
- * Serialize raw details without allowing a formatting failure to retire the View.
2143
- * @param value - Original record; Maps/Sets become objects/arrays and bigint becomes an n-suffixed string.
2144
- * @returns JSON with circular references marked, or an error message for the detail panel.
2145
- */
2146
- function inspectorJson(value) {
2147
- try {
2148
- return {
2149
- text: new InspectorJsonWriter().write(value),
2150
- failed: false
2151
- };
2152
- } catch (error) {
2153
- return {
2154
- text: error instanceof Error ? error.message : String(error),
2155
- failed: true
2156
- };
2157
- }
2158
- }
2159
- //#endregion
2160
- //#region \0rabi-css:/home/runner/work/rabi-harness/rabi-harness/packages/experimental/session-inspector/src/client/views/inspector.module.css.mjs
2161
- 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:hover,.GTtnTq_typeFilterButton[aria-pressed=true]{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(100vh - 24px);color:var(--dsw-alias-label-primary);padding:10px;font-size:11px;position:fixed;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:hover,.GTtnTq_typeFilterOptions button[aria-selected=true]{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_table tr:hover,.GTtnTq_selected{background:var(--dsw-alias-interactive-bg-hover)}.GTtnTq_sticky{position:sticky}.GTtnTq_table .GTtnTq_sticky,.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:hover,.GTtnTq_detailsResize:active,.GTtnTq_detailsResize:focus-visible{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:hover,.GTtnTq_pickButton[aria-pressed=true]{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}.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}}";
2162
- const tagId = "@unieai/rabi-experimental-session-inspector/inspector.module.css";
2163
- if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId) + "]") === null) {
2164
- const tag = document.createElement("style");
2165
- tag.dataset.plugin = "@unieai/rabi-experimental-session-inspector";
2166
- tag.dataset.pluginCss = tagId;
2167
- tag.textContent = css;
2168
- document.head.appendChild(tag);
2169
- }
2170
- var inspector_module_css_default = {
2171
- "chatPick": "GTtnTq_chatPick",
2172
- "chatPickMask": "GTtnTq_chatPickMask",
2173
- "chatReveal": "GTtnTq_chatReveal",
2174
- "contextRow": "GTtnTq_contextRow",
2175
- "details": "GTtnTq_details",
2176
- "detailsResize": "GTtnTq_detailsResize",
2177
- "disclosure": "GTtnTq_disclosure",
2178
- "empty": "GTtnTq_empty",
2179
- "idColumn": "GTtnTq_idColumn",
2180
- "identity": "GTtnTq_identity",
2181
- "identityText": "GTtnTq_identityText",
2182
- "locationColumn": "GTtnTq_locationColumn",
2183
- "modeControls": "GTtnTq_modeControls",
2184
- "modeSelector": "GTtnTq_modeSelector",
2185
- "objectBreadcrumbs": "GTtnTq_objectBreadcrumbs",
2186
- "objectDetails": "GTtnTq_objectDetails",
2187
- "objectField": "GTtnTq_objectField",
2188
- "objectMuted": "GTtnTq_objectMuted",
2189
- "objectReference": "GTtnTq_objectReference",
2190
- "objectTree": "GTtnTq_objectTree",
2191
- "objectValue": "GTtnTq_objectValue",
2192
- "pickButton": "GTtnTq_pickButton",
2193
- "pickNotice": "GTtnTq_pickNotice",
2194
- "preview": "GTtnTq_preview",
2195
- "record": "GTtnTq_record",
2196
- "root": "GTtnTq_root",
2197
- "scroller": "GTtnTq_scroller",
2198
- "selected": "GTtnTq_selected",
2199
- "sticky": "GTtnTq_sticky",
2200
- "table": "GTtnTq_table",
2201
- "timeColumn": "GTtnTq_timeColumn",
2202
- "toolbar": "GTtnTq_toolbar",
2203
- "typeColumn": "GTtnTq_typeColumn",
2204
- "typeFilterActions": "GTtnTq_typeFilterActions",
2205
- "typeFilterButton": "GTtnTq_typeFilterButton",
2206
- "typeFilterHelp": "GTtnTq_typeFilterHelp",
2207
- "typeFilterInput": "GTtnTq_typeFilterInput",
2208
- "typeFilterOptions": "GTtnTq_typeFilterOptions",
2209
- "typeFilterPanel": "GTtnTq_typeFilterPanel",
2210
- "typeHeader": "GTtnTq_typeHeader"
2211
- };
2212
- //#endregion
2213
- //#region lib/types/client/views/InspectorDetails.js
2214
- /** Locally resizable raw-data panel; pointer capture owns the drag lifetime. */
2215
- function clampPercent(value) {
2216
- return Math.max(15, Math.min(80, value));
2217
- }
2218
- /**
2219
- * Resize the raw-data area from its upper edge while keeping the table visible.
2220
- * @param props - Complete raw text, localized labels, and close callback.
2221
- * @returns Detail text with a pointer- and keyboard-operated horizontal separator.
2222
- */
2223
- function InspectorDetails({ text, failed, children, close, t }) {
2224
- const id = (0, react.useId)();
2225
- const panel = (0, react.useRef)(null);
2226
- const drag = (0, react.useRef)(null);
2227
- const [percent, setPercent] = (0, react.useState)(40);
2228
- const resize = (event) => {
2229
- const current = drag.current;
2230
- if (current === null || current.pointerId !== event.pointerId) return;
2231
- setPercent(clampPercent((current.height + current.y - event.clientY) / current.available * 100));
2232
- };
2233
- const stop = (event) => {
2234
- if (drag.current?.pointerId !== event.pointerId) return;
2235
- drag.current = null;
2236
- if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
2237
- };
2238
- return (0, react_jsx_runtime.jsxs)("div", {
2239
- ref: panel,
2240
- id,
2241
- className: inspector_module_css_default.details,
2242
- style: { flexBasis: `${percent}%` },
2243
- children: [
2244
- (0, react_jsx_runtime.jsx)("div", {
2245
- role: "separator",
2246
- tabIndex: 0,
2247
- "aria-orientation": "horizontal",
2248
- "aria-controls": id,
2249
- "aria-label": t("table.resizeDetails"),
2250
- "aria-valuemin": 15,
2251
- "aria-valuemax": 80,
2252
- "aria-valuenow": Math.round(percent),
2253
- className: inspector_module_css_default.detailsResize,
2254
- onPointerDown: (event) => {
2255
- if (event.button !== 0 || drag.current !== null) return;
2256
- const element = panel.current;
2257
- const available = element?.parentElement?.getBoundingClientRect().height ?? 0;
2258
- if (element === null || available === 0) return;
2259
- event.preventDefault();
2260
- drag.current = {
2261
- pointerId: event.pointerId,
2262
- y: event.clientY,
2263
- height: element.getBoundingClientRect().height,
2264
- available
2265
- };
2266
- event.currentTarget.setPointerCapture(event.pointerId);
2267
- },
2268
- onPointerMove: resize,
2269
- onPointerUp: (event) => {
2270
- resize(event);
2271
- stop(event);
2272
- },
2273
- onPointerCancel: stop,
2274
- onLostPointerCapture: () => {
2275
- drag.current = null;
2276
- },
2277
- onKeyDown: (event) => {
2278
- switch (event.key) {
2279
- case "ArrowUp":
2280
- setPercent((value) => clampPercent(value + 5));
2281
- break;
2282
- case "ArrowDown":
2283
- setPercent((value) => clampPercent(value - 5));
2284
- break;
2285
- case "Home":
2286
- setPercent(15);
2287
- break;
2288
- case "End":
2289
- setPercent(80);
2290
- break;
2291
- default: return;
2292
- }
2293
- event.preventDefault();
2294
- }
2295
- }),
2296
- (0, react_jsx_runtime.jsxs)("div", {
2297
- className: inspector_module_css_default.toolbar,
2298
- children: [(0, react_jsx_runtime.jsx)("span", { children: t("table.raw") }), (0, react_jsx_runtime.jsx)("button", {
2299
- type: "button",
2300
- onClick: close,
2301
- children: t("table.close")
2302
- })]
2303
- }),
2304
- children === void 0 ? (0, react_jsx_runtime.jsx)("pre", {
2305
- role: failed ? "alert" : void 0,
2306
- children: text
2307
- }) : (0, react_jsx_runtime.jsx)("div", {
2308
- className: inspector_module_css_default.objectDetails,
2309
- children
2310
- })
2311
- ]
2312
- });
2313
- }
2314
- //#endregion
2315
- //#region lib/types/client/views/object-value.js
2316
- /** Shallow, typed runtime-object inspection without JSON conversion or implicit getter calls. */
2317
- var CollectionProperties = class {
2318
- value;
2319
- length;
2320
- constructor(value, length) {
2321
- this.value = value;
2322
- this.length = length;
2323
- }
2324
- };
2325
- const typedArrayLength = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "length").get;
2326
- function indexedLength(value) {
2327
- if (Array.isArray(value)) return value.length;
2328
- if (ArrayBuffer.isView(value) && !(value instanceof DataView)) return typedArrayLength.call(value);
2329
- }
2330
- function field(value, key, index) {
2331
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
2332
- return {
2333
- key: typeof key === "symbol" ? `symbol:${index}` : key,
2334
- name: String(key),
2335
- value: descriptor?.value,
2336
- ...descriptor === void 0 ? { absent: true } : "value" in descriptor ? {} : { accessor: true }
2337
- };
2338
- }
2339
- /** Display of one value; child enumeration never recursively visits child values. */
2340
- var InspectorObjectValue = class {
2341
- value;
2342
- /** Shallow type or scalar preview; no child getters are evaluated. */
2343
- label;
2344
- /** Whether this value permits child enumeration rather than opaque scalar display. */
2345
- expandable;
2346
- /** @param value - Original runtime value, including Maps, Sets, and class instances. */
2347
- constructor(value) {
2348
- this.value = value;
2349
- this.expandable = value !== null && typeof value === "object" && !(value instanceof Date || value instanceof RegExp || value instanceof WeakMap || value instanceof WeakSet);
2350
- if (value instanceof Map) this.label = `Map(${value.size})`;
2351
- else if (value instanceof Set) this.label = `Set(${value.size})`;
2352
- else if (Array.isArray(value)) this.label = `Array(${value.length})`;
2353
- else if (value instanceof Date) this.label = `Date(${Number.isNaN(value.getTime()) ? "Invalid" : value.toISOString()})`;
2354
- else if (value instanceof RegExp) this.label = String(value);
2355
- else if (value instanceof WeakMap) this.label = "WeakMap";
2356
- else if (value instanceof WeakSet) this.label = "WeakSet";
2357
- else if (value instanceof ArrayBuffer) this.label = `ArrayBuffer(${value.byteLength})`;
2358
- else if (value instanceof CollectionProperties) this.label = "Object";
2359
- else if (value !== null && typeof value === "object") {
2360
- const prototype = Object.getPrototypeOf(value);
2361
- const constructor = prototype === null ? void 0 : Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
2362
- this.label = typeof constructor === "function" ? constructor.name : "Object";
2363
- } else if (typeof value === "string") this.label = JSON.stringify(value);
2364
- else if (typeof value === "bigint") this.label = `${value}n`;
2365
- else if (typeof value === "function") this.label = `[Function ${value.name}]`;
2366
- else this.label = String(value);
2367
- }
2368
- /**
2369
- * Enumerate one level without evaluating accessors or descending into children.
2370
- * @returns Original children; Map keys remain values rather than being coerced to property names.
2371
- */
2372
- *entries() {
2373
- const value = this.value;
2374
- if (value instanceof Map) {
2375
- let index = 0;
2376
- const entries = value;
2377
- for (const [key, item] of entries) yield {
2378
- key: String(index),
2379
- name: String(index++),
2380
- value: {
2381
- key,
2382
- value: item
2383
- }
2384
- };
2385
- } else if (value instanceof Set) {
2386
- let index = 0;
2387
- for (const item of value) yield {
2388
- key: String(index),
2389
- name: String(index++),
2390
- value: item
2391
- };
2392
- } else if (value instanceof ArrayBuffer || value instanceof DataView) yield {
2393
- key: "bytes",
2394
- name: "bytes",
2395
- value: value instanceof ArrayBuffer ? new Uint8Array(value) : new Uint8Array(value.buffer, value.byteOffset, value.byteLength)
2396
- };
2397
- else if (value !== null && typeof value === "object") {
2398
- const length = indexedLength(value);
2399
- if (length !== void 0) {
2400
- yield {
2401
- key: "properties",
2402
- name: "",
2403
- properties: true,
2404
- value: new CollectionProperties(value, length)
2405
- };
2406
- for (let index = 0; index < length; index++) yield field(value, String(index), index);
2407
- } else {
2408
- const target = value instanceof CollectionProperties ? value.value : value;
2409
- for (const [index, key] of Reflect.ownKeys(target).entries()) {
2410
- 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;
2411
- const entry = field(target, key, index);
2412
- if (!entry.absent) yield entry;
2413
- }
2414
- }
2415
- }
2416
- }
2417
- };
2418
- //#endregion
2419
- //#region lib/types/client/views/InspectorObjectTree.js
2420
- /** Shared value rendering for JSON details and lazy runtime objects with identity links. */
2421
- const PAGE_SIZE = 50;
2422
- function ObjectBranch({ value, name, path, ancestors, root, accessor, absent, navigation, t }) {
2423
- const json = navigation === void 0;
2424
- const objects = navigation?.objects;
2425
- const revision = navigation?.revision;
2426
- const [expanded, setExpanded] = (0, react.useState)(root === true || json);
2427
- const [limit, setLimit] = (0, react.useState)(json ? Infinity : PAGE_SIZE);
2428
- const content = (0, react.useMemo)(() => {
2429
- try {
2430
- const reference = !root && value !== null && typeof value === "object" ? objects?.reference(value) : void 0;
2431
- const circular = value !== null && typeof value === "object" ? ancestors.get(value) : void 0;
2432
- const display = (reference === void 0 || reference.kind === "nodeData") && circular === void 0 && !accessor ? new InspectorObjectValue(value) : void 0;
2433
- const entries = [];
2434
- if (expanded && display?.expandable === true) for (const entry of display.entries()) {
2435
- if (json && entry.properties) continue;
2436
- entries.push(entry);
2437
- if (entries.length > limit) break;
2438
- }
2439
- return {
2440
- reference,
2441
- circular,
2442
- display,
2443
- entries,
2444
- error: void 0
2445
- };
2446
- } catch (error) {
2447
- return { error: error instanceof Error ? error.message : String(error) };
2448
- }
2449
- }, [
2450
- value,
2451
- root,
2452
- objects,
2453
- ancestors,
2454
- accessor,
2455
- expanded,
2456
- limit,
2457
- revision,
2458
- json
2459
- ]);
2460
- const children = (0, react.useMemo)(() => {
2461
- const next = new Map(ancestors);
2462
- if (value !== null && typeof value === "object") next.set(value, path);
2463
- return next;
2464
- }, [
2465
- ancestors,
2466
- value,
2467
- path
2468
- ]);
2469
- const field = (0, react_jsx_runtime.jsxs)("span", {
2470
- className: inspector_module_css_default.objectField,
2471
- children: [name, ": "]
2472
- });
2473
- if (content.error !== void 0) return (0, react_jsx_runtime.jsxs)("li", {
2474
- role: "alert",
2475
- children: [field, content.error]
2476
- });
2477
- if (absent) return (0, react_jsx_runtime.jsxs)("li", { children: [field, (0, react_jsx_runtime.jsx)("span", {
2478
- className: inspector_module_css_default.objectMuted,
2479
- children: t("object.absent")
2480
- })] });
2481
- if (accessor) return (0, react_jsx_runtime.jsxs)("li", { children: [field, (0, react_jsx_runtime.jsx)("span", {
2482
- className: inspector_module_css_default.objectMuted,
2483
- children: t("object.accessor")
2484
- })] });
2485
- const reference = content.reference;
2486
- const link = reference === void 0 || navigation === void 0 ? void 0 : (0, react_jsx_runtime.jsxs)("button", {
2487
- type: "button",
2488
- className: inspector_module_css_default.objectReference,
2489
- onClick: (event) => {
2490
- event.preventDefault();
2491
- event.stopPropagation();
2492
- navigation.navigate(reference);
2493
- },
2494
- children: [
2495
- "↗ ",
2496
- t(`object.${reference.kind}`),
2497
- " · ",
2498
- reference.identity
2499
- ]
2500
- });
2501
- if (reference !== void 0 && (reference.kind !== "nodeData" || content.circular !== void 0)) return (0, react_jsx_runtime.jsxs)("li", { children: [field, link] });
2502
- if (content.circular !== void 0) return (0, react_jsx_runtime.jsxs)("li", { children: [field, (0, react_jsx_runtime.jsxs)("span", {
2503
- className: inspector_module_css_default.objectMuted,
2504
- children: ["↩ ", content.circular]
2505
- })] });
2506
- const display = content.display;
2507
- if (!display.expandable) return (0, react_jsx_runtime.jsxs)("li", { children: [field, (0, react_jsx_runtime.jsx)("span", {
2508
- className: inspector_module_css_default.objectValue,
2509
- children: display.label
2510
- })] });
2511
- return (0, react_jsx_runtime.jsx)("li", { children: (0, react_jsx_runtime.jsxs)("details", {
2512
- open: expanded,
2513
- onToggle: (event) => {
2514
- setExpanded(event.currentTarget.open);
2515
- },
2516
- children: [(0, react_jsx_runtime.jsxs)("summary", { children: [
2517
- field,
2518
- link,
2519
- " ",
2520
- (0, react_jsx_runtime.jsx)("span", {
2521
- className: inspector_module_css_default.objectMuted,
2522
- children: display.label
2523
- })
2524
- ] }), expanded && (0, react_jsx_runtime.jsxs)("ul", { children: [
2525
- content.entries.slice(0, limit).map(({ key, properties, ...entry }) => (0, react_jsx_runtime.jsx)(ObjectBranch, {
2526
- ...entry,
2527
- name: properties ? t("object.properties") : entry.name,
2528
- path: properties ? path : `${path}.${entry.name}`,
2529
- ancestors: children,
2530
- navigation,
2531
- t
2532
- }, key)),
2533
- content.entries.length === 0 && (0, react_jsx_runtime.jsx)("li", {
2534
- className: inspector_module_css_default.objectMuted,
2535
- children: t("object.empty")
2536
- }),
2537
- content.entries.length > limit && (0, react_jsx_runtime.jsx)("li", { children: (0, react_jsx_runtime.jsx)("button", {
2538
- type: "button",
2539
- className: inspector_module_css_default.objectReference,
2540
- onClick: () => {
2541
- setLimit((value) => value + PAGE_SIZE);
2542
- },
2543
- children: t("object.more")
2544
- }) })
2545
- ] })]
2546
- }) });
2547
- }
2548
- function ValueTree(props) {
2549
- const ancestors = (0, react.useMemo)(() => /* @__PURE__ */ new Map(), []);
2550
- return (0, react_jsx_runtime.jsx)("ul", {
2551
- className: inspector_module_css_default.objectTree,
2552
- children: (0, react_jsx_runtime.jsx)(ObjectBranch, {
2553
- ...props,
2554
- name: "$",
2555
- path: "$",
2556
- ancestors,
2557
- root: true
2558
- })
2559
- });
2560
- }
2561
- /**
2562
- * Display serialized Inspector JSON with every container initially expanded and no reference navigation.
2563
- * @param props - Successful inspectorJson output and localized tree labels; empty text represents undefined.
2564
- * @returns The same value tree as Chat details, without collection paging or runtime-object links.
2565
- */
2566
- function InspectorJsonTree({ text, t }) {
2567
- return (0, react_jsx_runtime.jsx)(ValueTree, {
2568
- value: (0, react.useMemo)(() => text === "" ? void 0 : JSON.parse(text), [text]),
2569
- t
2570
- });
2571
- }
2572
- /**
2573
- * Inspect the root and nested Node Data inline; other registered objects remain navigation links.
2574
- * Node Data titles also navigate, while repeated ancestors never expand recursively.
2575
- * Expanded fields are cached until their value or Conversation publication changes.
2576
- * @param props - Original object, weak identity lookup, locale, and reference activation.
2577
- * @returns A lazily expanded, typed tree that retains Map keys and collection identities.
2578
- */
2579
- function InspectorObjectTree(props) {
2580
- const updates = props.objects.updates;
2581
- const revision = (0, react.useSyncExternalStore)((0, react.useCallback)((listener) => updates.subscribe(listener), [updates]), (0, react.useCallback)(() => updates.getSnapshot(), [updates]));
2582
- return (0, react_jsx_runtime.jsx)(ValueTree, {
2583
- value: props.value,
2584
- t: props.t,
2585
- navigation: {
2586
- objects: props.objects,
2587
- navigate: props.navigate,
2588
- revision
2589
- }
2590
- });
2591
- }
2592
- /** View-local spacing; constructing without a predecessor resets retained blank areas. */
2593
- var InspectorTableLayout = class {
2594
- hierarchy;
2595
- /** Visible data rows and their virtual sizes; excludes the table header and trailing space. */
2596
- items;
2597
- /** Whether a live block closure shortened the previous visible hierarchy. */
2598
- preservedCollapse;
2599
- /** Trailing space in CSS pixels retained to keep the viewport anchor stable. */
2600
- bottomPadding;
2601
- /** Anchored scroll offset in CSS pixels, or undefined when no anchor adjustment is needed. */
2602
- scrollOffset;
2603
- minimumExtent;
2604
- rowIndexes = /* @__PURE__ */ new Map();
2605
- /**
2606
- * @param hierarchy - Current visible data rows.
2607
- * @param previous - Previous committed layout, omitted after manual disclosure changes.
2608
- * @param viewport - Scroll geometry before the current row change.
2609
- * @param anchor - Clicked disclosure row to retain at its measured viewport position.
2610
- */
2611
- constructor(hierarchy, previous, viewport = {
2612
- offset: 0,
2613
- height: 0
2614
- }, anchor) {
2615
- this.hierarchy = hierarchy;
2616
- for (const [rowIndex, row] of hierarchy.rows.entries()) this.rowIndexes.set(row.key, rowIndex);
2617
- this.items = hierarchy.rows.map((row, rowIndex) => ({
2618
- key: row.key,
2619
- rowIndex,
2620
- row,
2621
- size: 30
2622
- }));
2623
- 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");
2624
- const anchorIndex = anchor === void 0 ? void 0 : this.rowIndexes.get(anchor.key);
2625
- 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;
2626
- const natural = (this.items.length + 1) * 30;
2627
- const minimum = this.scrollOffset === void 0 ? previous?.minimumExtent ?? 0 : Math.max(this.scrollOffset + viewport.height, (previous?.minimumExtent ?? 0) + this.scrollOffset - viewport.offset);
2628
- this.minimumExtent = minimum > natural ? minimum : 0;
2629
- this.bottomPadding = Math.max(0, this.minimumExtent - natural);
2630
- }
2631
- /**
2632
- * Keep the enclosing headers visible above the first visible data row.
2633
- * @param itemIndex - First visible virtual item.
2634
- * @returns Ancestor indexes in the virtual layout.
2635
- */
2636
- stickyIndexes(itemIndex) {
2637
- return this.hierarchy.stickyIndexes(itemIndex);
2638
- }
2639
- /**
2640
- * Resolve each sticky level below the table header and already occupied sticky rows.
2641
- * @param offset - Scroll offset in CSS pixels.
2642
- * @returns Active ancestor indexes, outermost first.
2643
- */
2644
- stickyIndexesAtOffset(offset) {
2645
- const indexes = [];
2646
- const first = Math.max(0, Math.floor(offset / 30));
2647
- while (indexes.length < this.items.length) {
2648
- const candidate = Math.min(this.items.length - 1, first + indexes.length);
2649
- const ancestors = this.stickyIndexes(candidate);
2650
- const next = ancestors[indexes.length];
2651
- if (next === void 0 || indexes.some((index, level) => ancestors[level] !== index)) break;
2652
- indexes.push(next);
2653
- }
2654
- return indexes;
2655
- }
2656
- anchorOffset(previous, offset) {
2657
- const first = Math.max(0, Math.min(previous.items.length - 1, Math.floor(offset / 30)));
2658
- const index = Math.min(previous.items.length - 1, first + previous.stickyIndexesAtOffset(offset).length);
2659
- const row = previous.items[index].row;
2660
- const retained = this.rowIndexes.get(row.key);
2661
- if (retained !== void 0) return Math.max(0, offset + (retained - index) * 30);
2662
- const ancestors = previous.stickyIndexes(index);
2663
- for (let level = ancestors.length - 1; level >= 0; level--) {
2664
- const parent = previous.items[ancestors[level]].row;
2665
- const next = this.rowIndexes.get(parent.key);
2666
- if (next !== void 0) return Math.max(0, (next - level) * 30);
2667
- }
2668
- return 0;
2669
- }
2670
- };
2671
- //#endregion
2672
- //#region lib/types/client/views/type-filter.js
2673
- /** Confirmed type filtering preserves the ancestors needed to inspect matching nested rows. */
2674
- /** Case-insensitive containment filter; optional surrounding stars have the same meaning as omission. */
2675
- var InspectorTypeFilter = class {
2676
- /** Trimmed type fragment without optional surrounding stars; preserves the entered case. */
2677
- query;
2678
- needle;
2679
- /** @param query - Type fragment; empty text or only stars clears filtering. */
2680
- constructor(query) {
2681
- this.query = query.trim().replace(/^\*+|\*+$/g, "").trim();
2682
- this.needle = this.query.toLowerCase();
2683
- }
2684
- /**
2685
- * Distinguish a type restriction from an empty or all-stars query.
2686
- * @returns Whether this filter restricts the table.
2687
- */
2688
- get active() {
2689
- return this.needle !== "";
2690
- }
2691
- /**
2692
- * Match a type by case-insensitive containment, accepting all types when filtering is inactive.
2693
- * @param type - Current raw type, absent while its record is unavailable.
2694
- * @returns Whether the record matches the filter.
2695
- */
2696
- matches(type) {
2697
- return !this.active || type !== void 0 && type.toLowerCase().includes(this.needle);
2698
- }
2699
- /**
2700
- * Retain matching rows and their ancestors; matching descendants start visible even under closed blocks.
2701
- * @param rows - Complete loaded hierarchy, before user disclosure choices.
2702
- * @param typeOf - Current type reader, independent of React row subscriptions.
2703
- * @returns Matching rows and contextual ancestors in their original order.
2704
- */
2705
- apply(rows, typeOf) {
2706
- if (!this.active) return {
2707
- rows,
2708
- matches: new Set(rows.map((row) => row.key))
2709
- };
2710
- const matches = new Set(rows.filter((row) => this.matches(typeOf(row.key))).map((row) => row.key));
2711
- const byKey = new Map(rows.map((row) => [row.key, row]));
2712
- const retained = new Set(matches);
2713
- for (const key of matches) {
2714
- let parent = byKey.get(key)?.parent;
2715
- while (parent !== void 0 && !retained.has(parent)) {
2716
- retained.add(parent);
2717
- parent = byKey.get(parent)?.parent;
2718
- }
2719
- }
2720
- const branches = /* @__PURE__ */ new Set();
2721
- for (const key of retained) {
2722
- const parent = byKey.get(key)?.parent;
2723
- if (parent !== void 0) branches.add(parent);
2724
- }
2725
- return {
2726
- matches,
2727
- rows: rows.filter((row) => retained.has(row.key)).map((row) => {
2728
- const { disclosure: _disclosure, ...plain } = row;
2729
- return branches.has(row.key) ? {
2730
- ...plain,
2731
- disclosure: "open"
2732
- } : plain;
2733
- })
2734
- };
2735
- }
2736
- /**
2737
- * Resolve candidates asynchronously from all loaded rows, not the already filtered subset.
2738
- * @param rows - Complete loaded row list.
2739
- * @param typeOf - Current raw type reader.
2740
- * @returns Distinct matching types in deterministic order.
2741
- */
2742
- async suggest(rows, typeOf) {
2743
- await Promise.resolve();
2744
- const types = /* @__PURE__ */ new Set();
2745
- for (const row of rows) {
2746
- const type = typeOf(row.key);
2747
- if (type !== void 0 && this.matches(type)) types.add(type);
2748
- }
2749
- return [...types].sort();
2750
- }
2751
- };
2752
- //#endregion
2753
- //#region lib/types/client/views/TypeFilter.js
2754
- /** Anchored type-filter editor with asynchronous suggestions and explicit confirmation. */
2755
- /**
2756
- * Edit a type fragment without filtering until Enter, Apply, or a candidate is selected.
2757
- * @param props - Confirmed query, candidate resolver, commit callback, and localized copy.
2758
- * @returns A header button and its portaled editor; stale responses cannot replace newer suggestions.
2759
- */
2760
- function TypeFilter({ value, suggest, apply, t }) {
2761
- const [open, setOpen] = (0, react.useState)(false);
2762
- const [draft, setDraft] = (0, react.useState)(value);
2763
- const [active, setActive] = (0, react.useState)(-1);
2764
- const [result, setResult] = (0, react.useState)();
2765
- const anchor = (0, react.useRef)(null);
2766
- const panel = (0, react.useRef)(null);
2767
- const input = (0, react.useRef)(null);
2768
- const id = (0, react.useId)();
2769
- const listId = `${id}-types`;
2770
- const position = (0, _unieai_rabi_client_ui_primitives.useAnchoredPosition)({
2771
- open,
2772
- anchorRef: anchor,
2773
- panelRef: panel,
2774
- gap: 4,
2775
- margin: 12
2776
- });
2777
- const close = (0, react.useCallback)((restoreFocus) => {
2778
- setOpen(false);
2779
- if (restoreFocus) anchor.current?.focus({ preventScroll: true });
2780
- }, []);
2781
- const commit = (query) => {
2782
- apply(query);
2783
- close(true);
2784
- };
2785
- (0, react.useEffect)(() => {
2786
- if (!open) return;
2787
- input.current?.focus({ preventScroll: true });
2788
- input.current?.select();
2789
- const outside = (event) => {
2790
- const target = event.target;
2791
- if (target instanceof Node && !panel.current?.contains(target) && !anchor.current?.contains(target)) close(false);
2792
- };
2793
- const blur = () => {
2794
- close(false);
2795
- };
2796
- window.addEventListener("pointerdown", outside, true);
2797
- window.addEventListener("blur", blur);
2798
- return () => {
2799
- window.removeEventListener("pointerdown", outside, true);
2800
- window.removeEventListener("blur", blur);
2801
- };
2802
- }, [open, close]);
2803
- (0, react.useEffect)(() => {
2804
- if (!open) return;
2805
- let current = true;
2806
- setResult(void 0);
2807
- setActive(-1);
2808
- Promise.resolve().then(() => suggest(draft)).then((items) => {
2809
- if (current) setResult({
2810
- query: draft,
2811
- items
2812
- });
2813
- }, (error) => {
2814
- if (current) setResult({
2815
- query: draft,
2816
- items: [],
2817
- error: error instanceof Error ? error.message : String(error)
2818
- });
2819
- });
2820
- return () => {
2821
- current = false;
2822
- };
2823
- }, [
2824
- open,
2825
- draft,
2826
- suggest
2827
- ]);
2828
- const current = result?.query === draft ? result : void 0;
2829
- const items = current?.items ?? [];
2830
- const selected = active >= 0 && active < items.length ? active : -1;
2831
- (0, react.useEffect)(() => {
2832
- if (selected >= 0) panel.current?.querySelectorAll("[role=\"option\"]")[selected]?.scrollIntoView({ block: "nearest" });
2833
- }, [selected]);
2834
- return (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [(0, react_jsx_runtime.jsx)("button", {
2835
- ref: anchor,
2836
- type: "button",
2837
- className: inspector_module_css_default.typeFilterButton,
2838
- "aria-label": t("filter.title"),
2839
- title: value === "" ? t("filter.title") : `${t("filter.title")}: *${value}*`,
2840
- "aria-haspopup": "dialog",
2841
- "aria-expanded": open,
2842
- "aria-pressed": value !== "",
2843
- onClick: () => {
2844
- if (open) {
2845
- close(true);
2846
- return;
2847
- }
2848
- setDraft(value);
2849
- setResult(void 0);
2850
- setActive(-1);
2851
- setOpen(true);
2852
- },
2853
- children: (0, react_jsx_runtime.jsx)("svg", {
2854
- width: "13",
2855
- height: "13",
2856
- viewBox: "0 0 16 16",
2857
- fill: "none",
2858
- stroke: "currentColor",
2859
- strokeWidth: "1.3",
2860
- "aria-hidden": "true",
2861
- children: (0, react_jsx_runtime.jsx)("path", { d: "M2 3h12L9.5 8v5l-3-1.5V8L2 3Z" })
2862
- })
2863
- }), open && (0, react_dom.createPortal)((0, react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.MenuSurface, {
2864
- compact: true,
2865
- ref: panel,
2866
- className: inspector_module_css_default.typeFilterPanel,
2867
- role: "dialog",
2868
- "aria-label": t("filter.title"),
2869
- style: position ?? {
2870
- left: 0,
2871
- top: 0,
2872
- visibility: "hidden"
2873
- },
2874
- onKeyDown: (event) => {
2875
- if (event.key === "Escape") {
2876
- event.preventDefault();
2877
- event.stopPropagation();
2878
- close(true);
2879
- }
2880
- },
2881
- onBlur: (event) => {
2882
- if (event.relatedTarget instanceof Node && !event.currentTarget.contains(event.relatedTarget) && !anchor.current?.contains(event.relatedTarget)) close(false);
2883
- },
2884
- children: (0, react_jsx_runtime.jsxs)("div", { children: [
2885
- (0, react_jsx_runtime.jsx)("input", {
2886
- ref: input,
2887
- className: inspector_module_css_default.typeFilterInput,
2888
- value: draft,
2889
- role: "combobox",
2890
- "aria-label": t("filter.input"),
2891
- "aria-autocomplete": "list",
2892
- "aria-expanded": true,
2893
- "aria-controls": listId,
2894
- "aria-activedescendant": selected < 0 ? void 0 : `${id}-option-${selected}`,
2895
- placeholder: t("filter.placeholder"),
2896
- onChange: (event) => {
2897
- setDraft(event.currentTarget.value);
2898
- setActive(-1);
2899
- },
2900
- onKeyDown: (event) => {
2901
- if (event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) return;
2902
- if (event.key === "ArrowDown" || event.key === "ArrowUp") {
2903
- event.preventDefault();
2904
- setActive(items.length === 0 ? -1 : selected < 0 ? event.key === "ArrowDown" ? 0 : items.length - 1 : (selected + (event.key === "ArrowDown" ? 1 : -1) + items.length) % items.length);
2905
- } else if (event.key === "Enter") {
2906
- event.preventDefault();
2907
- commit(items[selected] ?? draft);
2908
- }
2909
- }
2910
- }),
2911
- (0, react_jsx_runtime.jsx)("div", {
2912
- className: inspector_module_css_default.typeFilterHelp,
2913
- children: t("filter.help")
2914
- }),
2915
- (0, react_jsx_runtime.jsx)("div", {
2916
- id: listId,
2917
- role: "listbox",
2918
- "aria-label": t("filter.candidates"),
2919
- "aria-busy": current === void 0,
2920
- className: inspector_module_css_default.typeFilterOptions,
2921
- children: items.map((type, index) => (0, react_jsx_runtime.jsx)("button", {
2922
- id: `${id}-option-${index}`,
2923
- type: "button",
2924
- role: "option",
2925
- "aria-selected": selected === index,
2926
- tabIndex: -1,
2927
- title: type,
2928
- onPointerDown: (event) => {
2929
- event.preventDefault();
2930
- },
2931
- onClick: () => {
2932
- commit(type);
2933
- },
2934
- children: type
2935
- }, type))
2936
- }),
2937
- current === void 0 && (0, react_jsx_runtime.jsx)("div", {
2938
- role: "status",
2939
- children: t("filter.loading")
2940
- }),
2941
- current?.error !== void 0 ? (0, react_jsx_runtime.jsxs)("div", {
2942
- role: "alert",
2943
- children: [
2944
- t("filter.failed"),
2945
- " ",
2946
- current.error
2947
- ]
2948
- }) : current !== void 0 && items.length === 0 && (0, react_jsx_runtime.jsx)("div", {
2949
- role: "status",
2950
- children: t("filter.noCandidates")
2951
- }),
2952
- (0, react_jsx_runtime.jsxs)("div", {
2953
- className: inspector_module_css_default.typeFilterActions,
2954
- children: [
2955
- (0, react_jsx_runtime.jsx)("button", {
2956
- type: "button",
2957
- onClick: () => {
2958
- setDraft("");
2959
- setActive(-1);
2960
- input.current?.focus();
2961
- },
2962
- children: t("filter.clear")
2963
- }),
2964
- (0, react_jsx_runtime.jsx)("button", {
2965
- type: "button",
2966
- onClick: () => {
2967
- close(true);
2968
- },
2969
- children: t("filter.cancel")
2970
- }),
2971
- (0, react_jsx_runtime.jsx)("button", {
2972
- type: "button",
2973
- onClick: () => {
2974
- commit(draft);
2975
- },
2976
- children: t("filter.apply")
2977
- })
2978
- ]
2979
- })
2980
- ] })
2981
- }), document.body)] });
2982
- }
2983
- //#endregion
2984
- //#region lib/types/client/views/InspectorTable.js
2985
- /** Virtualized raw-data table shared by Session log and Chat structure views. */
2986
- const DataRow = (0, react.memo)(function DataRow({ row, selected, branch, collapsed, added, stickyLevel, pulse, context, select, toggle, useRecord, flash, showTime, t }) {
2987
- const record = useRecord(row.key);
2988
- const element = (0, react.useRef)(null);
2989
- const previous = (0, react.useRef)(record);
2990
- const previousPulse = (0, react.useRef)(0);
2991
- (0, react.useEffect)(() => {
2992
- const changed = previous.current !== record;
2993
- previous.current = record;
2994
- const navigated = pulse > 0 && previousPulse.current !== pulse;
2995
- previousPulse.current = pulse;
2996
- if (!flash && !navigated || !changed && !added && !navigated || element.current === null || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
2997
- const color = getComputedStyle(element.current).getPropertyValue("--dsw-specific-bubble-highlight");
2998
- const animation = element.current.animate([{ backgroundColor: color }, { backgroundColor: "transparent" }], { duration: 700 });
2999
- return () => {
3000
- animation.cancel();
3001
- };
3002
- }, [
3003
- record,
3004
- added,
3005
- flash,
3006
- pulse
3007
- ]);
3008
- const summary = (0, react.useMemo)(() => (collapsed ? record?.collapsedSummary : void 0) ?? record?.summary ?? inspectorPreview(record?.value), [record, collapsed]);
3009
- return (0, react_jsx_runtime.jsxs)("tr", {
3010
- ref: element,
3011
- "aria-selected": selected,
3012
- "data-inspector-context": context ? "" : void 0,
3013
- title: context ? t("filter.context") : void 0,
3014
- className: [
3015
- selected && inspector_module_css_default.selected,
3016
- stickyLevel !== void 0 && inspector_module_css_default.sticky,
3017
- context && inspector_module_css_default.contextRow
3018
- ].filter(Boolean).join(" "),
3019
- style: stickyLevel === void 0 ? void 0 : {
3020
- top: (stickyLevel + 1) * 30,
3021
- zIndex: 9 - stickyLevel
3022
- },
3023
- children: [
3024
- (0, react_jsx_runtime.jsx)("td", {
3025
- className: inspector_module_css_default.identity,
3026
- children: (0, react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.Tooltip, {
3027
- label: record?.identity ?? "",
3028
- side: "right",
3029
- portal: true,
3030
- children: (0, react_jsx_runtime.jsx)("span", {
3031
- className: inspector_module_css_default.identityText,
3032
- tabIndex: 0,
3033
- children: record?.identity
3034
- })
3035
- })
3036
- }),
3037
- (0, react_jsx_runtime.jsxs)("td", {
3038
- style: { paddingInlineStart: 8 + row.depth * 20 },
3039
- children: [branch && (0, react_jsx_runtime.jsx)("button", {
3040
- type: "button",
3041
- className: inspector_module_css_default.disclosure,
3042
- "aria-label": collapsed ? t("table.expand") : t("table.collapse"),
3043
- "aria-expanded": !collapsed,
3044
- onClick: () => {
3045
- toggle(row, element.current);
3046
- },
3047
- children: collapsed ? "▸" : "▾"
3048
- }), (0, react_jsx_runtime.jsx)("button", {
3049
- type: "button",
3050
- className: inspector_module_css_default.record,
3051
- onClick: () => {
3052
- select(row.key);
3053
- },
3054
- children: record?.type
3055
- })]
3056
- }),
3057
- (0, react_jsx_runtime.jsx)("td", { children: record?.location }),
3058
- showTime && (0, react_jsx_runtime.jsx)("td", { children: record?.time === void 0 ? "" : new Date(record.time).toISOString().slice(11, 23) }),
3059
- (0, react_jsx_runtime.jsx)("td", { children: (0, react_jsx_runtime.jsx)("button", {
3060
- type: "button",
3061
- className: inspector_module_css_default.preview,
3062
- onClick: () => {
3063
- select(row.key);
3064
- },
3065
- children: summary
3066
- }) })
3067
- ]
3068
- });
3069
- });
3070
- /**
3071
- * Render a paged hierarchy with stable virtual row keys and live JSON details.
3072
- * @param props - Framework hooks, pagination, locale, and the view's highlight policy.
3073
- * @returns Virtual table and selected raw data.
3074
- */
3075
- function InspectorTable({ title, flash, showTime, modeSelector, objects, navigation, pickedRow, notice, useRows, useRecord, useSession, loadOlder, typeOf, t }) {
3076
- const allRows = useRows((value) => value);
3077
- const hasMore = useSession((value) => value.hasMore);
3078
- const loading = useSession((value) => value.loadingOlder);
3079
- const openError = useSession((value) => value.openError);
3080
- const [failure, setFailure] = (0, react.useState)(null);
3081
- const [selected, setSelected] = (0, react.useState)(null);
3082
- const record = useRecord(selected ?? "");
3083
- const rowLabel = `${record?.type ?? ""} · ${record?.identity ?? selected}`;
3084
- const [objectHistory, setObjectHistory] = (0, react.useState)(null);
3085
- const objectTarget = objectHistory?.references.at(-1);
3086
- const [reveal, setReveal] = (0, react.useState)(null);
3087
- const appliedReveal = (0, react.useRef)(null);
3088
- const appliedPick = (0, react.useRef)();
3089
- const [disclosures, setDisclosures] = (0, react.useState)(/* @__PURE__ */ new Map());
3090
- const [typeQuery, setTypeQuery] = (0, react.useState)("");
3091
- const typeFilter = (0, react.useMemo)(() => new InspectorTypeFilter(typeQuery), [typeQuery]);
3092
- const filtered = (0, react.useMemo)(() => typeFilter.apply(allRows, typeOf), [
3093
- allRows,
3094
- typeOf,
3095
- typeFilter
3096
- ]);
3097
- const suggestTypes = (0, react.useCallback)((query) => new InspectorTypeFilter(query).suggest(allRows, typeOf), [allRows, typeOf]);
3098
- const scroller = (0, react.useRef)(null);
3099
- const followMode = (0, react.useRef)("tail");
3100
- const viewport = (0, react.useRef)({
3101
- offset: 0,
3102
- height: 600
3103
- });
3104
- const disclosureAnchor = (0, react.useRef)();
3105
- const [spacingGeneration, resetSpacing] = (0, react.useState)(0);
3106
- const toggle = (0, react.useCallback)((row, element) => {
3107
- const host = scroller.current;
3108
- followMode.current = "manual";
3109
- disclosureAnchor.current = {
3110
- key: row.key,
3111
- top: element.getBoundingClientRect().top - host.getBoundingClientRect().top - host.clientTop
3112
- };
3113
- viewport.current = {
3114
- offset: host.scrollTop,
3115
- height: host.clientHeight
3116
- };
3117
- setDisclosures((previous) => {
3118
- const next = new Map(previous);
3119
- next.set(row.key, {
3120
- state: row.disclosure,
3121
- collapsed: !inspectorRowCollapsed(row, previous)
3122
- });
3123
- return next;
3124
- });
3125
- }, []);
3126
- const locateChat = (0, react.useCallback)((target) => {
3127
- navigation?.reveal(target ?? {});
3128
- }, [navigation]);
3129
- const select = (0, react.useCallback)((key) => {
3130
- setSelected(key);
3131
- setObjectHistory(null);
3132
- const target = navigation?.target(key);
3133
- locateChat(target);
3134
- }, [navigation, locateChat]);
3135
- const revealRow = (0, react.useCallback)((key) => {
3136
- const clearFilter = typeFilter.active && !filtered.rows.some((row) => row.key === key);
3137
- if (clearFilter) setTypeQuery("");
3138
- followMode.current = "scroll";
3139
- setSelected(key);
3140
- setDisclosures((previous) => {
3141
- const next = new Map(previous);
3142
- const byKey = new Map((clearFilter ? allRows : filtered.rows).map((row) => [row.key, row]));
3143
- let parent = byKey.get(key)?.parent;
3144
- while (parent !== void 0) {
3145
- const row = byKey.get(parent);
3146
- if (row === void 0) break;
3147
- next.set(parent, {
3148
- state: row.disclosure,
3149
- collapsed: false
3150
- });
3151
- parent = row.parent;
3152
- }
3153
- return next;
3154
- });
3155
- setReveal((previous) => ({
3156
- key,
3157
- pulse: (previous?.pulse ?? 0) + 1
3158
- }));
3159
- }, [
3160
- allRows,
3161
- typeFilter,
3162
- filtered.rows
3163
- ]);
3164
- const navigate = (0, react.useCallback)((reference) => {
3165
- setObjectHistory((previous) => ({
3166
- rootKey: previous?.rootKey ?? selected,
3167
- rootLabel: previous?.rootLabel ?? rowLabel,
3168
- references: [...previous?.references ?? [], reference]
3169
- }));
3170
- locateChat(reference.target);
3171
- if (reference.rowKey !== void 0) revealRow(reference.rowKey);
3172
- }, [
3173
- revealRow,
3174
- locateChat,
3175
- selected,
3176
- rowLabel
3177
- ]);
3178
- const backToObject = (index) => {
3179
- const history = objectHistory;
3180
- const reference = history.references[index - 1];
3181
- const key = index === 0 ? history.rootKey : reference?.rowKey;
3182
- const target = index === 0 ? navigation?.target(history.rootKey) : reference?.target;
3183
- setObjectHistory(index === 0 ? null : {
3184
- ...history,
3185
- references: history.references.slice(0, index)
3186
- });
3187
- if (key !== void 0) revealRow(key);
3188
- locateChat(target);
3189
- };
3190
- (0, react.useLayoutEffect)(() => {
3191
- if (pickedRow === void 0 || appliedPick.current === pickedRow || !allRows.some((row) => row.key === pickedRow.key)) return;
3192
- appliedPick.current = pickedRow;
3193
- setObjectHistory(null);
3194
- revealRow(pickedRow.key);
3195
- }, [
3196
- pickedRow,
3197
- allRows,
3198
- revealRow
3199
- ]);
3200
- const hierarchy = (0, react.useMemo)(() => new InspectorTableHierarchy(filtered.rows, disclosures), [filtered.rows, disclosures]);
3201
- const rows = hierarchy.rows;
3202
- const committed = (0, react.useRef)();
3203
- 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), [
3204
- hierarchy,
3205
- disclosures,
3206
- spacingGeneration
3207
- ]);
3208
- const anchoredOffset = committed.current?.layout !== layout ? layout.scrollOffset : void 0;
3209
- const seen = (0, react.useRef)(/* @__PURE__ */ new Map());
3210
- const initialized = (0, react.useRef)(false);
3211
- const arrivals = (0, react.useMemo)(() => {
3212
- const now = performance.now();
3213
- const next = new Map(allRows.map((row) => [row.key, seen.current.get(row.key) ?? (initialized.current ? now : -Infinity)]));
3214
- if (allRows.length > 0) initialized.current = true;
3215
- seen.current = next;
3216
- return next;
3217
- }, [allRows]);
3218
- const keyOf = (0, react.useCallback)((index) => layout.items[index].key, [layout]);
3219
- const sizeOf = (0, react.useCallback)((index) => layout.items[index].size, [layout]);
3220
- const virtualRef = (0, react.useRef)();
3221
- const extractRange = (0, react.useCallback)((range) => {
3222
- const offset = anchoredOffset ?? virtualRef.current.scrollOffset;
3223
- const visible = anchoredOffset === void 0 ? range : {
3224
- ...range,
3225
- startIndex: Math.max(0, Math.floor(offset / 30) - 1),
3226
- endIndex: Math.min(range.count - 1, Math.ceil((offset + viewport.current.height) / 30) - 1)
3227
- };
3228
- return [...new Set([...layout.stickyIndexesAtOffset(offset), ...(0, _tanstack_react_virtual.defaultRangeExtractor)(visible)])].sort((left, right) => left - right);
3229
- }, [layout, anchoredOffset]);
3230
- const virtual = (0, _tanstack_react_virtual.useVirtualizer)({
3231
- count: layout.items.length,
3232
- getScrollElement: () => scroller.current,
3233
- estimateSize: sizeOf,
3234
- getItemKey: keyOf,
3235
- overscan: 12,
3236
- initialRect: {
3237
- width: 0,
3238
- height: 600
3239
- },
3240
- anchorTo: layout.scrollOffset !== void 0 || followMode.current === "manual" ? "start" : "end",
3241
- scrollEndThreshold: 40,
3242
- paddingStart: 30,
3243
- scrollPaddingStart: 30,
3244
- rangeExtractor: extractRange,
3245
- paddingEnd: layout.bottomPadding
3246
- });
3247
- virtualRef.current = virtual;
3248
- const viewportHeight = virtual.scrollRect?.height;
3249
- const applyTypeFilter = (query) => {
3250
- followMode.current = "scroll";
3251
- setTypeQuery(new InspectorTypeFilter(query).query);
3252
- setDisclosures(/* @__PURE__ */ new Map());
3253
- resetSpacing((value) => value + 1);
3254
- setSelected(null);
3255
- setObjectHistory(null);
3256
- setReveal(null);
3257
- virtual.scrollToOffset(0);
3258
- };
3259
- (0, react.useLayoutEffect)(() => {
3260
- if (anchoredOffset !== void 0) virtual.scrollToOffset(anchoredOffset);
3261
- else if (followMode.current === "tail" && layout.bottomPadding === 0) virtual.scrollToEnd();
3262
- viewport.current = {
3263
- offset: scroller.current.scrollTop,
3264
- height: viewportHeight ?? 600
3265
- };
3266
- disclosureAnchor.current = void 0;
3267
- committed.current = {
3268
- layout,
3269
- disclosures,
3270
- spacingGeneration
3271
- };
3272
- }, [
3273
- virtual,
3274
- layout,
3275
- disclosures,
3276
- spacingGeneration,
3277
- viewportHeight,
3278
- anchoredOffset
3279
- ]);
3280
- (0, react.useLayoutEffect)(() => {
3281
- if (reveal === null || appliedReveal.current === reveal) return;
3282
- const index = layout.items.findIndex((item) => item.key === reveal.key);
3283
- if (index === -1) return;
3284
- virtual.scrollToIndex(index, { align: "center" });
3285
- appliedReveal.current = reveal;
3286
- }, [
3287
- layout,
3288
- reveal,
3289
- virtual
3290
- ]);
3291
- const items = virtual.getVirtualItems();
3292
- const sticky = new Map(layout.stickyIndexesAtOffset(anchoredOffset ?? virtual.scrollOffset).map((index, level) => [index, level]));
3293
- const lastItem = items.at(-1);
3294
- const bottom = lastItem === void 0 ? 0 : Math.max(0, virtual.getTotalSize() - lastItem.end);
3295
- const detail = (0, react.useMemo)(() => inspectorJson(objects === void 0 ? record?.value : void 0), [record, objects]);
3296
- const detailValue = objectTarget === void 0 ? record?.value : objectTarget.read();
3297
- const breadcrumbs = [objectHistory?.rootLabel ?? rowLabel, ...objectHistory?.references.map((reference) => `${t(`object.${reference.kind}`)} · ${reference.identity}`) ?? []];
3298
- const columns = showTime ? 5 : 4;
3299
- return (0, react_jsx_runtime.jsxs)("section", {
3300
- className: inspector_module_css_default.root,
3301
- "aria-label": title,
3302
- children: [
3303
- (0, react_jsx_runtime.jsxs)("div", {
3304
- className: inspector_module_css_default.toolbar,
3305
- children: [
3306
- (0, react_jsx_runtime.jsxs)("span", { children: [
3307
- modeSelector ?? title,
3308
- " · ",
3309
- typeFilter.active ? `${filtered.matches.size} / ${allRows.length}` : allRows.length
3310
- ] }),
3311
- hasMore && (0, react_jsx_runtime.jsx)("button", {
3312
- type: "button",
3313
- disabled: loading,
3314
- onClick: () => {
3315
- followMode.current = "scroll";
3316
- setFailure(null);
3317
- loadOlder().catch((error) => {
3318
- setFailure(String(error));
3319
- });
3320
- },
3321
- children: loading ? t("table.loading") : t("table.older")
3322
- }),
3323
- (0, react_jsx_runtime.jsx)("button", {
3324
- type: "button",
3325
- onClick: () => {
3326
- followMode.current = "tail";
3327
- resetSpacing((value) => value + 1);
3328
- },
3329
- children: t("table.latest")
3330
- })
3331
- ]
3332
- }),
3333
- notice !== void 0 && (0, react_jsx_runtime.jsx)("div", {
3334
- className: inspector_module_css_default.pickNotice,
3335
- role: "status",
3336
- children: notice
3337
- }),
3338
- (failure !== null || openError !== null) && (0, react_jsx_runtime.jsx)("p", {
3339
- role: "alert",
3340
- children: failure ?? openError?.message
3341
- }),
3342
- (0, react_jsx_runtime.jsxs)("div", {
3343
- ref: scroller,
3344
- className: inspector_module_css_default.scroller,
3345
- onScroll: ({ currentTarget }) => {
3346
- viewport.current.offset = currentTarget.scrollTop;
3347
- if (followMode.current !== "manual") followMode.current = currentTarget.scrollHeight - currentTarget.clientHeight - currentTarget.scrollTop <= 40 ? "tail" : "scroll";
3348
- },
3349
- children: [(0, react_jsx_runtime.jsxs)("table", {
3350
- className: inspector_module_css_default.table,
3351
- "aria-label": title,
3352
- "aria-rowcount": rows.length + 1,
3353
- children: [(0, react_jsx_runtime.jsx)("thead", { children: (0, react_jsx_runtime.jsxs)("tr", { children: [
3354
- (0, react_jsx_runtime.jsx)("th", {
3355
- className: inspector_module_css_default.idColumn,
3356
- children: t("table.id")
3357
- }),
3358
- (0, react_jsx_runtime.jsx)("th", {
3359
- className: inspector_module_css_default.typeColumn,
3360
- children: (0, react_jsx_runtime.jsxs)("span", {
3361
- className: inspector_module_css_default.typeHeader,
3362
- children: [t("table.type"), (0, react_jsx_runtime.jsx)(TypeFilter, {
3363
- value: typeQuery,
3364
- suggest: suggestTypes,
3365
- apply: applyTypeFilter,
3366
- t
3367
- })]
3368
- })
3369
- }),
3370
- (0, react_jsx_runtime.jsx)("th", {
3371
- className: inspector_module_css_default.locationColumn,
3372
- children: t("table.location")
3373
- }),
3374
- showTime && (0, react_jsx_runtime.jsx)("th", {
3375
- className: inspector_module_css_default.timeColumn,
3376
- children: t("table.time")
3377
- }),
3378
- (0, react_jsx_runtime.jsx)("th", { children: t("table.data") })
3379
- ] }) }), (0, react_jsx_runtime.jsxs)("tbody", { children: [items.map((item, position) => {
3380
- const gap = item.start - (items[position - 1]?.end ?? 30);
3381
- const entry = layout.items[item.index];
3382
- const arrival = arrivals.get(entry.row.key);
3383
- return (0, react_jsx_runtime.jsxs)(react.Fragment, { children: [gap > 0 && (0, react_jsx_runtime.jsx)("tr", {
3384
- "aria-hidden": "true",
3385
- children: (0, react_jsx_runtime.jsx)("td", {
3386
- colSpan: columns,
3387
- style: {
3388
- height: gap,
3389
- padding: 0
3390
- }
3391
- })
3392
- }), (0, react_jsx_runtime.jsx)(DataRow, {
3393
- row: entry.row,
3394
- selected: entry.row.key === selected,
3395
- context: typeFilter.active && !filtered.matches.has(entry.row.key),
3396
- branch: hierarchy.isBranch(entry.row.key),
3397
- collapsed: inspectorRowCollapsed(entry.row, disclosures),
3398
- stickyLevel: sticky.get(item.index),
3399
- pulse: reveal?.key === entry.row.key ? reveal.pulse : 0,
3400
- added: performance.now() - arrival < 700,
3401
- useRecord,
3402
- select,
3403
- toggle,
3404
- flash,
3405
- showTime,
3406
- t
3407
- })] }, item.key);
3408
- }), bottom > 0 && (0, react_jsx_runtime.jsx)("tr", {
3409
- "aria-hidden": "true",
3410
- "data-inspector-fold-space": layout.bottomPadding > 0 ? "" : void 0,
3411
- children: (0, react_jsx_runtime.jsx)("td", {
3412
- colSpan: columns,
3413
- style: {
3414
- height: bottom,
3415
- padding: 0
3416
- }
3417
- })
3418
- })] })]
3419
- }), rows.length === 0 && (0, react_jsx_runtime.jsx)("p", {
3420
- className: inspector_module_css_default.empty,
3421
- children: t("table.empty")
3422
- })]
3423
- }),
3424
- selected !== null && (0, react_jsx_runtime.jsx)(InspectorDetails, {
3425
- failed: detail.failed,
3426
- text: record === void 0 ? t("table.removed") : detail.failed ? `${t("table.rawError")}\n${detail.text}` : detail.text,
3427
- close: () => {
3428
- setSelected(null);
3429
- setObjectHistory(null);
3430
- },
3431
- t,
3432
- children: objects === void 0 ? record === void 0 || detail.failed ? void 0 : (0, react_jsx_runtime.jsx)(InspectorJsonTree, {
3433
- text: detail.text,
3434
- t
3435
- }, selected) : (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [(0, react_jsx_runtime.jsx)("nav", {
3436
- className: inspector_module_css_default.objectBreadcrumbs,
3437
- "aria-label": t("object.navigation"),
3438
- 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", {
3439
- "aria-hidden": "true",
3440
- children: "›"
3441
- }), (0, react_jsx_runtime.jsx)("button", {
3442
- type: "button",
3443
- title: label,
3444
- disabled: index === breadcrumbs.length - 1,
3445
- "aria-current": index === breadcrumbs.length - 1 ? "page" : void 0,
3446
- onClick: () => {
3447
- backToObject(index);
3448
- },
3449
- children: label
3450
- })] }, index)) })
3451
- }), (0, react_jsx_runtime.jsx)(InspectorObjectTree, {
3452
- value: detailValue,
3453
- objects,
3454
- navigate,
3455
- t
3456
- }, objectTarget?.id ?? selected)] })
3457
- })
3458
- ]
3459
- });
3460
- }
3461
- //#endregion
3462
- //#region lib/types/client/views/chat-node/highlight.js
3463
- /** Clipping geometry for the Inspector's element-picker overlay outside the Chat subtree. */
3464
- /**
3465
- * Intersect a Chat box with its scrollports and the transcript area above the composer.
3466
- * @param element - Existing Chat Node, call, or Group box.
3467
- * @returns The visible rectangle, or undefined when the target is outside the conversation viewport.
3468
- */
3469
- function visibleChatRect(element) {
3470
- const rect = element.getBoundingClientRect();
3471
- let left = Math.max(0, rect.left), right = Math.min(window.innerWidth, rect.right);
3472
- let top = Math.max(0, rect.top), bottom = Math.min(window.innerHeight, rect.bottom);
3473
- for (let parent = element.parentElement; parent !== null; parent = parent.parentElement) {
3474
- if (!parent.matches("[data-conversation-scroll], [data-step-process-body]")) continue;
3475
- const bounds = parent.getBoundingClientRect();
3476
- left = Math.max(left, bounds.left);
3477
- right = Math.min(right, bounds.right);
3478
- top = Math.max(top, bounds.top);
3479
- bottom = Math.min(bottom, bounds.bottom);
3480
- if (parent.hasAttribute("data-conversation-scroll")) {
3481
- const composer = parent.querySelector(":scope > [data-composer-seat]")?.getBoundingClientRect();
3482
- if (composer !== void 0 && composer.height > 0) bottom = Math.min(bottom, composer.top);
3483
- }
3484
- }
3485
- return bottom <= top || right <= left ? void 0 : {
3486
- left,
3487
- top,
3488
- width: right - left,
3489
- height: bottom - top
3490
- };
3491
- }
3492
- /**
3493
- * Place an Inspector overlay without changing the Chat content box.
3494
- * @param overlay - Inspector-owned fixed-position element.
3495
- * @param element - Existing Chat Node, call, or Group box.
3496
- * @returns Whether any part of the target remains visible after clipping.
3497
- */
3498
- function placeChatHighlight(overlay, element) {
3499
- const rect = visibleChatRect(element);
3500
- if (rect === void 0) return false;
3501
- Object.assign(overlay.style, {
3502
- left: `${rect.left}px`,
3503
- top: `${rect.top}px`,
3504
- width: `${rect.width}px`,
3505
- height: `${rect.height}px`
3506
- });
3507
- return true;
3508
- }
3509
- //#endregion
3510
- //#region lib/types/client/views/chat-node/reveal.js
3511
- /** Inspector-owned DOM reveal and native scrolling, without a Conversation request channel. */
3512
- const SCROLL_QUIET_MS = 150;
3513
- const SCROLL_KEYS = new Set([
3514
- "ArrowUp",
3515
- "ArrowDown",
3516
- "PageUp",
3517
- "PageDown",
3518
- "Home",
3519
- "End",
3520
- " ",
3521
- "Escape"
3522
- ]);
3523
- function hasRenderedBox(element) {
3524
- if (!displayed(element)) return false;
3525
- const box = element.getBoundingClientRect();
3526
- return box.width > 0 && box.height > 0;
3527
- }
3528
- /** Owns one deferred reveal and body-level flash, without modifying Chat content nodes. */
3529
- var InspectorChatRevealer = class {
3530
- getRoot;
3531
- frame;
3532
- overlay;
3533
- animation;
3534
- cancelScroll;
3535
- /** @param getRoot - Current Session's main Chat, or undefined when it is not displayed. */
3536
- constructor(getRoot) {
3537
- this.getRoot = getRoot;
3538
- }
3539
- /**
3540
- * Reveal the first usable occurrence, falling back to the displayed Chat column.
3541
- * Hidden or empty candidates do not prevent nearby content from being highlighted.
3542
- * The highlight waits for scrolling to settle; reduced-motion mode scrolls immediately without a flash.
3543
- * @param targets - Exact and approximate Node, Group, or Turn identities in preference order.
3544
- */
3545
- reveal(targets) {
3546
- this.dispose();
3547
- this.frame = requestAnimationFrame(() => {
3548
- this.frame = void 0;
3549
- const root = this.getRoot();
3550
- if (root === void 0) return;
3551
- for (const initial of findChatTargets(root, targets)) {
3552
- if (!root.contains(initial)) continue;
3553
- const hidden = [];
3554
- for (let element = initial; element !== null && element !== root; element = element.parentElement) if (element.getAttribute("hidden") === "until-found") hidden.push(element);
3555
- if (hidden.length > 0 || visibleChatRect(initial) === void 0) root.closest("[data-conversation-scroll]")?.dispatchEvent(new Event("beforematch"));
3556
- for (const element of hidden.reverse()) (0, react_dom.flushSync)(() => {
3557
- element.dispatchEvent(new Event("beforematch"));
3558
- });
3559
- if (this.getRoot() !== root) return;
3560
- const row = root.contains(initial) ? initial : findChatTargets(root, targets).find(hasRenderedBox);
3561
- if (row === void 0 || !hasRenderedBox(row)) continue;
3562
- if (visibleChatRect(row) === void 0) {
3563
- if (!window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
3564
- this.smoothScroll(row, root, targets);
3565
- return;
3566
- }
3567
- row.scrollIntoView({
3568
- behavior: "instant",
3569
- block: "center",
3570
- inline: "nearest"
3571
- });
3572
- }
3573
- this.queueFlash(row, root, targets);
3574
- return;
3575
- }
3576
- if (displayed(root) && visibleChatRect(root) !== void 0) this.queueFlash(root, root, targets);
3577
- });
3578
- }
3579
- /** Cancel pending native scrolling and remove the Inspector-owned overlay. */
3580
- dispose() {
3581
- if (this.frame !== void 0) cancelAnimationFrame(this.frame);
3582
- this.frame = void 0;
3583
- this.cancelScroll?.();
3584
- if (this.animation !== void 0) {
3585
- this.animation.onfinish = null;
3586
- this.animation.cancel();
3587
- }
3588
- this.animation = void 0;
3589
- this.overlay?.remove();
3590
- this.overlay = void 0;
3591
- }
3592
- queueFlash(row, root, targets) {
3593
- this.frame = requestAnimationFrame(() => {
3594
- this.frame = void 0;
3595
- if (this.getRoot() !== root) {
3596
- this.dispose();
3597
- return;
3598
- }
3599
- if (this.flash(row)) return;
3600
- for (const candidate of findChatTargets(root, targets)) if (candidate !== row && this.flash(candidate)) return;
3601
- if (row !== root && this.flash(root)) return;
3602
- this.dispose();
3603
- });
3604
- }
3605
- smoothScroll(row, root, targets) {
3606
- const parents = /* @__PURE__ */ new Set();
3607
- for (let element = row.parentElement; element !== null; element = element.parentElement) parents.add(element);
3608
- const moving = /* @__PURE__ */ new Set();
3609
- let pending = true;
3610
- let quiet;
3611
- let settledFrame;
3612
- const targetOf = (event) => {
3613
- const target = event.target === document ? document.scrollingElement : event.target;
3614
- return target instanceof Element && parents.has(target) ? target : void 0;
3615
- };
3616
- const cleanup = () => {
3617
- pending = false;
3618
- window.clearTimeout(quiet);
3619
- if (settledFrame !== void 0) cancelAnimationFrame(settledFrame);
3620
- window.removeEventListener("scroll", onScroll, true);
3621
- window.removeEventListener("scrollend", onEnd, true);
3622
- for (const type of [
3623
- "wheel",
3624
- "touchstart",
3625
- "pointerdown",
3626
- "keydown"
3627
- ]) window.removeEventListener(type, interrupt, true);
3628
- this.cancelScroll = void 0;
3629
- };
3630
- const finish = () => {
3631
- if (!pending) return;
3632
- cleanup();
3633
- this.queueFlash(row, root, targets);
3634
- };
3635
- const awaitQuiet = () => {
3636
- window.clearTimeout(quiet);
3637
- quiet = window.setTimeout(finish, SCROLL_QUIET_MS);
3638
- };
3639
- const onScroll = (event) => {
3640
- const target = targetOf(event);
3641
- if (target === void 0) return;
3642
- moving.add(target);
3643
- awaitQuiet();
3644
- };
3645
- const onEnd = (event) => {
3646
- const target = targetOf(event);
3647
- if (target === void 0 || !moving.delete(target) || moving.size > 0 || settledFrame !== void 0) return;
3648
- settledFrame = requestAnimationFrame(() => {
3649
- settledFrame = void 0;
3650
- if (moving.size === 0) finish();
3651
- });
3652
- };
3653
- const cancel = () => {
3654
- if (!pending) return;
3655
- cleanup();
3656
- for (const element of parents) if (element.isConnected && (element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth)) element.scrollTo({
3657
- top: element.scrollTop,
3658
- left: element.scrollLeft,
3659
- behavior: "instant"
3660
- });
3661
- };
3662
- const interrupt = (event) => {
3663
- if (event instanceof KeyboardEvent && !SCROLL_KEYS.has(event.key)) return;
3664
- cancel();
3665
- this.dispose();
3666
- };
3667
- this.cancelScroll = cancel;
3668
- window.addEventListener("scroll", onScroll, {
3669
- capture: true,
3670
- passive: true
3671
- });
3672
- window.addEventListener("scrollend", onEnd, {
3673
- capture: true,
3674
- passive: true
3675
- });
3676
- for (const type of [
3677
- "wheel",
3678
- "touchstart",
3679
- "pointerdown",
3680
- "keydown"
3681
- ]) window.addEventListener(type, interrupt, {
3682
- capture: true,
3683
- passive: true
3684
- });
3685
- awaitQuiet();
3686
- row.scrollIntoView({
3687
- behavior: "smooth",
3688
- block: "center",
3689
- inline: "nearest"
3690
- });
3691
- }
3692
- flash(row) {
3693
- if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
3694
- this.dispose();
3695
- return true;
3696
- }
3697
- if (!displayed(row)) return false;
3698
- const overlay = document.createElement("div");
3699
- if (!placeChatHighlight(overlay, row)) return false;
3700
- overlay.className = inspector_module_css_default.chatReveal;
3701
- overlay.dataset.sessionInspectorHighlight = "reveal";
3702
- overlay.setAttribute("aria-hidden", "true");
3703
- document.body.append(overlay);
3704
- this.overlay = overlay;
3705
- const animation = overlay.animate([
3706
- { opacity: .65 },
3707
- { opacity: .1 },
3708
- { opacity: .5 },
3709
- { opacity: 0 }
3710
- ], { duration: 700 });
3711
- this.animation = animation;
3712
- animation.onfinish = () => {
3713
- if (this.animation === animation) this.dispose();
3714
- };
3715
- return true;
3716
- }
3717
- };
3718
- //#endregion
3719
- //#region lib/types/client/views/View.js
3720
- /** One Sidebar Inspector with locally selected Chat and Session-log presentations. */
3721
- /** @param props - Session-bound sources. @returns One Inspector with an in-toolbar presentation selector. */
3722
- function SessionInspectorView(props) {
3723
- const [mode, setMode] = (0, react.useState)("session-log");
3724
- const [picking, setPicking] = (0, react.useState)(false);
3725
- const [pickFailed, setPickFailed] = (0, react.useState)(false);
3726
- const [pickedRow, setPickedRow] = (0, react.useState)();
3727
- const pickButton = (0, react.useRef)(null);
3728
- const chat = mode === "chat-node";
3729
- const revealer = (0, react.useMemo)(() => new InspectorChatRevealer(props.chatRoot), [props.chatRoot]);
3730
- (0, react.useEffect)(() => () => {
3731
- revealer.dispose();
3732
- }, [revealer, mode]);
3733
- const typeOf = (0, react.useCallback)((key) => props.recordType(key, mode), [props.recordType, mode]);
3734
- const revealChat = (0, react.useCallback)((target) => {
3735
- revealer.reveal(props.resolveChatTargets(target));
3736
- }, [revealer, props.resolveChatTargets]);
3737
- const navigation = (0, react.useMemo)(() => ({
3738
- reveal: revealChat,
3739
- target: chat ? (key) => props.objects.row(key)?.target : props.logChatTarget
3740
- }), [
3741
- chat,
3742
- props.objects,
3743
- props.logChatTarget,
3744
- revealChat
3745
- ]);
3746
- (0, react.useEffect)(() => {
3747
- if (!picking || pickButton.current === null) return;
3748
- revealer.dispose();
3749
- const stopPicking = props.pickChat(pickButton.current, (target) => {
3750
- const key = props.pickRow(target, mode);
3751
- if (key === void 0) {
3752
- setPickFailed(true);
3753
- return false;
3754
- }
3755
- setPickedRow({ key });
3756
- setPicking(false);
3757
- setPickFailed(false);
3758
- return true;
3759
- }, () => {
3760
- setPicking(false);
3761
- setPickFailed(false);
3762
- });
3763
- if (stopPicking === void 0) {
3764
- setPicking(false);
3765
- setPickFailed(true);
3766
- }
3767
- return stopPicking;
3768
- }, [
3769
- picking,
3770
- mode,
3771
- props.pickChat,
3772
- props.pickRow,
3773
- revealer
3774
- ]);
3775
- const selector = (0, react_jsx_runtime.jsxs)("span", {
3776
- className: inspector_module_css_default.modeControls,
3777
- children: [(0, react_jsx_runtime.jsxs)("select", {
3778
- className: inspector_module_css_default.modeSelector,
3779
- "aria-label": props.t("view.presentation"),
3780
- value: mode,
3781
- onChange: (event) => {
3782
- setPicking(false);
3783
- setPickFailed(false);
3784
- setPickedRow(void 0);
3785
- setMode(event.currentTarget.value === "chat-node" ? "chat-node" : "session-log");
3786
- },
3787
- children: [(0, react_jsx_runtime.jsx)("option", {
3788
- value: "session-log",
3789
- children: props.t("view.sessionLog")
3790
- }), (0, react_jsx_runtime.jsx)("option", {
3791
- value: "chat-node",
3792
- children: props.t("view.chatNode")
3793
- })]
3794
- }), (0, react_jsx_runtime.jsx)("button", {
3795
- ref: pickButton,
3796
- type: "button",
3797
- className: inspector_module_css_default.pickButton,
3798
- "aria-pressed": picking,
3799
- "aria-label": props.t("picker.pick"),
3800
- title: props.t(picking ? "picker.cancel" : "picker.pick"),
3801
- onClick: () => {
3802
- setPickFailed(false);
3803
- setPicking((value) => !value);
3804
- },
3805
- children: (0, react_jsx_runtime.jsxs)("svg", {
3806
- width: "16",
3807
- height: "16",
3808
- viewBox: "0 0 16 16",
3809
- fill: "none",
3810
- stroke: "currentColor",
3811
- strokeWidth: "1.3",
3812
- "aria-hidden": "true",
3813
- children: [(0, react_jsx_runtime.jsx)("circle", {
3814
- cx: "8",
3815
- cy: "8",
3816
- r: "4.5"
3817
- }), (0, react_jsx_runtime.jsx)("path", { d: "M8 0v5M8 11v5M0 8h5M11 8h5" })]
3818
- })
3819
- })]
3820
- });
3821
- return (0, react_jsx_runtime.jsx)(InspectorTable, {
3822
- title: props.t(chat ? "view.chatNode" : "view.sessionLog"),
3823
- modeSelector: selector,
3824
- pickedRow,
3825
- notice: picking ? props.t(pickFailed ? "picker.noMatch" : "picker.instructions") : pickFailed ? props.t("picker.noChat") : void 0,
3826
- useRows: chat ? props.useChatRows : props.useLogRows,
3827
- useRecord: chat ? props.useChatRecord : props.useLogRecord,
3828
- useSession: props.useSession,
3829
- loadOlder: props.loadOlder,
3830
- typeOf,
3831
- t: props.t,
3832
- flash: chat,
3833
- showTime: !chat,
3834
- navigation,
3835
- ...chat ? { objects: props.objects } : {}
3836
- }, mode);
3837
- }
3838
- //#endregion
3839
- //#region lib/types/client/views/chat-node/reveal-target.js
3840
- /** Precise and nearby Chat reveal candidates from the Inspector's loaded Chat snapshot. */
3841
- function nearest(nodes, seq) {
3842
- let best;
3843
- for (const node of nodes) if (best === void 0 || Math.abs(node.anchorSeq - seq) < Math.abs(best.anchorSeq - seq)) best = node;
3844
- return best;
3845
- }
3846
- function primaryTarget(target, visible) {
3847
- if (target.nodeKey !== void 0 || target.anchorSeq === void 0) return target;
3848
- const inTurn = target.turn === void 0 ? visible : visible.filter((node) => (node.location.kind === "turn" || node.location.kind === "step") && node.location.turn.turn === target.turn);
3849
- const inStep = target.step === void 0 ? inTurn : inTurn.filter((node) => node.location.kind === "step" && node.location.step.step === target.step);
3850
- const rootCallId = target.rootCallId ?? target.callId;
3851
- const tool = rootCallId === void 0 ? void 0 : visible.find((node) => node.kind === "tool-call" && node.data.root.callId === rootCallId);
3852
- const exact = inStep.find((node) => node.anchorSeq === target.anchorSeq);
3853
- const kind = target.nodeKind === void 0 ? void 0 : inStep.find((node) => node.kind === target.nodeKind);
3854
- const node = tool ?? exact ?? kind ?? nearest(inStep, target.anchorSeq) ?? nearest(inTurn, target.anchorSeq);
3855
- if (node === void 0) return target;
3856
- const turn = target.turn ?? (node.location.kind === "turn" || node.location.kind === "step" ? node.location.turn.turn : void 0);
3857
- return {
3858
- ...target,
3859
- nodeKey: node.key,
3860
- ...turn === void 0 ? {} : { turn }
3861
- };
3862
- }
3863
- function nodeTarget(node) {
3864
- const location = node.location;
3865
- return {
3866
- nodeKey: node.key,
3867
- anchorSeq: node.anchorSeq,
3868
- ...location.kind === "turn" || location.kind === "step" ? { turn: location.turn.turn } : {},
3869
- ...location.kind === "step" ? { step: location.step.step } : {}
3870
- };
3871
- }
3872
- function targetKey(target) {
3873
- return JSON.stringify([
3874
- target.anchorSeq,
3875
- target.callId,
3876
- target.rootCallId,
3877
- target.nodeKey,
3878
- target.nodeKind,
3879
- target.groupKey,
3880
- target.groupPart,
3881
- target.turn,
3882
- target.step
3883
- ]);
3884
- }
3885
- /**
3886
- * Preserve the primary identity or tool/exact/kind/nearest placement, then rank visible neighbors.
3887
- * Explicit-node primaries include missing model coordinates, even when the node is hidden.
3888
- * Request coordinates take precedence over the node's position.
3889
- * Without a known anchor sequence, only the original target is returned.
3890
- * @param target - Object identity or original event coordinates supplied by another View.
3891
- * @param nodes - Current Session's loaded Chat nodes; equal-distance candidates retain input order.
3892
- * @returns Primary target followed by distinct Step, Turn, and Session neighbors with only node coordinates.
3893
- */
3894
- function resolveChatRevealTargets(target, nodes) {
3895
- const visible = nodes.filter((node) => node.visibility === "visible");
3896
- const explicit = target.nodeKey === void 0 ? void 0 : nodes.find((node) => node.key === target.nodeKey);
3897
- const position = explicit === void 0 ? void 0 : nodeTarget(explicit);
3898
- const referenceSeq = target.anchorSeq ?? position?.anchorSeq;
3899
- const turn = target.turn ?? position?.turn;
3900
- const step = target.step ?? position?.step;
3901
- const primary = position === void 0 ? primaryTarget(target, visible) : {
3902
- ...target,
3903
- anchorSeq: target.anchorSeq ?? position.anchorSeq,
3904
- ...turn === void 0 ? {} : { turn },
3905
- ...step === void 0 ? {} : { step }
3906
- };
3907
- if (referenceSeq === void 0) return [primary];
3908
- const rank = (candidate) => {
3909
- const sameTurn = turn === void 0 || candidate.turn === turn;
3910
- if (sameTurn && step !== void 0 && candidate.step === step) return 0;
3911
- return sameTurn && turn !== void 0 ? 1 : 2;
3912
- };
3913
- const neighbors = visible.map(nodeTarget).sort((left, right) => rank(left) - rank(right) || Math.abs(left.anchorSeq - referenceSeq) - Math.abs(right.anchorSeq - referenceSeq));
3914
- const candidates = [primary];
3915
- const seen = new Set([targetKey(primary)]);
3916
- for (const candidate of neighbors) {
3917
- const key = targetKey(candidate);
3918
- if (seen.has(key)) continue;
3919
- seen.add(key);
3920
- candidates.push(candidate);
3921
- }
3922
- return candidates;
3923
- }
3924
- //#endregion
3925
- //#region lib/types/client/views/chat-node/picker.js
3926
- /** One-shot Inspector picking through a real click-catching mask over the main Chat. */
3927
- const POINTER_ACTIONS = [
3928
- "pointerdown",
3929
- "pointerup",
3930
- "mousedown",
3931
- "mouseup",
3932
- "auxclick",
3933
- "dblclick",
3934
- "contextmenu"
3935
- ];
3936
- /** Owns the mask, preview, and geometry observers for one picking gesture. */
3937
- var InspectorChatPicker = class {
3938
- getRoot;
3939
- owner;
3940
- picked;
3941
- cancelled;
3942
- released;
3943
- mask;
3944
- overlay;
3945
- root;
3946
- observing;
3947
- resizing;
3948
- /**
3949
- * @param getRoot - Current Session's displayed main Chat.
3950
- * @param owner - Inspector button; hiding or removing it cancels picking.
3951
- * @param picked - True completes selection; false keeps the mask for another pick.
3952
- * @param cancelled - Clear the owning panel's picking state.
3953
- * @param released - Forget this gesture after its DOM resources are released.
3954
- */
3955
- constructor(getRoot, owner, picked, cancelled, released) {
3956
- this.getRoot = getRoot;
3957
- this.owner = owner;
3958
- this.picked = picked;
3959
- this.cancelled = cancelled;
3960
- this.released = released;
3961
- }
3962
- /**
3963
- * Begin picking in the visible main Chat.
3964
- * @returns Whether a visible Chat was found and its mask installed.
3965
- */
3966
- start() {
3967
- const root = this.getRoot();
3968
- if (root === void 0 || !displayed(root) || !displayed(this.owner)) return false;
3969
- const mask = document.createElement("div");
3970
- if (!placeChatHighlight(mask, root)) return false;
3971
- mask.className = inspector_module_css_default.chatPickMask;
3972
- mask.dataset.sessionInspectorPicker = "";
3973
- mask.setAttribute("aria-hidden", "true");
3974
- this.root = root;
3975
- this.mask = mask;
3976
- mask.addEventListener("pointermove", this.move);
3977
- mask.addEventListener("pointerleave", this.hide);
3978
- mask.addEventListener("click", this.click);
3979
- mask.addEventListener("wheel", this.wheel, { passive: false });
3980
- for (const type of POINTER_ACTIONS) mask.addEventListener(type, this.suppress);
3981
- document.body.append(mask);
3982
- window.addEventListener("keydown", this.keydown, true);
3983
- window.addEventListener("blur", this.cancel);
3984
- window.addEventListener("scroll", this.position, true);
3985
- window.addEventListener("resize", this.position);
3986
- this.observing = new MutationObserver(this.verify);
3987
- for (const start of [this.owner, root]) for (let element = start; element !== null; element = element.parentElement) this.observing.observe(element, {
3988
- attributes: true,
3989
- attributeFilter: [
3990
- "hidden",
3991
- "style",
3992
- "class"
3993
- ],
3994
- childList: true
3995
- });
3996
- if (typeof ResizeObserver !== "undefined") {
3997
- this.resizing = new ResizeObserver(this.position);
3998
- this.resizing.observe(root);
3999
- }
4000
- return true;
4001
- }
4002
- /** Remove the mask and observers without calling panel callbacks during unmount. */
4003
- dispose() {
4004
- const mask = this.mask;
4005
- if (mask !== void 0) {
4006
- mask.removeEventListener("pointermove", this.move);
4007
- mask.removeEventListener("pointerleave", this.hide);
4008
- mask.removeEventListener("click", this.click);
4009
- mask.removeEventListener("wheel", this.wheel);
4010
- for (const type of POINTER_ACTIONS) mask.removeEventListener(type, this.suppress);
4011
- mask.remove();
4012
- }
4013
- this.mask = void 0;
4014
- this.root = void 0;
4015
- window.removeEventListener("keydown", this.keydown, true);
4016
- window.removeEventListener("blur", this.cancel);
4017
- window.removeEventListener("scroll", this.position, true);
4018
- window.removeEventListener("resize", this.position);
4019
- this.observing?.disconnect();
4020
- this.observing = void 0;
4021
- this.resizing?.disconnect();
4022
- this.resizing = void 0;
4023
- this.hide();
4024
- this.released();
4025
- }
4026
- currentRoot() {
4027
- const root = this.root;
4028
- return root !== void 0 && this.getRoot() === root && displayed(root) && displayed(this.owner) ? root : void 0;
4029
- }
4030
- position = () => {
4031
- this.hide();
4032
- this.verify();
4033
- };
4034
- verify = () => {
4035
- if (this.mask === void 0) return;
4036
- const root = this.currentRoot();
4037
- if (root === void 0 || !placeChatHighlight(this.mask, root)) this.cancel();
4038
- };
4039
- hit(event) {
4040
- if (this.mask === void 0) return void 0;
4041
- const root = this.currentRoot();
4042
- if (root === void 0) {
4043
- this.cancel();
4044
- return;
4045
- }
4046
- const element = document.elementsFromPoint(event.clientX, event.clientY).find((element) => element !== this.mask && element !== this.overlay);
4047
- return element !== void 0 && inChat(element, root) ? {
4048
- element,
4049
- root
4050
- } : void 0;
4051
- }
4052
- hide = () => {
4053
- this.overlay?.remove();
4054
- this.overlay = void 0;
4055
- };
4056
- /** Stop the gesture and clear its owning panel's picking state. */
4057
- cancel = () => {
4058
- if (this.mask === void 0) return;
4059
- this.dispose();
4060
- this.cancelled();
4061
- };
4062
- move = (event) => {
4063
- const hit = this.hit(event);
4064
- const match = hit === void 0 ? void 0 : matchChatElement(hit.element, hit.root);
4065
- if (match === void 0) {
4066
- this.hide();
4067
- return;
4068
- }
4069
- const overlay = this.overlay ?? document.createElement("div");
4070
- overlay.className = inspector_module_css_default.chatPick;
4071
- overlay.dataset.sessionInspectorHighlight = "pick";
4072
- overlay.setAttribute("aria-hidden", "true");
4073
- if (!placeChatHighlight(overlay, match.element)) {
4074
- this.hide();
4075
- return;
4076
- }
4077
- if (this.overlay === void 0) {
4078
- document.body.append(overlay);
4079
- this.overlay = overlay;
4080
- }
4081
- };
4082
- suppress = (event) => {
4083
- event.preventDefault();
4084
- event.stopImmediatePropagation();
4085
- };
4086
- click = (event) => {
4087
- this.suppress(event);
4088
- if (event.button !== 0) return;
4089
- const hit = this.hit(event);
4090
- const match = hit === void 0 ? void 0 : matchChatElement(hit.element, hit.root);
4091
- if (match !== void 0 && this.picked(match.target)) this.dispose();
4092
- };
4093
- wheel = (event) => {
4094
- this.suppress(event);
4095
- const hit = this.hit(event);
4096
- for (let element = hit?.element ?? null; element !== null; element = element.parentElement) {
4097
- if (!(element instanceof HTMLElement) || !element.matches("[data-conversation-scroll], [data-step-process-body]")) continue;
4098
- const vertical = event.deltaY < 0 ? element.scrollTop > 0 : element.scrollTop + element.clientHeight < element.scrollHeight;
4099
- const horizontal = event.deltaX < 0 ? element.scrollLeft > 0 : element.scrollLeft + element.clientWidth < element.scrollWidth;
4100
- if (!(event.deltaY !== 0 && vertical || event.deltaX !== 0 && horizontal)) continue;
4101
- const style = getComputedStyle(element);
4102
- 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;
4103
- element.scrollBy({
4104
- top: event.deltaY * scale,
4105
- left: event.deltaX * scale,
4106
- behavior: "instant"
4107
- });
4108
- break;
4109
- }
4110
- };
4111
- keydown = (event) => {
4112
- if (event.key !== "Escape") return;
4113
- this.suppress(event);
4114
- this.cancel();
4115
- };
4116
- };
4117
- //#endregion
4118
- //#region lib/types/client/views/index.js
4119
- /** Session-scoped Sidebar tab backed by the existing Chat and Session-log models. */
4120
- /**
4121
- * Register the Session Inspector Sidebar page and its Session-scoped sources.
4122
- * @param ctx - Client plugin context owning the tab registration and Session-bound model cache.
4123
- */
4124
- function registerInspectorTab(ctx) {
4125
- let activePicker;
4126
- let disposed = false;
4127
- ctx.effect(() => () => {
4128
- disposed = true;
4129
- activePicker?.dispose();
4130
- }, "session-inspector: chat picker");
4131
- const t = ctx.locale.bind(NS);
4132
- const id = "@unieai/rabi-experimental-session-inspector";
4133
- ctx.effect(() => ctx.sidebarRightTabs.register({
4134
- id,
4135
- kind: "session-inspector-log",
4136
- title: () => t("tab.title"),
4137
- guide: [{
4138
- id: "open",
4139
- order: 60,
4140
- title: () => t("tab.title"),
4141
- description: () => t("tab.description")
4142
- }]
4143
- }), "session-inspector: sidebar tab");
4144
- const models = /* @__PURE__ */ new WeakMap();
4145
- ctx.slots.inject("sidebar.right.pane.tab", () => ctx.slots.register({
4146
- name: "sidebar.right.pane.tab",
4147
- key: id,
4148
- locale: NS,
4149
- inject: (sessionId) => {
4150
- const binding = ctx.sessions.binding(sessionId);
4151
- if (binding === void 0) throw new Error(`session-inspector: unknown Session ${sessionId}`);
4152
- let sources = models.get(binding);
4153
- if (sources === void 0) {
4154
- const conversation = ctx.uiConversation.binding(binding);
4155
- const chat = new ChatNodeModel(conversation);
4156
- const log = new SessionLogModel(binding.eventSource);
4157
- const chatRoot = () => ctx.uiSession.adapter.current.getSnapshot().key === sessionId ? mainChatRoot() : void 0;
4158
- sources = {
4159
- hooks: {
4160
- chatRows: chat,
4161
- logRows: log
4162
- },
4163
- keyedHooks: {
4164
- chatRecord: chat.row,
4165
- logRecord: log.row
4166
- },
4167
- chatRoot,
4168
- pickChat: (owner, picked, cancelled) => {
4169
- if (disposed) return void 0;
4170
- activePicker?.cancel();
4171
- const picker = new InspectorChatPicker(chatRoot, owner, picked, cancelled, () => {
4172
- if (activePicker === picker) activePicker = void 0;
4173
- });
4174
- if (!picker.start()) return void 0;
4175
- activePicker = picker;
4176
- return () => {
4177
- picker.dispose();
4178
- };
4179
- },
4180
- resolveChatTargets: (target) => resolveChatRevealTargets(target, conversation.snapshot.getSnapshot().views.get("chat")?.nodes.values() ?? []),
4181
- recordType: (key, mode) => (mode === "chat-node" ? chat.row(key) : log.row(key))?.getSnapshot()?.type,
4182
- loadOlder: () => binding.session.loadOlder(),
4183
- objects: chat.objects(sessionId),
4184
- logChatTarget: (key) => {
4185
- const anchor = log.chatAnchor(key);
4186
- if (anchor === void 0) return void 0;
4187
- return sessionLogChatTarget(anchor);
4188
- },
4189
- pickRow: (target, mode) => {
4190
- if (mode === "chat-node") return chat.pick(target);
4191
- const snapshot = conversation.snapshot.getSnapshot();
4192
- const groups = snapshot.views.grouped("chat");
4193
- const reference = target.groupKey === void 0 ? void 0 : groups?.entries.find((entry) => entry.kind === "group" && entry.key === target.groupKey);
4194
- const group = reference?.kind === "group" ? groups?.groupSource(reference.key).getSnapshot() : void 0;
4195
- const nodeKey = target.nodeKey ?? group?.members[0]?.key;
4196
- const node = nodeKey === void 0 ? void 0 : snapshot.views.get("chat")?.nodes.get(nodeKey);
4197
- const location = node?.location;
4198
- return log.pick({
4199
- ...target,
4200
- ...node === void 0 ? {} : {
4201
- anchorSeq: node.anchorSeq,
4202
- nodeKind: node.kind
4203
- },
4204
- ...location?.kind === "turn" || location?.kind === "step" ? { turn: location.turn.turn } : {},
4205
- ...location?.kind === "step" ? { step: location.step.step } : {}
4206
- });
4207
- }
4208
- };
4209
- models.set(binding, sources);
4210
- }
4211
- return sources;
4212
- }
4213
- }, SessionInspectorView));
4214
- }
4215
- //#endregion
4216
- //#region lib/types/client/index.js
4217
- /** Browser plugin contributing the Session Inspector Log sidebar tab. */
4218
- /** Services required to register the localized Session-bound sidebar tab. */
4219
- const inject = [
4220
- "slots",
4221
- "locale",
4222
- "sessions",
4223
- "uiSession",
4224
- "uiConversation",
4225
- "sidebarRightTabs"
4226
- ];
4227
- /**
4228
- * Register the Inspector tab for this plugin's lifetime.
4229
- * @param ctx - Client plugin context owning the dictionaries and registrations.
4230
- */
4231
- function apply(ctx) {
4232
- ctx.effect(() => ctx.locale.register(NS, {
4233
- en,
4234
- zh
4235
- }), "session-inspector: dictionaries");
4236
- registerInspectorTab(ctx);
4237
- }
4238
- //#endregion
4239
- exports.apply = apply;
4240
- exports.inject = inject;
4241
- return module.exports;
4242
- }
4243
- });
4244
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}});