@copilotkit/web-inspector 0.0.0-main-20260402184302

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 (48) hide show
  1. package/CHANGELOG.md +473 -0
  2. package/LICENSE +21 -0
  3. package/dist/assets/inspector-logo-icon.cjs +12 -0
  4. package/dist/assets/inspector-logo-icon.cjs.map +1 -0
  5. package/dist/assets/inspector-logo-icon.mjs +6 -0
  6. package/dist/assets/inspector-logo-icon.mjs.map +1 -0
  7. package/dist/assets/inspector-logo.cjs +12 -0
  8. package/dist/assets/inspector-logo.cjs.map +1 -0
  9. package/dist/assets/inspector-logo.mjs +6 -0
  10. package/dist/assets/inspector-logo.mjs.map +1 -0
  11. package/dist/index.cjs +2881 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.cts +208 -0
  14. package/dist/index.d.cts.map +1 -0
  15. package/dist/index.d.mts +208 -0
  16. package/dist/index.d.mts.map +1 -0
  17. package/dist/index.mjs +2878 -0
  18. package/dist/index.mjs.map +1 -0
  19. package/dist/index.umd.js +3049 -0
  20. package/dist/index.umd.js.map +1 -0
  21. package/dist/lib/context-helpers.cjs +82 -0
  22. package/dist/lib/context-helpers.cjs.map +1 -0
  23. package/dist/lib/context-helpers.mjs +75 -0
  24. package/dist/lib/context-helpers.mjs.map +1 -0
  25. package/dist/lib/persistence.cjs +62 -0
  26. package/dist/lib/persistence.cjs.map +1 -0
  27. package/dist/lib/persistence.mjs +56 -0
  28. package/dist/lib/persistence.mjs.map +1 -0
  29. package/dist/styles/generated.cjs +12 -0
  30. package/dist/styles/generated.cjs.map +1 -0
  31. package/dist/styles/generated.mjs +6 -0
  32. package/dist/styles/generated.mjs.map +1 -0
  33. package/package.json +51 -0
  34. package/src/__tests__/web-inspector.spec.ts +191 -0
  35. package/src/assets/inspector-logo-icon.svg +8 -0
  36. package/src/assets/inspector-logo.svg +40 -0
  37. package/src/components.d.ts +20 -0
  38. package/src/index.ts +4364 -0
  39. package/src/lib/context-helpers.ts +166 -0
  40. package/src/lib/persistence.ts +109 -0
  41. package/src/lib/types.ts +19 -0
  42. package/src/styles/generated.css +2 -0
  43. package/src/styles/tailwind.css +23 -0
  44. package/src/types/css.d.ts +4 -0
  45. package/src/types/svg.d.ts +4 -0
  46. package/tsconfig.json +14 -0
  47. package/tsdown.config.ts +45 -0
  48. package/vitest.config.ts +10 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,2881 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_generated = require('./styles/generated.cjs');
3
+ const require_inspector_logo = require('./assets/inspector-logo.cjs');
4
+ const require_inspector_logo_icon = require('./assets/inspector-logo-icon.cjs');
5
+ const require_context_helpers = require('./lib/context-helpers.cjs');
6
+ const require_persistence = require('./lib/persistence.cjs');
7
+ let lit = require("lit");
8
+ let lit_directives_style_map_js = require("lit/directives/style-map.js");
9
+ let lit_directives_unsafe_html_js = require("lit/directives/unsafe-html.js");
10
+ let marked = require("marked");
11
+ let lucide = require("lucide");
12
+ let _copilotkit_core = require("@copilotkit/core");
13
+
14
+ //#region src/index.ts
15
+ const WEB_INSPECTOR_TAG = "cpk-web-inspector";
16
+ const EDGE_MARGIN = 16;
17
+ const DRAG_THRESHOLD = 6;
18
+ const MIN_WINDOW_WIDTH = 600;
19
+ const MIN_WINDOW_WIDTH_DOCKED_LEFT = 420;
20
+ const MIN_WINDOW_HEIGHT = 200;
21
+ const INSPECTOR_STORAGE_KEY = "cpk:inspector:state";
22
+ const ANNOUNCEMENT_STORAGE_KEY = "cpk:inspector:announcements";
23
+ const ANNOUNCEMENT_URL = "https://cdn.copilotkit.ai/announcements.json";
24
+ const DEFAULT_BUTTON_SIZE = {
25
+ width: 48,
26
+ height: 48
27
+ };
28
+ const DEFAULT_WINDOW_SIZE = {
29
+ width: 840,
30
+ height: 560
31
+ };
32
+ const DOCKED_LEFT_WIDTH = 500;
33
+ const MAX_AGENT_EVENTS = 200;
34
+ const MAX_TOTAL_EVENTS = 500;
35
+ const AGENT_EVENT_TYPES = [
36
+ "RUN_STARTED",
37
+ "RUN_FINISHED",
38
+ "RUN_ERROR",
39
+ "TEXT_MESSAGE_START",
40
+ "TEXT_MESSAGE_CONTENT",
41
+ "TEXT_MESSAGE_END",
42
+ "TOOL_CALL_START",
43
+ "TOOL_CALL_ARGS",
44
+ "TOOL_CALL_END",
45
+ "TOOL_CALL_RESULT",
46
+ "STATE_SNAPSHOT",
47
+ "STATE_DELTA",
48
+ "MESSAGES_SNAPSHOT",
49
+ "RAW_EVENT",
50
+ "CUSTOM_EVENT",
51
+ "REASONING_START",
52
+ "REASONING_MESSAGE_START",
53
+ "REASONING_MESSAGE_CONTENT",
54
+ "REASONING_MESSAGE_END",
55
+ "REASONING_END",
56
+ "REASONING_ENCRYPTED_VALUE"
57
+ ];
58
+ var WebInspectorElement = class extends lit.LitElement {
59
+ constructor(..._args) {
60
+ super(..._args);
61
+ this._core = null;
62
+ this.coreSubscriber = null;
63
+ this.coreUnsubscribe = null;
64
+ this.runtimeStatus = null;
65
+ this.coreProperties = {};
66
+ this.lastCoreError = null;
67
+ this.agentSubscriptions = /* @__PURE__ */ new Map();
68
+ this.agentEvents = /* @__PURE__ */ new Map();
69
+ this.agentMessages = /* @__PURE__ */ new Map();
70
+ this.agentStates = /* @__PURE__ */ new Map();
71
+ this.flattenedEvents = [];
72
+ this.eventCounter = 0;
73
+ this.contextStore = {};
74
+ this.pointerId = null;
75
+ this.dragStart = null;
76
+ this.dragOffset = {
77
+ x: 0,
78
+ y: 0
79
+ };
80
+ this.isDragging = false;
81
+ this.pointerContext = null;
82
+ this.isOpen = false;
83
+ this.draggedDuringInteraction = false;
84
+ this.ignoreNextButtonClick = false;
85
+ this.selectedMenu = "ag-ui-events";
86
+ this.contextMenuOpen = false;
87
+ this.dockMode = "floating";
88
+ this.previousBodyMargins = null;
89
+ this.transitionTimeoutId = null;
90
+ this.bodyTransitionTimeoutIds = /* @__PURE__ */ new Set();
91
+ this.pendingSelectedContext = null;
92
+ this.autoAttachCore = true;
93
+ this.attemptedAutoAttach = false;
94
+ this.cachedTools = [];
95
+ this.toolSignature = "";
96
+ this.eventFilterText = "";
97
+ this.eventTypeFilter = "all";
98
+ this.announcementMarkdown = null;
99
+ this.announcementHtml = null;
100
+ this.announcementTimestamp = null;
101
+ this.announcementPreviewText = null;
102
+ this.hasUnseenAnnouncement = false;
103
+ this.announcementLoaded = false;
104
+ this.announcementLoadError = null;
105
+ this.announcementPromise = null;
106
+ this.showAnnouncementPreview = true;
107
+ this.contextState = {
108
+ button: {
109
+ position: {
110
+ x: EDGE_MARGIN,
111
+ y: EDGE_MARGIN
112
+ },
113
+ size: { ...DEFAULT_BUTTON_SIZE },
114
+ anchor: {
115
+ horizontal: "right",
116
+ vertical: "top"
117
+ },
118
+ anchorOffset: {
119
+ x: EDGE_MARGIN,
120
+ y: EDGE_MARGIN
121
+ }
122
+ },
123
+ window: {
124
+ position: {
125
+ x: EDGE_MARGIN,
126
+ y: EDGE_MARGIN
127
+ },
128
+ size: { ...DEFAULT_WINDOW_SIZE },
129
+ anchor: {
130
+ horizontal: "right",
131
+ vertical: "top"
132
+ },
133
+ anchorOffset: {
134
+ x: EDGE_MARGIN,
135
+ y: EDGE_MARGIN
136
+ }
137
+ }
138
+ };
139
+ this.hasCustomPosition = {
140
+ button: false,
141
+ window: false
142
+ };
143
+ this.resizePointerId = null;
144
+ this.resizeStart = null;
145
+ this.resizeInitialSize = null;
146
+ this.isResizing = false;
147
+ this.menuItems = [
148
+ {
149
+ key: "ag-ui-events",
150
+ label: "AG-UI Events",
151
+ icon: "Zap"
152
+ },
153
+ {
154
+ key: "agents",
155
+ label: "Agent",
156
+ icon: "Bot"
157
+ },
158
+ {
159
+ key: "frontend-tools",
160
+ label: "Frontend Tools",
161
+ icon: "Hammer"
162
+ },
163
+ {
164
+ key: "agent-context",
165
+ label: "Context",
166
+ icon: "FileText"
167
+ }
168
+ ];
169
+ this.handlePointerDown = (event) => {
170
+ if (this.dockMode !== "floating" && this.isOpen) return;
171
+ const target = event.currentTarget;
172
+ const context = target?.dataset.dragContext === "window" ? "window" : "button";
173
+ const eventTarget = event.target;
174
+ if (context === "window" && eventTarget?.closest("button")) return;
175
+ this.pointerContext = context;
176
+ this.measureContext(context);
177
+ event.preventDefault();
178
+ this.pointerId = event.pointerId;
179
+ this.dragStart = {
180
+ x: event.clientX,
181
+ y: event.clientY
182
+ };
183
+ const state = this.contextState[context];
184
+ this.dragOffset = {
185
+ x: event.clientX - state.position.x,
186
+ y: event.clientY - state.position.y
187
+ };
188
+ this.isDragging = false;
189
+ this.draggedDuringInteraction = false;
190
+ this.ignoreNextButtonClick = false;
191
+ target?.setPointerCapture?.(this.pointerId);
192
+ };
193
+ this.handlePointerMove = (event) => {
194
+ if (this.pointerId !== event.pointerId || !this.dragStart || !this.pointerContext) return;
195
+ const distance = Math.hypot(event.clientX - this.dragStart.x, event.clientY - this.dragStart.y);
196
+ if (!this.isDragging && distance < DRAG_THRESHOLD) return;
197
+ event.preventDefault();
198
+ this.setDragging(true);
199
+ this.draggedDuringInteraction = true;
200
+ const desired = {
201
+ x: event.clientX - this.dragOffset.x,
202
+ y: event.clientY - this.dragOffset.y
203
+ };
204
+ const constrained = this.constrainToViewport(desired, this.pointerContext);
205
+ this.contextState[this.pointerContext].position = constrained;
206
+ this.updateHostTransform(this.pointerContext);
207
+ };
208
+ this.handlePointerUp = (event) => {
209
+ if (this.pointerId !== event.pointerId) return;
210
+ const target = event.currentTarget;
211
+ if (target?.hasPointerCapture(this.pointerId)) target.releasePointerCapture(this.pointerId);
212
+ const context = this.pointerContext ?? this.activeContext;
213
+ if (this.isDragging && this.pointerContext) {
214
+ event.preventDefault();
215
+ this.setDragging(false);
216
+ if (this.pointerContext === "window") {
217
+ this.updateAnchorFromPosition(this.pointerContext);
218
+ this.hasCustomPosition.window = true;
219
+ this.applyAnchorPosition(this.pointerContext);
220
+ } else if (this.pointerContext === "button") {
221
+ this.snapButtonToCorner();
222
+ this.hasCustomPosition.button = true;
223
+ if (this.draggedDuringInteraction) this.ignoreNextButtonClick = true;
224
+ }
225
+ } else if (context === "button" && !this.isOpen && !this.draggedDuringInteraction) this.openInspector();
226
+ this.resetPointerTracking();
227
+ };
228
+ this.handlePointerCancel = (event) => {
229
+ if (this.pointerId !== event.pointerId) return;
230
+ const target = event.currentTarget;
231
+ if (target?.hasPointerCapture(this.pointerId)) target.releasePointerCapture(this.pointerId);
232
+ this.resetPointerTracking();
233
+ };
234
+ this.handleButtonClick = (event) => {
235
+ if (this.isDragging) {
236
+ event.preventDefault();
237
+ return;
238
+ }
239
+ if (this.ignoreNextButtonClick) {
240
+ event.preventDefault();
241
+ this.ignoreNextButtonClick = false;
242
+ return;
243
+ }
244
+ if (!this.isOpen) {
245
+ event.preventDefault();
246
+ this.openInspector();
247
+ }
248
+ };
249
+ this.handleClosePointerDown = (event) => {
250
+ event.stopPropagation();
251
+ event.preventDefault();
252
+ };
253
+ this.handleCloseClick = () => {
254
+ this.closeInspector();
255
+ };
256
+ this.handleResizePointerDown = (event) => {
257
+ event.stopPropagation();
258
+ event.preventDefault();
259
+ this.hasCustomPosition.window = true;
260
+ this.isResizing = true;
261
+ this.resizePointerId = event.pointerId;
262
+ this.resizeStart = {
263
+ x: event.clientX,
264
+ y: event.clientY
265
+ };
266
+ this.resizeInitialSize = { ...this.contextState.window.size };
267
+ if (document.body && this.dockMode !== "floating") document.body.style.transition = "";
268
+ event.currentTarget?.setPointerCapture?.(event.pointerId);
269
+ };
270
+ this.handleResizePointerMove = (event) => {
271
+ if (!this.isResizing || this.resizePointerId !== event.pointerId || !this.resizeStart || !this.resizeInitialSize) return;
272
+ event.preventDefault();
273
+ const deltaX = event.clientX - this.resizeStart.x;
274
+ const deltaY = event.clientY - this.resizeStart.y;
275
+ const state = this.contextState.window;
276
+ if (this.dockMode === "docked-left") {
277
+ state.size = this.clampWindowSize({
278
+ width: this.resizeInitialSize.width + deltaX,
279
+ height: state.size.height
280
+ });
281
+ if (document.body) document.body.style.marginLeft = `${state.size.width}px`;
282
+ } else {
283
+ state.size = this.clampWindowSize({
284
+ width: this.resizeInitialSize.width + deltaX,
285
+ height: this.resizeInitialSize.height + deltaY
286
+ });
287
+ this.keepPositionWithinViewport("window");
288
+ this.updateAnchorFromPosition("window");
289
+ }
290
+ this.requestUpdate();
291
+ this.updateHostTransform("window");
292
+ };
293
+ this.handleResizePointerUp = (event) => {
294
+ if (this.resizePointerId !== event.pointerId) return;
295
+ const target = event.currentTarget;
296
+ if (target?.hasPointerCapture(this.resizePointerId)) target.releasePointerCapture(this.resizePointerId);
297
+ if (this.dockMode === "floating") {
298
+ this.updateAnchorFromPosition("window");
299
+ this.applyAnchorPosition("window");
300
+ }
301
+ this.persistState();
302
+ this.resetResizeTracking();
303
+ };
304
+ this.handleResizePointerCancel = (event) => {
305
+ if (this.resizePointerId !== event.pointerId) return;
306
+ const target = event.currentTarget;
307
+ if (target?.hasPointerCapture(this.resizePointerId)) target.releasePointerCapture(this.resizePointerId);
308
+ if (this.dockMode === "floating") {
309
+ this.updateAnchorFromPosition("window");
310
+ this.applyAnchorPosition("window");
311
+ }
312
+ this.persistState();
313
+ this.resetResizeTracking();
314
+ };
315
+ this.handleResize = () => {
316
+ this.measureContext("button");
317
+ this.applyAnchorPosition("button");
318
+ this.measureContext("window");
319
+ if (this.hasCustomPosition.window) this.applyAnchorPosition("window");
320
+ else this.centerContext("window");
321
+ this.updateHostTransform();
322
+ };
323
+ this.contextOptions = [{
324
+ key: "all-agents",
325
+ label: "All Agents"
326
+ }];
327
+ this.selectedContext = "all-agents";
328
+ this.expandedRows = /* @__PURE__ */ new Set();
329
+ this.copiedEvents = /* @__PURE__ */ new Set();
330
+ this.expandedTools = /* @__PURE__ */ new Set();
331
+ this.expandedContextItems = /* @__PURE__ */ new Set();
332
+ this.copiedContextItems = /* @__PURE__ */ new Set();
333
+ this.handleClearEvents = () => {
334
+ if (this.selectedContext === "all-agents") {
335
+ this.agentEvents.clear();
336
+ this.flattenedEvents = [];
337
+ } else {
338
+ this.agentEvents.delete(this.selectedContext);
339
+ this.flattenedEvents = this.flattenedEvents.filter((event) => event.agentId !== this.selectedContext);
340
+ }
341
+ this.expandedRows.clear();
342
+ this.copiedEvents.clear();
343
+ this.requestUpdate();
344
+ };
345
+ this.handleGlobalPointerDown = (event) => {
346
+ if (!this.contextMenuOpen) return;
347
+ if (!event.composedPath().some((node) => {
348
+ return node instanceof HTMLElement && node.dataset?.contextDropdownRoot === "true";
349
+ })) {
350
+ this.contextMenuOpen = false;
351
+ this.requestUpdate();
352
+ }
353
+ };
354
+ this.handleDismissAnnouncement = () => {
355
+ this.markAnnouncementSeen();
356
+ };
357
+ }
358
+ static {
359
+ this.properties = {
360
+ core: { attribute: false },
361
+ autoAttachCore: {
362
+ type: Boolean,
363
+ attribute: "auto-attach-core"
364
+ }
365
+ };
366
+ }
367
+ get core() {
368
+ return this._core;
369
+ }
370
+ set core(value) {
371
+ const oldValue = this._core;
372
+ if (oldValue === value) return;
373
+ this.detachFromCore();
374
+ this._core = value ?? null;
375
+ this.requestUpdate("core", oldValue);
376
+ if (this._core) this.attachToCore(this._core);
377
+ }
378
+ attachToCore(core) {
379
+ this.runtimeStatus = core.runtimeConnectionStatus;
380
+ this.coreProperties = core.properties;
381
+ this.lastCoreError = null;
382
+ this.coreSubscriber = {
383
+ onRuntimeConnectionStatusChanged: ({ status }) => {
384
+ this.runtimeStatus = status;
385
+ this.requestUpdate();
386
+ },
387
+ onPropertiesChanged: ({ properties }) => {
388
+ this.coreProperties = properties;
389
+ this.requestUpdate();
390
+ },
391
+ onError: ({ code, error }) => {
392
+ this.lastCoreError = {
393
+ code,
394
+ message: error.message
395
+ };
396
+ this.requestUpdate();
397
+ },
398
+ onAgentsChanged: ({ agents }) => {
399
+ this.processAgentsChanged(agents);
400
+ },
401
+ onContextChanged: ({ context }) => {
402
+ this.contextStore = this.normalizeContextStore(context);
403
+ this.requestUpdate();
404
+ }
405
+ };
406
+ this.coreUnsubscribe = core.subscribe(this.coreSubscriber).unsubscribe;
407
+ this.processAgentsChanged(core.agents);
408
+ if (core.context) this.contextStore = this.normalizeContextStore(core.context);
409
+ }
410
+ detachFromCore() {
411
+ if (this.coreUnsubscribe) {
412
+ this.coreUnsubscribe();
413
+ this.coreUnsubscribe = null;
414
+ }
415
+ this.coreSubscriber = null;
416
+ this.runtimeStatus = null;
417
+ this.lastCoreError = null;
418
+ this.coreProperties = {};
419
+ this.cachedTools = [];
420
+ this.toolSignature = "";
421
+ this.teardownAgentSubscriptions();
422
+ }
423
+ teardownAgentSubscriptions() {
424
+ for (const unsubscribe of this.agentSubscriptions.values()) unsubscribe();
425
+ this.agentSubscriptions.clear();
426
+ this.agentEvents.clear();
427
+ this.agentMessages.clear();
428
+ this.agentStates.clear();
429
+ this.flattenedEvents = [];
430
+ this.eventCounter = 0;
431
+ }
432
+ processAgentsChanged(agents) {
433
+ const seenAgentIds = /* @__PURE__ */ new Set();
434
+ for (const agent of Object.values(agents)) {
435
+ if (!agent?.agentId) continue;
436
+ seenAgentIds.add(agent.agentId);
437
+ this.subscribeToAgent(agent);
438
+ }
439
+ for (const agentId of Array.from(this.agentSubscriptions.keys())) if (!seenAgentIds.has(agentId)) {
440
+ this.unsubscribeFromAgent(agentId);
441
+ this.agentEvents.delete(agentId);
442
+ this.agentMessages.delete(agentId);
443
+ this.agentStates.delete(agentId);
444
+ }
445
+ this.updateContextOptions(seenAgentIds);
446
+ this.refreshToolsSnapshot();
447
+ this.requestUpdate();
448
+ }
449
+ refreshToolsSnapshot() {
450
+ if (!this._core) {
451
+ if (this.cachedTools.length > 0) {
452
+ this.cachedTools = [];
453
+ this.toolSignature = "";
454
+ this.requestUpdate();
455
+ }
456
+ return;
457
+ }
458
+ const tools = this.extractToolsFromAgents();
459
+ const signature = JSON.stringify(tools.map((tool) => ({
460
+ agentId: tool.agentId,
461
+ name: tool.name,
462
+ type: tool.type,
463
+ hasDescription: Boolean(tool.description),
464
+ hasParameters: Boolean(tool.parameters)
465
+ })));
466
+ if (signature !== this.toolSignature) {
467
+ this.toolSignature = signature;
468
+ this.cachedTools = tools;
469
+ this.requestUpdate();
470
+ }
471
+ }
472
+ tryAutoAttachCore() {
473
+ if (this.attemptedAutoAttach || this._core || !this.autoAttachCore || typeof window === "undefined") return;
474
+ this.attemptedAutoAttach = true;
475
+ const globalWindow = window;
476
+ const foundCore = [
477
+ globalWindow.__COPILOTKIT_CORE__,
478
+ globalWindow.copilotkit?.core,
479
+ globalWindow.copilotkitCore
480
+ ].find((candidate) => !!candidate && typeof candidate === "object");
481
+ if (foundCore) this.core = foundCore;
482
+ }
483
+ subscribeToAgent(agent) {
484
+ if (!agent.agentId) return;
485
+ const agentId = agent.agentId;
486
+ this.unsubscribeFromAgent(agentId);
487
+ const { unsubscribe } = agent.subscribe({
488
+ onRunStartedEvent: ({ event }) => {
489
+ this.recordAgentEvent(agentId, "RUN_STARTED", event);
490
+ },
491
+ onRunFinishedEvent: ({ event, result }) => {
492
+ this.recordAgentEvent(agentId, "RUN_FINISHED", {
493
+ event,
494
+ result
495
+ });
496
+ },
497
+ onRunErrorEvent: ({ event }) => {
498
+ this.recordAgentEvent(agentId, "RUN_ERROR", event);
499
+ },
500
+ onTextMessageStartEvent: ({ event }) => {
501
+ this.recordAgentEvent(agentId, "TEXT_MESSAGE_START", event);
502
+ },
503
+ onTextMessageContentEvent: ({ event, textMessageBuffer }) => {
504
+ this.recordAgentEvent(agentId, "TEXT_MESSAGE_CONTENT", {
505
+ event,
506
+ textMessageBuffer
507
+ });
508
+ },
509
+ onTextMessageEndEvent: ({ event, textMessageBuffer }) => {
510
+ this.recordAgentEvent(agentId, "TEXT_MESSAGE_END", {
511
+ event,
512
+ textMessageBuffer
513
+ });
514
+ },
515
+ onToolCallStartEvent: ({ event }) => {
516
+ this.recordAgentEvent(agentId, "TOOL_CALL_START", event);
517
+ },
518
+ onToolCallArgsEvent: ({ event, toolCallBuffer, toolCallName, partialToolCallArgs }) => {
519
+ this.recordAgentEvent(agentId, "TOOL_CALL_ARGS", {
520
+ event,
521
+ toolCallBuffer,
522
+ toolCallName,
523
+ partialToolCallArgs
524
+ });
525
+ },
526
+ onToolCallEndEvent: ({ event, toolCallArgs, toolCallName }) => {
527
+ this.recordAgentEvent(agentId, "TOOL_CALL_END", {
528
+ event,
529
+ toolCallArgs,
530
+ toolCallName
531
+ });
532
+ },
533
+ onToolCallResultEvent: ({ event }) => {
534
+ this.recordAgentEvent(agentId, "TOOL_CALL_RESULT", event);
535
+ },
536
+ onStateSnapshotEvent: ({ event }) => {
537
+ this.recordAgentEvent(agentId, "STATE_SNAPSHOT", event);
538
+ this.syncAgentState(agent);
539
+ },
540
+ onStateDeltaEvent: ({ event }) => {
541
+ this.recordAgentEvent(agentId, "STATE_DELTA", event);
542
+ this.syncAgentState(agent);
543
+ },
544
+ onMessagesSnapshotEvent: ({ event }) => {
545
+ this.recordAgentEvent(agentId, "MESSAGES_SNAPSHOT", event);
546
+ this.syncAgentMessages(agent);
547
+ },
548
+ onMessagesChanged: () => {
549
+ this.syncAgentMessages(agent);
550
+ },
551
+ onRawEvent: ({ event }) => {
552
+ this.recordAgentEvent(agentId, "RAW_EVENT", event);
553
+ },
554
+ onCustomEvent: ({ event }) => {
555
+ this.recordAgentEvent(agentId, "CUSTOM_EVENT", event);
556
+ },
557
+ onReasoningStartEvent: ({ event }) => {
558
+ this.recordAgentEvent(agentId, "REASONING_START", event);
559
+ },
560
+ onReasoningMessageStartEvent: ({ event }) => {
561
+ this.recordAgentEvent(agentId, "REASONING_MESSAGE_START", event);
562
+ },
563
+ onReasoningMessageContentEvent: ({ event, reasoningMessageBuffer }) => {
564
+ this.recordAgentEvent(agentId, "REASONING_MESSAGE_CONTENT", {
565
+ event,
566
+ reasoningMessageBuffer
567
+ });
568
+ },
569
+ onReasoningMessageEndEvent: ({ event, reasoningMessageBuffer }) => {
570
+ this.recordAgentEvent(agentId, "REASONING_MESSAGE_END", {
571
+ event,
572
+ reasoningMessageBuffer
573
+ });
574
+ },
575
+ onReasoningEndEvent: ({ event }) => {
576
+ this.recordAgentEvent(agentId, "REASONING_END", event);
577
+ },
578
+ onReasoningEncryptedValueEvent: ({ event }) => {
579
+ this.recordAgentEvent(agentId, "REASONING_ENCRYPTED_VALUE", event);
580
+ }
581
+ });
582
+ this.agentSubscriptions.set(agentId, unsubscribe);
583
+ this.syncAgentMessages(agent);
584
+ this.syncAgentState(agent);
585
+ if (!this.agentEvents.has(agentId)) this.agentEvents.set(agentId, []);
586
+ }
587
+ unsubscribeFromAgent(agentId) {
588
+ const unsubscribe = this.agentSubscriptions.get(agentId);
589
+ if (unsubscribe) {
590
+ unsubscribe();
591
+ this.agentSubscriptions.delete(agentId);
592
+ }
593
+ }
594
+ recordAgentEvent(agentId, type, payload) {
595
+ const eventId = `${agentId}:${++this.eventCounter}`;
596
+ const normalizedPayload = this.normalizeEventPayload(type, payload);
597
+ const event = {
598
+ id: eventId,
599
+ agentId,
600
+ type,
601
+ timestamp: Date.now(),
602
+ payload: normalizedPayload
603
+ };
604
+ const nextAgentEvents = [event, ...this.agentEvents.get(agentId) ?? []].slice(0, MAX_AGENT_EVENTS);
605
+ this.agentEvents.set(agentId, nextAgentEvents);
606
+ this.flattenedEvents = [event, ...this.flattenedEvents].slice(0, MAX_TOTAL_EVENTS);
607
+ this.refreshToolsSnapshot();
608
+ this.requestUpdate();
609
+ }
610
+ syncAgentMessages(agent) {
611
+ if (!agent?.agentId) return;
612
+ const messages = this.normalizeAgentMessages(agent.messages);
613
+ if (messages) this.agentMessages.set(agent.agentId, messages);
614
+ else this.agentMessages.delete(agent.agentId);
615
+ this.requestUpdate();
616
+ }
617
+ syncAgentState(agent) {
618
+ if (!agent?.agentId) return;
619
+ const state = agent.state;
620
+ if (state === void 0 || state === null) this.agentStates.delete(agent.agentId);
621
+ else this.agentStates.set(agent.agentId, this.sanitizeForLogging(state));
622
+ this.requestUpdate();
623
+ }
624
+ updateContextOptions(agentIds) {
625
+ const nextOptions = [{
626
+ key: "all-agents",
627
+ label: "All Agents"
628
+ }, ...Array.from(agentIds).sort((a, b) => a.localeCompare(b)).map((id) => ({
629
+ key: id,
630
+ label: id
631
+ }))];
632
+ if (this.contextOptions.length !== nextOptions.length || this.contextOptions.some((option, index) => option.key !== nextOptions[index]?.key)) this.contextOptions = nextOptions;
633
+ const pendingContext = this.pendingSelectedContext;
634
+ if (pendingContext) {
635
+ if (pendingContext === "all-agents" || agentIds.has(pendingContext)) {
636
+ if (this.selectedContext !== pendingContext) {
637
+ this.selectedContext = pendingContext;
638
+ this.expandedRows.clear();
639
+ }
640
+ this.pendingSelectedContext = null;
641
+ } else if (agentIds.size > 0) this.pendingSelectedContext = null;
642
+ }
643
+ if (!nextOptions.some((option) => option.key === this.selectedContext) && this.pendingSelectedContext === null) {
644
+ let nextSelected = "all-agents";
645
+ if (agentIds.has("default")) nextSelected = "default";
646
+ else if (agentIds.size > 0) nextSelected = Array.from(agentIds).sort((a, b) => a.localeCompare(b))[0];
647
+ if (this.selectedContext !== nextSelected) {
648
+ this.selectedContext = nextSelected;
649
+ this.expandedRows.clear();
650
+ this.persistState();
651
+ }
652
+ }
653
+ }
654
+ getEventsForSelectedContext() {
655
+ if (this.selectedContext === "all-agents") return this.flattenedEvents;
656
+ return this.agentEvents.get(this.selectedContext) ?? [];
657
+ }
658
+ filterEvents(events) {
659
+ const query = this.eventFilterText.trim().toLowerCase();
660
+ return events.filter((event) => {
661
+ if (this.eventTypeFilter !== "all" && event.type !== this.eventTypeFilter) return false;
662
+ if (!query) return true;
663
+ const payloadText = this.stringifyPayload(event.payload, false).toLowerCase();
664
+ return event.type.toLowerCase().includes(query) || event.agentId.toLowerCase().includes(query) || payloadText.includes(query);
665
+ });
666
+ }
667
+ getLatestStateForAgent(agentId) {
668
+ if (this.agentStates.has(agentId)) {
669
+ const value = this.agentStates.get(agentId);
670
+ return value === void 0 ? null : value;
671
+ }
672
+ const stateEvent = (this.agentEvents.get(agentId) ?? []).find((e) => e.type === "STATE_SNAPSHOT");
673
+ if (!stateEvent) return null;
674
+ return stateEvent.payload;
675
+ }
676
+ getLatestMessagesForAgent(agentId) {
677
+ return this.agentMessages.get(agentId) ?? null;
678
+ }
679
+ getAgentStatus(agentId) {
680
+ const events = this.agentEvents.get(agentId) ?? [];
681
+ if (events.length === 0) return "idle";
682
+ const runEvent = events.find((e) => e.type === "RUN_STARTED" || e.type === "RUN_FINISHED" || e.type === "RUN_ERROR");
683
+ if (!runEvent) return "idle";
684
+ if (runEvent.type === "RUN_ERROR") return "error";
685
+ if (runEvent.type === "RUN_STARTED") return events.find((e) => e.type === "RUN_FINISHED" && e.timestamp > runEvent.timestamp) ? "idle" : "running";
686
+ return "idle";
687
+ }
688
+ getAgentStats(agentId) {
689
+ const events = this.agentEvents.get(agentId) ?? [];
690
+ const messages = this.agentMessages.get(agentId);
691
+ const toolCallCount = messages ? messages.reduce((count, message) => count + (message.toolCalls?.length ?? 0), 0) : events.filter((e) => e.type === "TOOL_CALL_END").length;
692
+ const messageCount = messages?.length ?? 0;
693
+ return {
694
+ totalEvents: events.length,
695
+ lastActivity: events[0]?.timestamp ?? null,
696
+ messages: messageCount,
697
+ toolCalls: toolCallCount,
698
+ errors: events.filter((e) => e.type === "RUN_ERROR").length
699
+ };
700
+ }
701
+ renderToolCallDetails(toolCalls) {
702
+ if (!Array.isArray(toolCalls) || toolCalls.length === 0) return lit.nothing;
703
+ return lit.html`
704
+ <div class="mt-2 space-y-2">
705
+ ${toolCalls.map((call, index) => {
706
+ const functionName = call.function?.name ?? call.toolName ?? "Unknown function";
707
+ const callId = typeof call?.id === "string" ? call.id : `tool-call-${index + 1}`;
708
+ const argsString = this.formatToolCallArguments(call.function?.arguments);
709
+ return lit.html`
710
+ <div
711
+ class="rounded-md border border-gray-200 bg-gray-50 p-3 text-xs text-gray-700"
712
+ >
713
+ <div
714
+ class="flex flex-wrap items-center justify-between gap-1 font-medium text-gray-900"
715
+ >
716
+ <span>${functionName}</span>
717
+ <span class="text-[10px] text-gray-500">ID: ${callId}</span>
718
+ </div>
719
+ ${argsString ? lit.html`<pre
720
+ class="mt-2 overflow-auto rounded bg-white p-2 text-[11px] leading-relaxed text-gray-800"
721
+ >
722
+ ${argsString}</pre
723
+ >` : lit.nothing}
724
+ </div>
725
+ `;
726
+ })}
727
+ </div>
728
+ `;
729
+ }
730
+ formatToolCallArguments(args) {
731
+ if (args === void 0 || args === null || args === "") return null;
732
+ if (typeof args === "string") try {
733
+ const parsed = JSON.parse(args);
734
+ return JSON.stringify(parsed, null, 2);
735
+ } catch {
736
+ return args;
737
+ }
738
+ if (typeof args === "object") try {
739
+ return JSON.stringify(args, null, 2);
740
+ } catch {
741
+ return String(args);
742
+ }
743
+ return String(args);
744
+ }
745
+ hasRenderableState(state) {
746
+ if (state === null || state === void 0) return false;
747
+ if (Array.isArray(state)) return state.length > 0;
748
+ if (typeof state === "object") return Object.keys(state).length > 0;
749
+ if (typeof state === "string") {
750
+ const trimmed = state.trim();
751
+ return trimmed.length > 0 && trimmed !== "{}";
752
+ }
753
+ return true;
754
+ }
755
+ formatStateForDisplay(state) {
756
+ if (state === null || state === void 0) return "";
757
+ if (typeof state === "string") {
758
+ const trimmed = state.trim();
759
+ if (trimmed.length === 0) return "";
760
+ try {
761
+ const parsed = JSON.parse(trimmed);
762
+ return JSON.stringify(parsed, null, 2);
763
+ } catch {
764
+ return state;
765
+ }
766
+ }
767
+ if (typeof state === "object") try {
768
+ return JSON.stringify(state, null, 2);
769
+ } catch {
770
+ return String(state);
771
+ }
772
+ return String(state);
773
+ }
774
+ getEventBadgeClasses(type) {
775
+ const base = "font-mono text-[10px] font-medium inline-flex items-center rounded-sm px-1.5 py-0.5 border";
776
+ if (type.startsWith("RUN_")) return `${base} bg-blue-50 text-blue-700 border-blue-200`;
777
+ if (type.startsWith("TEXT_MESSAGE")) return `${base} bg-emerald-50 text-emerald-700 border-emerald-200`;
778
+ if (type.startsWith("TOOL_CALL")) return `${base} bg-amber-50 text-amber-700 border-amber-200`;
779
+ if (type.startsWith("REASONING")) return `${base} bg-fuchsia-50 text-fuchsia-700 border-fuchsia-200`;
780
+ if (type.startsWith("STATE")) return `${base} bg-violet-50 text-violet-700 border-violet-200`;
781
+ if (type.startsWith("MESSAGES")) return `${base} bg-sky-50 text-sky-700 border-sky-200`;
782
+ if (type === "RUN_ERROR") return `${base} bg-rose-50 text-rose-700 border-rose-200`;
783
+ return `${base} bg-gray-100 text-gray-600 border-gray-200`;
784
+ }
785
+ stringifyPayload(payload, pretty) {
786
+ try {
787
+ if (payload === void 0) return pretty ? "undefined" : "undefined";
788
+ if (typeof payload === "string") return payload;
789
+ return JSON.stringify(payload, null, pretty ? 2 : 0) ?? "";
790
+ } catch (error) {
791
+ console.warn("Failed to stringify inspector payload", error);
792
+ return String(payload);
793
+ }
794
+ }
795
+ extractEventFromPayload(payload) {
796
+ if (payload && typeof payload === "object" && "event" in payload) return payload.event;
797
+ return payload;
798
+ }
799
+ async copyToClipboard(text, eventId) {
800
+ try {
801
+ await navigator.clipboard.writeText(text);
802
+ this.copiedEvents.add(eventId);
803
+ this.requestUpdate();
804
+ setTimeout(() => {
805
+ this.copiedEvents.delete(eventId);
806
+ this.requestUpdate();
807
+ }, 2e3);
808
+ } catch (err) {
809
+ console.error("Failed to copy to clipboard:", err);
810
+ }
811
+ }
812
+ static {
813
+ this.styles = [(0, lit.unsafeCSS)(require_generated.default), lit.css`
814
+ :host {
815
+ position: fixed;
816
+ top: 0;
817
+ left: 0;
818
+ z-index: 2147483646;
819
+ display: block;
820
+ will-change: transform;
821
+ }
822
+
823
+ :host([data-transitioning="true"]) {
824
+ transition: transform 300ms ease;
825
+ }
826
+
827
+ .console-button {
828
+ transition:
829
+ transform 300ms cubic-bezier(0.34, 1.56, 0.64, 1),
830
+ opacity 160ms ease;
831
+ }
832
+
833
+ .console-button[data-dragging="true"] {
834
+ transition: opacity 160ms ease;
835
+ }
836
+
837
+ .inspector-window[data-transitioning="true"] {
838
+ transition:
839
+ width 300ms ease,
840
+ height 300ms ease;
841
+ }
842
+
843
+ .inspector-window[data-docked="true"] {
844
+ border-radius: 0 !important;
845
+ box-shadow: none !important;
846
+ }
847
+
848
+ .resize-handle {
849
+ touch-action: none;
850
+ user-select: none;
851
+ }
852
+
853
+ .dock-resize-handle {
854
+ position: absolute;
855
+ top: 0;
856
+ right: 0;
857
+ width: 10px;
858
+ height: 100%;
859
+ cursor: ew-resize;
860
+ touch-action: none;
861
+ z-index: 50;
862
+ background: transparent;
863
+ }
864
+
865
+ .tooltip-target {
866
+ position: relative;
867
+ }
868
+
869
+ .tooltip-target::after {
870
+ content: attr(data-tooltip);
871
+ position: absolute;
872
+ top: calc(100% + 6px);
873
+ left: 50%;
874
+ transform: translateX(-50%) translateY(-4px);
875
+ white-space: nowrap;
876
+ background: rgba(17, 24, 39, 0.95);
877
+ color: white;
878
+ padding: 4px 8px;
879
+ border-radius: 6px;
880
+ font-size: 10px;
881
+ line-height: 1.2;
882
+ box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
883
+ opacity: 0;
884
+ pointer-events: none;
885
+ transition:
886
+ opacity 120ms ease,
887
+ transform 120ms ease;
888
+ z-index: 4000;
889
+ }
890
+
891
+ .tooltip-target:hover::after {
892
+ opacity: 1;
893
+ transform: translateX(-50%) translateY(0);
894
+ }
895
+
896
+ .announcement-preview {
897
+ position: absolute;
898
+ top: 50%;
899
+ transform: translateY(-50%);
900
+ min-width: 300px;
901
+ max-width: 300px;
902
+ background: white;
903
+ color: #111827;
904
+ font-size: 13px;
905
+ line-height: 1.4;
906
+ border-radius: 12px;
907
+ box-shadow: 0 12px 28px rgba(15, 23, 42, 0.22);
908
+ padding: 10px 12px;
909
+ display: inline-flex;
910
+ align-items: flex-start;
911
+ gap: 8px;
912
+ z-index: 4500;
913
+ animation: fade-slide-in 160ms ease;
914
+ border: 1px solid rgba(148, 163, 184, 0.35);
915
+ white-space: normal;
916
+ word-break: break-word;
917
+ text-align: left;
918
+ }
919
+
920
+ .announcement-preview[data-side="left"] {
921
+ right: 100%;
922
+ margin-right: 10px;
923
+ }
924
+
925
+ .announcement-preview[data-side="right"] {
926
+ left: 100%;
927
+ margin-left: 10px;
928
+ }
929
+
930
+ .announcement-preview__arrow {
931
+ position: absolute;
932
+ width: 10px;
933
+ height: 10px;
934
+ background: white;
935
+ border: 1px solid rgba(148, 163, 184, 0.35);
936
+ transform: rotate(45deg);
937
+ top: 50%;
938
+ margin-top: -5px;
939
+ z-index: -1;
940
+ }
941
+
942
+ .announcement-preview[data-side="left"] .announcement-preview__arrow {
943
+ right: -5px;
944
+ box-shadow: 6px -6px 10px rgba(15, 23, 42, 0.12);
945
+ }
946
+
947
+ .announcement-preview[data-side="right"] .announcement-preview__arrow {
948
+ left: -5px;
949
+ box-shadow: -6px 6px 10px rgba(15, 23, 42, 0.12);
950
+ }
951
+
952
+ .announcement-dismiss {
953
+ color: #6b7280;
954
+ font-size: 12px;
955
+ padding: 2px 8px;
956
+ border-radius: 8px;
957
+ border: 1px solid rgba(148, 163, 184, 0.5);
958
+ background: rgba(248, 250, 252, 0.9);
959
+ transition:
960
+ background 120ms ease,
961
+ color 120ms ease;
962
+ }
963
+
964
+ .announcement-dismiss:hover {
965
+ background: rgba(241, 245, 249, 1);
966
+ color: #111827;
967
+ }
968
+
969
+ .announcement-content {
970
+ color: #111827;
971
+ font-size: 14px;
972
+ line-height: 1.6;
973
+ }
974
+
975
+ .announcement-content h1,
976
+ .announcement-content h2,
977
+ .announcement-content h3 {
978
+ font-weight: 700;
979
+ margin: 0.4rem 0 0.2rem;
980
+ }
981
+
982
+ .announcement-content h1 {
983
+ font-size: 1.1rem;
984
+ }
985
+
986
+ .announcement-content h2 {
987
+ font-size: 1rem;
988
+ }
989
+
990
+ .announcement-content h3 {
991
+ font-size: 0.95rem;
992
+ }
993
+
994
+ .announcement-content p {
995
+ margin: 0.25rem 0;
996
+ }
997
+
998
+ .announcement-content ul {
999
+ list-style: disc;
1000
+ padding-left: 1.25rem;
1001
+ margin: 0.3rem 0;
1002
+ }
1003
+
1004
+ .announcement-content ol {
1005
+ list-style: decimal;
1006
+ padding-left: 1.25rem;
1007
+ margin: 0.3rem 0;
1008
+ }
1009
+
1010
+ .announcement-content a {
1011
+ color: #0f766e;
1012
+ text-decoration: underline;
1013
+ }
1014
+ `];
1015
+ }
1016
+ connectedCallback() {
1017
+ super.connectedCallback();
1018
+ if (typeof window !== "undefined") {
1019
+ window.addEventListener("resize", this.handleResize);
1020
+ window.addEventListener("pointerdown", this.handleGlobalPointerDown);
1021
+ this.hydrateStateFromStorageEarly();
1022
+ this.tryAutoAttachCore();
1023
+ this.ensureAnnouncementLoading();
1024
+ }
1025
+ }
1026
+ disconnectedCallback() {
1027
+ super.disconnectedCallback();
1028
+ if (typeof window !== "undefined") {
1029
+ window.removeEventListener("resize", this.handleResize);
1030
+ window.removeEventListener("pointerdown", this.handleGlobalPointerDown);
1031
+ }
1032
+ for (const id of this.bodyTransitionTimeoutIds) clearTimeout(id);
1033
+ this.bodyTransitionTimeoutIds.clear();
1034
+ if (this.transitionTimeoutId !== null) {
1035
+ clearTimeout(this.transitionTimeoutId);
1036
+ this.transitionTimeoutId = null;
1037
+ }
1038
+ this.removeDockStyles(true);
1039
+ this.detachFromCore();
1040
+ }
1041
+ firstUpdated() {
1042
+ if (typeof window === "undefined") return;
1043
+ if (!this._core) this.tryAutoAttachCore();
1044
+ this.measureContext("button");
1045
+ this.measureContext("window");
1046
+ this.contextState.button.anchor = {
1047
+ horizontal: "right",
1048
+ vertical: "top"
1049
+ };
1050
+ this.contextState.button.anchorOffset = {
1051
+ x: EDGE_MARGIN,
1052
+ y: EDGE_MARGIN
1053
+ };
1054
+ this.contextState.window.anchor = {
1055
+ horizontal: "right",
1056
+ vertical: "top"
1057
+ };
1058
+ this.contextState.window.anchorOffset = {
1059
+ x: EDGE_MARGIN,
1060
+ y: EDGE_MARGIN
1061
+ };
1062
+ this.hydrateStateFromStorage();
1063
+ if (this.isOpen && this.dockMode !== "floating") this.applyDockStyles(true);
1064
+ this.applyAnchorPosition("button");
1065
+ if (this.dockMode === "floating") if (this.hasCustomPosition.window) this.applyAnchorPosition("window");
1066
+ else this.centerContext("window");
1067
+ this.ensureAnnouncementLoading();
1068
+ this.updateHostTransform(this.isOpen ? "window" : "button");
1069
+ }
1070
+ render() {
1071
+ return this.isOpen ? this.renderWindow() : this.renderButton();
1072
+ }
1073
+ renderButton() {
1074
+ return lit.html`
1075
+ <button
1076
+ class=${[
1077
+ "console-button",
1078
+ "group",
1079
+ "relative",
1080
+ "pointer-events-auto",
1081
+ "inline-flex",
1082
+ "h-12",
1083
+ "w-12",
1084
+ "items-center",
1085
+ "justify-center",
1086
+ "rounded-full",
1087
+ "border",
1088
+ "border-white/20",
1089
+ "bg-slate-950/95",
1090
+ "text-xs",
1091
+ "font-medium",
1092
+ "text-white",
1093
+ "ring-1",
1094
+ "ring-white/10",
1095
+ "backdrop-blur-md",
1096
+ "transition",
1097
+ "hover:border-white/30",
1098
+ "hover:bg-slate-900/95",
1099
+ "hover:scale-105",
1100
+ "focus-visible:outline",
1101
+ "focus-visible:outline-2",
1102
+ "focus-visible:outline-offset-2",
1103
+ "focus-visible:outline-rose-500",
1104
+ "touch-none",
1105
+ "select-none",
1106
+ this.isDragging ? "cursor-grabbing" : "cursor-grab"
1107
+ ].join(" ")}
1108
+ type="button"
1109
+ aria-label="Web Inspector"
1110
+ data-drag-context="button"
1111
+ data-dragging=${this.isDragging && this.pointerContext === "button" ? "true" : "false"}
1112
+ @pointerdown=${this.handlePointerDown}
1113
+ @pointermove=${this.handlePointerMove}
1114
+ @pointerup=${this.handlePointerUp}
1115
+ @pointercancel=${this.handlePointerCancel}
1116
+ @click=${this.handleButtonClick}
1117
+ >
1118
+ ${this.renderAnnouncementPreview()}
1119
+ <img
1120
+ src=${require_inspector_logo_icon.default}
1121
+ alt="Inspector logo"
1122
+ class="h-5 w-auto"
1123
+ loading="lazy"
1124
+ />
1125
+ </button>
1126
+ `;
1127
+ }
1128
+ renderWindow() {
1129
+ const windowState = this.contextState.window;
1130
+ const isDocked = this.dockMode !== "floating";
1131
+ const isTransitioning = this.hasAttribute("data-transitioning");
1132
+ const windowStyles = isDocked ? this.getDockedWindowStyles() : {
1133
+ width: `${Math.round(windowState.size.width)}px`,
1134
+ height: `${Math.round(windowState.size.height)}px`,
1135
+ minWidth: `${MIN_WINDOW_WIDTH}px`,
1136
+ minHeight: `${MIN_WINDOW_HEIGHT}px`
1137
+ };
1138
+ const hasContextDropdown = this.contextOptions.length > 0;
1139
+ const contextDropdown = hasContextDropdown ? this.renderContextDropdown() : lit.nothing;
1140
+ const coreStatus = this.getCoreStatusSummary();
1141
+ const agentSelector = hasContextDropdown ? contextDropdown : lit.html`
1142
+ <div
1143
+ class="flex items-center gap-2 rounded-md border border-dashed border-gray-200 px-2 py-1 text-xs text-gray-400"
1144
+ >
1145
+ <span>${this.renderIcon("Bot")}</span>
1146
+ <span class="truncate">No agents available</span>
1147
+ </div>
1148
+ `;
1149
+ return lit.html`
1150
+ <section
1151
+ class="inspector-window pointer-events-auto relative flex flex-col overflow-hidden rounded-xl border border-gray-200 bg-white text-gray-900 shadow-lg"
1152
+ style=${(0, lit_directives_style_map_js.styleMap)(windowStyles)}
1153
+ data-docked=${isDocked}
1154
+ data-transitioning=${isTransitioning}
1155
+ >
1156
+ ${isDocked ? lit.html`
1157
+ <div
1158
+ class="dock-resize-handle pointer-events-auto"
1159
+ role="presentation"
1160
+ aria-hidden="true"
1161
+ @pointerdown=${this.handleResizePointerDown}
1162
+ @pointermove=${this.handleResizePointerMove}
1163
+ @pointerup=${this.handleResizePointerUp}
1164
+ @pointercancel=${this.handleResizePointerCancel}
1165
+ ></div>
1166
+ ` : lit.nothing}
1167
+ <div
1168
+ class="flex flex-1 flex-col overflow-hidden bg-white text-gray-800"
1169
+ >
1170
+ <div
1171
+ class="drag-handle relative z-30 flex flex-col border-b border-gray-200 bg-white/95 backdrop-blur-sm ${isDocked ? "" : this.isDragging && this.pointerContext === "window" ? "cursor-grabbing" : "cursor-grab"}"
1172
+ data-drag-context="window"
1173
+ @pointerdown=${isDocked ? void 0 : this.handlePointerDown}
1174
+ @pointermove=${isDocked ? void 0 : this.handlePointerMove}
1175
+ @pointerup=${isDocked ? void 0 : this.handlePointerUp}
1176
+ @pointercancel=${isDocked ? void 0 : this.handlePointerCancel}
1177
+ >
1178
+ <div class="flex flex-wrap items-center gap-3 px-4 py-3">
1179
+ <div class="flex items-center min-w-0">
1180
+ <img
1181
+ src=${require_inspector_logo.default}
1182
+ alt="Inspector logo"
1183
+ class="h-6 w-auto"
1184
+ loading="lazy"
1185
+ />
1186
+ </div>
1187
+ <div class="ml-auto flex min-w-0 items-center gap-2">
1188
+ <div class="min-w-[160px] max-w-xs">${agentSelector}</div>
1189
+ <div class="flex items-center gap-1">
1190
+ ${this.renderDockControls()}
1191
+ <button
1192
+ class="flex h-8 w-8 items-center justify-center rounded-md text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-400"
1193
+ type="button"
1194
+ aria-label="Close Web Inspector"
1195
+ @pointerdown=${this.handleClosePointerDown}
1196
+ @click=${this.handleCloseClick}
1197
+ >
1198
+ ${this.renderIcon("X")}
1199
+ </button>
1200
+ </div>
1201
+ </div>
1202
+ </div>
1203
+ <div
1204
+ class="flex flex-wrap items-center gap-2 border-t border-gray-100 px-3 py-2 text-xs"
1205
+ >
1206
+ ${this.menuItems.map(({ key, label, icon }) => {
1207
+ const isSelected = this.selectedMenu === key;
1208
+ return lit.html`
1209
+ <button
1210
+ type="button"
1211
+ class=${["inline-flex items-center gap-2 rounded-md px-3 py-2 transition focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-300", isSelected ? "bg-gray-900 text-white shadow-sm" : "text-gray-600 hover:bg-gray-100 hover:text-gray-900"].join(" ")}
1212
+ aria-pressed=${isSelected}
1213
+ @click=${() => this.handleMenuSelect(key)}
1214
+ >
1215
+ <span
1216
+ class="text-gray-400 ${isSelected ? "text-white" : ""}"
1217
+ >
1218
+ ${this.renderIcon(icon)}
1219
+ </span>
1220
+ <span>${label}</span>
1221
+ </button>
1222
+ `;
1223
+ })}
1224
+ </div>
1225
+ </div>
1226
+ <div class="flex flex-1 flex-col overflow-hidden">
1227
+ <div class="flex-1 overflow-auto">
1228
+ ${this.renderAnnouncementPanel()}
1229
+ ${this.renderCoreWarningBanner()} ${this.renderMainContent()}
1230
+ <slot></slot>
1231
+ </div>
1232
+ <div class="border-t border-gray-200 bg-gray-50 px-4 py-2">
1233
+ <div
1234
+ class="flex items-center gap-2 rounded-md px-3 py-2 text-xs ${coreStatus.tone} w-full overflow-hidden my-1"
1235
+ title=${coreStatus.description}
1236
+ >
1237
+ <span
1238
+ class="flex h-6 w-6 items-center justify-center rounded bg-white/60"
1239
+ >
1240
+ ${this.renderIcon("Activity")}
1241
+ </span>
1242
+ <span class="font-medium">${coreStatus.label}</span>
1243
+ <span class="truncate text-[11px] opacity-80"
1244
+ >${coreStatus.description}</span
1245
+ >
1246
+ </div>
1247
+ </div>
1248
+ </div>
1249
+ </div>
1250
+ <div
1251
+ class="resize-handle pointer-events-auto absolute bottom-1 right-1 flex h-5 w-5 cursor-nwse-resize items-center justify-center text-gray-400 transition hover:text-gray-600"
1252
+ role="presentation"
1253
+ aria-hidden="true"
1254
+ @pointerdown=${this.handleResizePointerDown}
1255
+ @pointermove=${this.handleResizePointerMove}
1256
+ @pointerup=${this.handleResizePointerUp}
1257
+ @pointercancel=${this.handleResizePointerCancel}
1258
+ >
1259
+ <svg
1260
+ class="h-3 w-3"
1261
+ viewBox="0 0 16 16"
1262
+ fill="none"
1263
+ stroke="currentColor"
1264
+ stroke-linecap="round"
1265
+ stroke-width="1.5"
1266
+ >
1267
+ <path d="M5 15L15 5" />
1268
+ <path d="M9 15L15 9" />
1269
+ </svg>
1270
+ </div>
1271
+ </section>
1272
+ `;
1273
+ }
1274
+ hydrateStateFromStorageEarly() {
1275
+ if (typeof document === "undefined" || typeof window === "undefined") return;
1276
+ const persisted = require_persistence.loadInspectorState(INSPECTOR_STORAGE_KEY);
1277
+ if (!persisted) return;
1278
+ if (typeof persisted.isOpen === "boolean") this.isOpen = persisted.isOpen;
1279
+ if (require_persistence.isValidDockMode(persisted.dockMode)) this.dockMode = persisted.dockMode;
1280
+ if (typeof persisted.selectedMenu === "string") {
1281
+ const validMenu = this.menuItems.find((item) => item.key === persisted.selectedMenu);
1282
+ if (validMenu) this.selectedMenu = validMenu.key;
1283
+ }
1284
+ if (typeof persisted.selectedContext === "string") {
1285
+ this.selectedContext = persisted.selectedContext;
1286
+ this.pendingSelectedContext = persisted.selectedContext;
1287
+ }
1288
+ }
1289
+ hydrateStateFromStorage() {
1290
+ if (typeof document === "undefined" || typeof window === "undefined") return;
1291
+ const persisted = require_persistence.loadInspectorState(INSPECTOR_STORAGE_KEY);
1292
+ if (!persisted) return;
1293
+ const persistedButton = persisted.button;
1294
+ if (persistedButton) {
1295
+ if (require_persistence.isValidAnchor(persistedButton.anchor)) this.contextState.button.anchor = persistedButton.anchor;
1296
+ if (require_persistence.isValidPosition(persistedButton.anchorOffset)) this.contextState.button.anchorOffset = persistedButton.anchorOffset;
1297
+ if (typeof persistedButton.hasCustomPosition === "boolean") this.hasCustomPosition.button = persistedButton.hasCustomPosition;
1298
+ }
1299
+ const persistedWindow = persisted.window;
1300
+ if (persistedWindow) {
1301
+ if (require_persistence.isValidAnchor(persistedWindow.anchor)) this.contextState.window.anchor = persistedWindow.anchor;
1302
+ if (require_persistence.isValidPosition(persistedWindow.anchorOffset)) this.contextState.window.anchorOffset = persistedWindow.anchorOffset;
1303
+ if (require_persistence.isValidSize(persistedWindow.size)) this.contextState.window.size = this.clampWindowSize(persistedWindow.size);
1304
+ if (typeof persistedWindow.hasCustomPosition === "boolean") this.hasCustomPosition.window = persistedWindow.hasCustomPosition;
1305
+ }
1306
+ if (typeof persisted.selectedContext === "string") {
1307
+ this.selectedContext = persisted.selectedContext;
1308
+ this.pendingSelectedContext = persisted.selectedContext;
1309
+ }
1310
+ }
1311
+ get activeContext() {
1312
+ return this.isOpen ? "window" : "button";
1313
+ }
1314
+ measureContext(context) {
1315
+ const selector = context === "window" ? ".inspector-window" : ".console-button";
1316
+ const element = this.renderRoot?.querySelector(selector);
1317
+ if (!element) return;
1318
+ const fallback = context === "window" ? DEFAULT_WINDOW_SIZE : DEFAULT_BUTTON_SIZE;
1319
+ require_context_helpers.updateSizeFromElement(this.contextState[context], element, fallback);
1320
+ }
1321
+ centerContext(context) {
1322
+ if (typeof window === "undefined") return;
1323
+ const viewport = this.getViewportSize();
1324
+ require_context_helpers.centerContext(this.contextState[context], viewport, EDGE_MARGIN);
1325
+ if (context === this.activeContext) this.updateHostTransform(context);
1326
+ this.hasCustomPosition[context] = false;
1327
+ this.persistState();
1328
+ }
1329
+ ensureWindowPlacement() {
1330
+ if (typeof window === "undefined") return;
1331
+ if (!this.hasCustomPosition.window) {
1332
+ this.centerContext("window");
1333
+ return;
1334
+ }
1335
+ const viewport = this.getViewportSize();
1336
+ require_context_helpers.keepPositionWithinViewport(this.contextState.window, viewport, EDGE_MARGIN);
1337
+ require_context_helpers.updateAnchorFromPosition(this.contextState.window, viewport, EDGE_MARGIN);
1338
+ this.updateHostTransform("window");
1339
+ this.persistState();
1340
+ }
1341
+ constrainToViewport(position, context) {
1342
+ if (typeof window === "undefined") return position;
1343
+ const viewport = this.getViewportSize();
1344
+ return require_context_helpers.constrainToViewport(this.contextState[context], position, viewport, EDGE_MARGIN);
1345
+ }
1346
+ keepPositionWithinViewport(context) {
1347
+ if (typeof window === "undefined") return;
1348
+ const viewport = this.getViewportSize();
1349
+ require_context_helpers.keepPositionWithinViewport(this.contextState[context], viewport, EDGE_MARGIN);
1350
+ }
1351
+ getViewportSize() {
1352
+ if (typeof window === "undefined") return { ...DEFAULT_WINDOW_SIZE };
1353
+ return {
1354
+ width: window.innerWidth,
1355
+ height: window.innerHeight
1356
+ };
1357
+ }
1358
+ persistState() {
1359
+ const state = {
1360
+ button: {
1361
+ anchor: this.contextState.button.anchor,
1362
+ anchorOffset: this.contextState.button.anchorOffset,
1363
+ hasCustomPosition: this.hasCustomPosition.button
1364
+ },
1365
+ window: {
1366
+ anchor: this.contextState.window.anchor,
1367
+ anchorOffset: this.contextState.window.anchorOffset,
1368
+ size: {
1369
+ width: Math.round(this.contextState.window.size.width),
1370
+ height: Math.round(this.contextState.window.size.height)
1371
+ },
1372
+ hasCustomPosition: this.hasCustomPosition.window
1373
+ },
1374
+ isOpen: this.isOpen,
1375
+ dockMode: this.dockMode,
1376
+ selectedMenu: this.selectedMenu,
1377
+ selectedContext: this.selectedContext
1378
+ };
1379
+ require_persistence.saveInspectorState(INSPECTOR_STORAGE_KEY, state);
1380
+ this.pendingSelectedContext = state.selectedContext ?? null;
1381
+ }
1382
+ clampWindowSize(size) {
1383
+ const minWidth = this.dockMode === "docked-left" ? MIN_WINDOW_WIDTH_DOCKED_LEFT : MIN_WINDOW_WIDTH;
1384
+ if (typeof window === "undefined") return {
1385
+ width: Math.max(minWidth, size.width),
1386
+ height: Math.max(MIN_WINDOW_HEIGHT, size.height)
1387
+ };
1388
+ return require_context_helpers.clampSize(size, this.getViewportSize(), EDGE_MARGIN, minWidth, MIN_WINDOW_HEIGHT);
1389
+ }
1390
+ setDockMode(mode) {
1391
+ if (this.dockMode === mode) return;
1392
+ this.startHostTransition();
1393
+ this.removeDockStyles();
1394
+ this.dockMode = mode;
1395
+ if (mode !== "floating") {
1396
+ if (mode === "docked-left") this.contextState.window.size.width = DOCKED_LEFT_WIDTH;
1397
+ this.applyDockStyles();
1398
+ } else {
1399
+ this.contextState.window.size = { ...DEFAULT_WINDOW_SIZE };
1400
+ this.centerContext("window");
1401
+ }
1402
+ this.persistState();
1403
+ this.requestUpdate();
1404
+ this.updateHostTransform("window");
1405
+ }
1406
+ startHostTransition(duration = 300) {
1407
+ this.setAttribute("data-transitioning", "true");
1408
+ if (this.transitionTimeoutId !== null) clearTimeout(this.transitionTimeoutId);
1409
+ this.transitionTimeoutId = setTimeout(() => {
1410
+ this.removeAttribute("data-transitioning");
1411
+ this.transitionTimeoutId = null;
1412
+ }, duration);
1413
+ }
1414
+ applyDockStyles(skipTransition = false) {
1415
+ if (typeof document === "undefined" || !document.body) return;
1416
+ const computedStyle = window.getComputedStyle(document.body);
1417
+ this.previousBodyMargins = {
1418
+ left: computedStyle.marginLeft,
1419
+ bottom: computedStyle.marginBottom
1420
+ };
1421
+ if (!this.isResizing && !skipTransition) document.body.style.transition = "margin 300ms ease";
1422
+ if (this.dockMode === "docked-left") document.body.style.marginLeft = `${this.contextState.window.size.width}px`;
1423
+ if (!this.isResizing && !skipTransition) {
1424
+ const id = setTimeout(() => {
1425
+ this.bodyTransitionTimeoutIds.delete(id);
1426
+ if (typeof document !== "undefined" && document.body) document.body.style.transition = "";
1427
+ }, 300);
1428
+ this.bodyTransitionTimeoutIds.add(id);
1429
+ }
1430
+ }
1431
+ removeDockStyles(skipTransition = false) {
1432
+ if (typeof document === "undefined" || !document.body) return;
1433
+ if (!this.isResizing && !skipTransition) document.body.style.transition = "margin 300ms ease";
1434
+ if (this.previousBodyMargins) {
1435
+ document.body.style.marginLeft = this.previousBodyMargins.left;
1436
+ document.body.style.marginBottom = this.previousBodyMargins.bottom;
1437
+ this.previousBodyMargins = null;
1438
+ } else {
1439
+ document.body.style.marginLeft = "";
1440
+ document.body.style.marginBottom = "";
1441
+ }
1442
+ if (!skipTransition) {
1443
+ const id = setTimeout(() => {
1444
+ this.bodyTransitionTimeoutIds.delete(id);
1445
+ if (typeof document !== "undefined" && document.body) document.body.style.transition = "";
1446
+ }, 300);
1447
+ this.bodyTransitionTimeoutIds.add(id);
1448
+ } else document.body.style.transition = "";
1449
+ }
1450
+ updateHostTransform(context = this.activeContext) {
1451
+ if (context !== this.activeContext) return;
1452
+ if (this.isOpen && this.dockMode === "docked-left") this.style.transform = `translate3d(0, 0, 0)`;
1453
+ else {
1454
+ const { position } = this.contextState[context];
1455
+ this.style.transform = `translate3d(${position.x}px, ${position.y}px, 0)`;
1456
+ }
1457
+ }
1458
+ setDragging(value) {
1459
+ if (this.isDragging !== value) {
1460
+ this.isDragging = value;
1461
+ this.requestUpdate();
1462
+ }
1463
+ }
1464
+ updateAnchorFromPosition(context) {
1465
+ if (typeof window === "undefined") return;
1466
+ const viewport = this.getViewportSize();
1467
+ require_context_helpers.updateAnchorFromPosition(this.contextState[context], viewport, EDGE_MARGIN);
1468
+ }
1469
+ snapButtonToCorner() {
1470
+ if (typeof window === "undefined") return;
1471
+ const viewport = this.getViewportSize();
1472
+ const state = this.contextState.button;
1473
+ const centerX = state.position.x + state.size.width / 2;
1474
+ const centerY = state.position.y + state.size.height / 2;
1475
+ state.anchor = {
1476
+ horizontal: centerX < viewport.width / 2 ? "left" : "right",
1477
+ vertical: centerY < viewport.height / 2 ? "top" : "bottom"
1478
+ };
1479
+ state.anchorOffset = {
1480
+ x: EDGE_MARGIN,
1481
+ y: EDGE_MARGIN
1482
+ };
1483
+ this.startHostTransition();
1484
+ this.applyAnchorPosition("button");
1485
+ }
1486
+ applyAnchorPosition(context) {
1487
+ if (typeof window === "undefined") return;
1488
+ const viewport = this.getViewportSize();
1489
+ require_context_helpers.applyAnchorPosition(this.contextState[context], viewport, EDGE_MARGIN);
1490
+ this.updateHostTransform(context);
1491
+ this.persistState();
1492
+ }
1493
+ resetResizeTracking() {
1494
+ this.resizePointerId = null;
1495
+ this.resizeStart = null;
1496
+ this.resizeInitialSize = null;
1497
+ this.isResizing = false;
1498
+ }
1499
+ resetPointerTracking() {
1500
+ this.pointerId = null;
1501
+ this.dragStart = null;
1502
+ this.pointerContext = null;
1503
+ this.setDragging(false);
1504
+ this.draggedDuringInteraction = false;
1505
+ }
1506
+ openInspector() {
1507
+ if (this.isOpen) return;
1508
+ this.showAnnouncementPreview = false;
1509
+ this.ensureAnnouncementLoading();
1510
+ this.isOpen = true;
1511
+ this.persistState();
1512
+ if (this.dockMode !== "floating") this.applyDockStyles();
1513
+ this.ensureWindowPlacement();
1514
+ this.requestUpdate();
1515
+ this.updateComplete.then(() => {
1516
+ this.measureContext("window");
1517
+ if (this.dockMode === "floating") if (this.hasCustomPosition.window) this.applyAnchorPosition("window");
1518
+ else this.centerContext("window");
1519
+ else this.updateHostTransform("window");
1520
+ });
1521
+ }
1522
+ closeInspector() {
1523
+ if (!this.isOpen) return;
1524
+ this.isOpen = false;
1525
+ if (this.dockMode !== "floating") this.removeDockStyles();
1526
+ this.persistState();
1527
+ this.updateHostTransform("button");
1528
+ this.requestUpdate();
1529
+ this.updateComplete.then(() => {
1530
+ this.measureContext("button");
1531
+ this.applyAnchorPosition("button");
1532
+ });
1533
+ }
1534
+ renderIcon(name) {
1535
+ const iconNode = lucide.icons[name];
1536
+ if (!iconNode) return lit.nothing;
1537
+ return (0, lit_directives_unsafe_html_js.unsafeHTML)(`<svg ${this.serializeAttributes({
1538
+ xmlns: "http://www.w3.org/2000/svg",
1539
+ viewBox: "0 0 24 24",
1540
+ fill: "none",
1541
+ stroke: "currentColor",
1542
+ "stroke-width": "1.5",
1543
+ "stroke-linecap": "round",
1544
+ "stroke-linejoin": "round",
1545
+ class: "h-3.5 w-3.5"
1546
+ })}>${iconNode.map(([tag, attrs]) => `<${tag} ${this.serializeAttributes(attrs)} />`).join("")}</svg>`);
1547
+ }
1548
+ renderDockControls() {
1549
+ if (this.dockMode === "floating") return lit.html`
1550
+ <button
1551
+ class="flex h-8 w-8 items-center justify-center rounded-md text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-400"
1552
+ type="button"
1553
+ aria-label="Dock to left"
1554
+ title="Dock Left"
1555
+ @click=${() => this.handleDockClick("docked-left")}
1556
+ >
1557
+ ${this.renderIcon("PanelLeft")}
1558
+ </button>
1559
+ `;
1560
+ else return lit.html`
1561
+ <button
1562
+ class="flex h-8 w-8 items-center justify-center rounded-md text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-400"
1563
+ type="button"
1564
+ aria-label="Float window"
1565
+ title="Float"
1566
+ @click=${() => this.handleDockClick("floating")}
1567
+ >
1568
+ ${this.renderIcon("Maximize2")}
1569
+ </button>
1570
+ `;
1571
+ }
1572
+ getDockedWindowStyles() {
1573
+ if (this.dockMode === "docked-left") return {
1574
+ position: "fixed",
1575
+ top: "0",
1576
+ left: "0",
1577
+ bottom: "0",
1578
+ width: `${Math.round(this.contextState.window.size.width)}px`,
1579
+ height: "100vh",
1580
+ minWidth: `${MIN_WINDOW_WIDTH_DOCKED_LEFT}px`,
1581
+ borderRadius: "0"
1582
+ };
1583
+ return {
1584
+ width: `${Math.round(this.contextState.window.size.width)}px`,
1585
+ height: `${Math.round(this.contextState.window.size.height)}px`,
1586
+ minWidth: `${MIN_WINDOW_WIDTH}px`,
1587
+ minHeight: `${MIN_WINDOW_HEIGHT}px`
1588
+ };
1589
+ }
1590
+ handleDockClick(mode) {
1591
+ this.setDockMode(mode);
1592
+ }
1593
+ serializeAttributes(attributes) {
1594
+ return Object.entries(attributes).filter(([key, value]) => key !== "key" && value !== void 0 && value !== null && value !== "").map(([key, value]) => `${key}="${String(value).replace(/"/g, "&quot;")}"`).join(" ");
1595
+ }
1596
+ sanitizeForLogging(value, depth = 0, seen = /* @__PURE__ */ new WeakSet()) {
1597
+ if (value === void 0) return "[undefined]";
1598
+ if (value === null || typeof value === "number" || typeof value === "boolean") return value;
1599
+ if (typeof value === "string") return value;
1600
+ if (typeof value === "bigint" || typeof value === "symbol" || typeof value === "function") return String(value);
1601
+ if (value instanceof Date) return value.toISOString();
1602
+ if (Array.isArray(value)) {
1603
+ if (depth >= 4) return "[Truncated depth]";
1604
+ return value.map((item) => this.sanitizeForLogging(item, depth + 1, seen));
1605
+ }
1606
+ if (typeof value === "object") {
1607
+ if (seen.has(value)) return "[Circular]";
1608
+ seen.add(value);
1609
+ if (depth >= 4) return "[Truncated depth]";
1610
+ const result = {};
1611
+ for (const [key, entry] of Object.entries(value)) result[key] = this.sanitizeForLogging(entry, depth + 1, seen);
1612
+ return result;
1613
+ }
1614
+ return String(value);
1615
+ }
1616
+ normalizeEventPayload(_type, payload) {
1617
+ if (payload && typeof payload === "object" && "event" in payload) {
1618
+ const { event, ...rest } = payload;
1619
+ const cleaned = Object.keys(rest).length === 0 ? event : {
1620
+ event,
1621
+ ...rest
1622
+ };
1623
+ return this.sanitizeForLogging(cleaned);
1624
+ }
1625
+ return this.sanitizeForLogging(payload);
1626
+ }
1627
+ normalizeMessageContent(content) {
1628
+ if (typeof content === "string") return content;
1629
+ if (content && typeof content === "object" && "text" in content) {
1630
+ const maybeText = content.text;
1631
+ if (typeof maybeText === "string") return maybeText;
1632
+ }
1633
+ if (content === null || content === void 0) return "";
1634
+ if (typeof content === "object") try {
1635
+ return JSON.stringify(this.sanitizeForLogging(content));
1636
+ } catch {
1637
+ return "";
1638
+ }
1639
+ return String(content);
1640
+ }
1641
+ normalizeToolCalls(raw) {
1642
+ if (!Array.isArray(raw)) return [];
1643
+ return raw.map((entry) => {
1644
+ if (!entry || typeof entry !== "object") return null;
1645
+ const call = entry;
1646
+ const fn = call.function;
1647
+ const functionName = typeof fn?.name === "string" ? fn.name : typeof call.toolName === "string" ? call.toolName : void 0;
1648
+ const args = fn && "arguments" in fn ? fn.arguments : call.arguments;
1649
+ const normalized = {
1650
+ id: typeof call.id === "string" ? call.id : void 0,
1651
+ toolName: typeof call.toolName === "string" ? call.toolName : functionName,
1652
+ status: typeof call.status === "string" ? call.status : void 0
1653
+ };
1654
+ if (functionName) normalized.function = {
1655
+ name: functionName,
1656
+ arguments: this.sanitizeForLogging(args)
1657
+ };
1658
+ return normalized;
1659
+ }).filter((call) => Boolean(call));
1660
+ }
1661
+ normalizeAgentMessage(message) {
1662
+ if (!message || typeof message !== "object") return null;
1663
+ const raw = message;
1664
+ const role = typeof raw.role === "string" ? raw.role : "unknown";
1665
+ const contentText = this.normalizeMessageContent(raw.content);
1666
+ const toolCalls = this.normalizeToolCalls(raw.toolCalls);
1667
+ return {
1668
+ id: typeof raw.id === "string" ? raw.id : void 0,
1669
+ role,
1670
+ contentText,
1671
+ contentRaw: raw.content !== void 0 ? this.sanitizeForLogging(raw.content) : void 0,
1672
+ toolCalls
1673
+ };
1674
+ }
1675
+ normalizeAgentMessages(messages) {
1676
+ if (!Array.isArray(messages)) return null;
1677
+ return messages.map((message) => this.normalizeAgentMessage(message)).filter((msg) => msg !== null);
1678
+ }
1679
+ normalizeContextStore(context) {
1680
+ if (!context || typeof context !== "object") return {};
1681
+ const normalized = {};
1682
+ for (const [key, entry] of Object.entries(context)) if (entry && typeof entry === "object" && "value" in entry) {
1683
+ const candidate = entry;
1684
+ normalized[key] = {
1685
+ description: typeof candidate.description === "string" && candidate.description.trim().length > 0 ? candidate.description : void 0,
1686
+ value: candidate.value
1687
+ };
1688
+ } else normalized[key] = { value: entry };
1689
+ return normalized;
1690
+ }
1691
+ getSelectedMenu() {
1692
+ return this.menuItems.find((item) => item.key === this.selectedMenu) ?? this.menuItems[0];
1693
+ }
1694
+ renderCoreWarningBanner() {
1695
+ if (this._core) return lit.nothing;
1696
+ return lit.html`
1697
+ <div
1698
+ class="mx-4 my-3 flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800"
1699
+ >
1700
+ <span class="mt-0.5 shrink-0 text-amber-600"
1701
+ >${this.renderIcon("AlertTriangle")}</span
1702
+ >
1703
+ <div class="space-y-1">
1704
+ <div class="font-semibold text-amber-900">
1705
+ CopilotKit core not attached
1706
+ </div>
1707
+ <p class="text-[11px] leading-snug text-amber-800">
1708
+ Pass a live <code>CopilotKitCore</code> instance to
1709
+ <code>&lt;cpk-web-inspector&gt;</code> or expose it on
1710
+ <code>window.__COPILOTKIT_CORE__</code> for auto-attach.
1711
+ </p>
1712
+ </div>
1713
+ </div>
1714
+ `;
1715
+ }
1716
+ getCoreStatusSummary() {
1717
+ if (!this._core) return {
1718
+ label: "Core not attached",
1719
+ tone: "border border-amber-200 bg-amber-50 text-amber-800",
1720
+ description: "Pass a CopilotKitCore instance to <cpk-web-inspector> or enable auto-attach."
1721
+ };
1722
+ const status = this.runtimeStatus ?? _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Disconnected;
1723
+ const lastErrorMessage = this.lastCoreError?.message;
1724
+ if (status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Error) return {
1725
+ label: "Runtime error",
1726
+ tone: "border border-rose-200 bg-rose-50 text-rose-700",
1727
+ description: lastErrorMessage ?? "CopilotKit runtime reported an error."
1728
+ };
1729
+ if (status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Connecting) return {
1730
+ label: "Connecting",
1731
+ tone: "border border-amber-200 bg-amber-50 text-amber-800",
1732
+ description: "Waiting for CopilotKit runtime to finish connecting."
1733
+ };
1734
+ if (status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Connected) return {
1735
+ label: "Connected",
1736
+ tone: "border border-emerald-200 bg-emerald-50 text-emerald-700",
1737
+ description: "Live runtime connection established."
1738
+ };
1739
+ return {
1740
+ label: "Disconnected",
1741
+ tone: "border border-gray-200 bg-gray-50 text-gray-700",
1742
+ description: lastErrorMessage ?? "Waiting for CopilotKit runtime to connect."
1743
+ };
1744
+ }
1745
+ renderMainContent() {
1746
+ if (this.selectedMenu === "ag-ui-events") return this.renderEventsTable();
1747
+ if (this.selectedMenu === "agents") return this.renderAgentsView();
1748
+ if (this.selectedMenu === "frontend-tools") return this.renderToolsView();
1749
+ if (this.selectedMenu === "agent-context") return this.renderContextView();
1750
+ return lit.nothing;
1751
+ }
1752
+ renderEventsTable() {
1753
+ const events = this.getEventsForSelectedContext();
1754
+ const filteredEvents = this.filterEvents(events);
1755
+ const selectedLabel = this.selectedContext === "all-agents" ? "all agents" : `agent ${this.selectedContext}`;
1756
+ if (events.length === 0) return lit.html`
1757
+ <div
1758
+ class="flex h-full items-center justify-center px-4 py-8 text-center"
1759
+ >
1760
+ <div class="max-w-md">
1761
+ <div
1762
+ class="mb-3 flex justify-center text-gray-300 [&>svg]:!h-8 [&>svg]:!w-8"
1763
+ >
1764
+ ${this.renderIcon("Zap")}
1765
+ </div>
1766
+ <p class="text-sm text-gray-600">No events yet</p>
1767
+ <p class="mt-2 text-xs text-gray-500">
1768
+ Trigger an agent run to see live activity.
1769
+ </p>
1770
+ </div>
1771
+ </div>
1772
+ `;
1773
+ if (filteredEvents.length === 0) return lit.html`
1774
+ <div
1775
+ class="flex h-full items-center justify-center px-4 py-8 text-center"
1776
+ >
1777
+ <div class="max-w-md space-y-3">
1778
+ <div
1779
+ class="flex justify-center text-gray-300 [&>svg]:!h-8 [&>svg]:!w-8"
1780
+ >
1781
+ ${this.renderIcon("Filter")}
1782
+ </div>
1783
+ <p class="text-sm text-gray-600">
1784
+ No events match the current filters.
1785
+ </p>
1786
+ <div>
1787
+ <button
1788
+ type="button"
1789
+ class="inline-flex items-center gap-1 rounded-md bg-gray-900 px-3 py-1.5 text-[11px] font-medium text-white transition hover:bg-gray-800"
1790
+ @click=${this.resetEventFilters}
1791
+ >
1792
+ ${this.renderIcon("RefreshCw")}
1793
+ <span>Reset filters</span>
1794
+ </button>
1795
+ </div>
1796
+ </div>
1797
+ </div>
1798
+ `;
1799
+ return lit.html`
1800
+ <div class="flex h-full flex-col">
1801
+ <div
1802
+ class="flex flex-col gap-1.5 border-b border-gray-200 bg-white px-4 py-2.5"
1803
+ >
1804
+ <div class="flex flex-wrap items-center gap-2">
1805
+ <div class="relative min-w-[200px] flex-1">
1806
+ <input
1807
+ type="search"
1808
+ class="w-full rounded-md border border-gray-200 px-3 py-1.5 text-[11px] text-gray-700 shadow-sm outline-none ring-1 ring-transparent transition focus:border-gray-300 focus:ring-gray-200"
1809
+ placeholder="Search agent, type, payload"
1810
+ .value=${this.eventFilterText}
1811
+ @input=${this.handleEventFilterInput}
1812
+ />
1813
+ </div>
1814
+ <select
1815
+ class="w-40 rounded-md border border-gray-200 bg-white px-2 py-1.5 text-[11px] text-gray-700 shadow-sm outline-none transition focus:border-gray-300 focus:ring-2 focus:ring-gray-200"
1816
+ .value=${this.eventTypeFilter}
1817
+ @change=${this.handleEventTypeChange}
1818
+ >
1819
+ <option value="all">All event types</option>
1820
+ ${AGENT_EVENT_TYPES.map((type) => lit.html`<option value=${type}>
1821
+ ${type.toLowerCase().replace(/_/g, " ")}
1822
+ </option>`)}
1823
+ </select>
1824
+ <div class="flex items-center gap-1 text-[11px]">
1825
+ <button
1826
+ type="button"
1827
+ class="tooltip-target flex h-8 w-8 items-center justify-center rounded-md border border-gray-200 bg-white text-gray-600 transition hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50"
1828
+ title="Reset filters"
1829
+ data-tooltip="Reset filters"
1830
+ aria-label="Reset filters"
1831
+ @click=${this.resetEventFilters}
1832
+ ?disabled=${!this.eventFilterText && this.eventTypeFilter === "all"}
1833
+ >
1834
+ ${this.renderIcon("RotateCw")}
1835
+ </button>
1836
+ <button
1837
+ type="button"
1838
+ class="tooltip-target flex h-8 w-8 items-center justify-center rounded-md border border-gray-200 bg-white text-gray-600 transition hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50"
1839
+ title="Export JSON"
1840
+ data-tooltip="Export JSON"
1841
+ aria-label="Export JSON"
1842
+ @click=${() => this.exportEvents(filteredEvents)}
1843
+ ?disabled=${filteredEvents.length === 0}
1844
+ >
1845
+ ${this.renderIcon("Download")}
1846
+ </button>
1847
+ <button
1848
+ type="button"
1849
+ class="tooltip-target flex h-8 w-8 items-center justify-center rounded-md border border-gray-200 bg-white text-gray-600 transition hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50"
1850
+ title="Clear events"
1851
+ data-tooltip="Clear events"
1852
+ aria-label="Clear events"
1853
+ @click=${this.handleClearEvents}
1854
+ ?disabled=${events.length === 0}
1855
+ >
1856
+ ${this.renderIcon("Trash2")}
1857
+ </button>
1858
+ </div>
1859
+ </div>
1860
+ <div class="text-[11px] text-gray-500">
1861
+ Showing ${filteredEvents.length} of
1862
+ ${events.length}${this.selectedContext === "all-agents" ? "" : ` for ${selectedLabel}`}
1863
+ </div>
1864
+ </div>
1865
+ <div class="relative h-full w-full overflow-y-auto overflow-x-hidden">
1866
+ <table class="w-full table-fixed border-collapse text-xs box-border">
1867
+ <thead class="sticky top-0 z-10">
1868
+ <tr class="bg-white">
1869
+ <th
1870
+ class="border-b border-gray-200 bg-white px-3 py-2 text-left font-medium text-gray-900"
1871
+ >
1872
+ Agent
1873
+ </th>
1874
+ <th
1875
+ class="border-b border-gray-200 bg-white px-3 py-2 text-left font-medium text-gray-900"
1876
+ >
1877
+ Time
1878
+ </th>
1879
+ <th
1880
+ class="border-b border-gray-200 bg-white px-3 py-2 text-left font-medium text-gray-900"
1881
+ >
1882
+ Event Type
1883
+ </th>
1884
+ <th
1885
+ class="border-b border-gray-200 bg-white px-3 py-2 text-left font-medium text-gray-900"
1886
+ >
1887
+ AG-UI Event
1888
+ </th>
1889
+ </tr>
1890
+ </thead>
1891
+ <tbody>
1892
+ ${filteredEvents.map((event, index) => {
1893
+ const rowBg = index % 2 === 0 ? "bg-white" : "bg-gray-50/50";
1894
+ const badgeClasses = this.getEventBadgeClasses(event.type);
1895
+ const extractedEvent = this.extractEventFromPayload(event.payload);
1896
+ const inlineEvent = this.stringifyPayload(extractedEvent, false) || "—";
1897
+ const prettyEvent = this.stringifyPayload(extractedEvent, true) || inlineEvent;
1898
+ const isExpanded = this.expandedRows.has(event.id);
1899
+ return lit.html`
1900
+ <tr
1901
+ class="${rowBg} cursor-pointer transition hover:bg-blue-50/50"
1902
+ @click=${() => this.toggleRowExpansion(event.id)}
1903
+ >
1904
+ <td
1905
+ class="border-l border-r border-b border-gray-200 px-3 py-2"
1906
+ >
1907
+ <span class="font-mono text-[11px] text-gray-600"
1908
+ >${event.agentId}</span
1909
+ >
1910
+ </td>
1911
+ <td
1912
+ class="border-r border-b border-gray-200 px-3 py-2 font-mono text-[11px] text-gray-600"
1913
+ >
1914
+ <span title=${new Date(event.timestamp).toLocaleString()}>
1915
+ ${new Date(event.timestamp).toLocaleTimeString()}
1916
+ </span>
1917
+ </td>
1918
+ <td class="border-r border-b border-gray-200 px-3 py-2">
1919
+ <span class=${badgeClasses}>${event.type}</span>
1920
+ </td>
1921
+ <td
1922
+ class="border-r border-b border-gray-200 px-3 py-2 font-mono text-[10px] text-gray-600 ${isExpanded ? "" : "truncate max-w-xs"}"
1923
+ >
1924
+ ${isExpanded ? lit.html`
1925
+ <div class="group relative">
1926
+ <pre
1927
+ class="m-0 whitespace-pre-wrap break-words text-[10px] font-mono text-gray-600"
1928
+ >
1929
+ ${prettyEvent}</pre
1930
+ >
1931
+ <button
1932
+ class="absolute right-0 top-0 cursor-pointer rounded px-2 py-1 text-[10px] opacity-0 transition group-hover:opacity-100 ${this.copiedEvents.has(event.id) ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-600 hover:bg-gray-200 hover:text-gray-900"}"
1933
+ @click=${(e) => {
1934
+ e.stopPropagation();
1935
+ this.copyToClipboard(prettyEvent, event.id);
1936
+ }}
1937
+ >
1938
+ ${this.copiedEvents.has(event.id) ? lit.html`
1939
+ <span>✓ Copied</span>
1940
+ ` : lit.html`
1941
+ <span>Copy</span>
1942
+ `}
1943
+ </button>
1944
+ </div>
1945
+ ` : inlineEvent}
1946
+ </td>
1947
+ </tr>
1948
+ `;
1949
+ })}
1950
+ </tbody>
1951
+ </table>
1952
+ </div>
1953
+ </div>
1954
+ `;
1955
+ }
1956
+ handleEventFilterInput(event) {
1957
+ this.eventFilterText = event.target?.value ?? "";
1958
+ this.requestUpdate();
1959
+ }
1960
+ handleEventTypeChange(event) {
1961
+ const value = event.target?.value;
1962
+ if (!value) return;
1963
+ this.eventTypeFilter = value;
1964
+ this.requestUpdate();
1965
+ }
1966
+ resetEventFilters() {
1967
+ this.eventFilterText = "";
1968
+ this.eventTypeFilter = "all";
1969
+ this.requestUpdate();
1970
+ }
1971
+ exportEvents(events) {
1972
+ try {
1973
+ const payload = JSON.stringify(events, null, 2);
1974
+ const blob = new Blob([payload], { type: "application/json" });
1975
+ const url = URL.createObjectURL(blob);
1976
+ const anchor = document.createElement("a");
1977
+ anchor.href = url;
1978
+ anchor.download = `copilotkit-events-${Date.now()}.json`;
1979
+ anchor.click();
1980
+ URL.revokeObjectURL(url);
1981
+ } catch (error) {
1982
+ console.error("Failed to export events", error);
1983
+ }
1984
+ }
1985
+ renderAgentsView() {
1986
+ if (this.selectedContext === "all-agents") return lit.html`
1987
+ <div
1988
+ class="flex h-full items-center justify-center px-4 py-8 text-center"
1989
+ >
1990
+ <div class="max-w-md">
1991
+ <div
1992
+ class="mb-3 flex justify-center text-gray-300 [&>svg]:!h-8 [&>svg]:!w-8"
1993
+ >
1994
+ ${this.renderIcon("Bot")}
1995
+ </div>
1996
+ <p class="text-sm text-gray-600">No agent selected</p>
1997
+ <p class="mt-2 text-xs text-gray-500">
1998
+ Select an agent from the dropdown above to view details.
1999
+ </p>
2000
+ </div>
2001
+ </div>
2002
+ `;
2003
+ const agentId = this.selectedContext;
2004
+ const status = this.getAgentStatus(agentId);
2005
+ const stats = this.getAgentStats(agentId);
2006
+ const state = this.getLatestStateForAgent(agentId);
2007
+ const messages = this.getLatestMessagesForAgent(agentId);
2008
+ return lit.html`
2009
+ <div class="flex flex-col gap-4 p-4 overflow-auto">
2010
+ <!-- Agent Overview Card -->
2011
+ <div class="rounded-lg border border-gray-200 bg-white p-4">
2012
+ <div class="flex items-start justify-between mb-4">
2013
+ <div class="flex items-center gap-3">
2014
+ <div
2015
+ class="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-100 text-blue-600"
2016
+ >
2017
+ ${this.renderIcon("Bot")}
2018
+ </div>
2019
+ <div>
2020
+ <h3 class="font-semibold text-sm text-gray-900">${agentId}</h3>
2021
+ <span
2022
+ class="inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-medium ${{
2023
+ running: "bg-emerald-50 text-emerald-700",
2024
+ idle: "bg-gray-100 text-gray-600",
2025
+ error: "bg-rose-50 text-rose-700"
2026
+ }[status]} relative -translate-y-[2px]"
2027
+ >
2028
+ <span
2029
+ class="h-1.5 w-1.5 rounded-full ${status === "running" ? "bg-emerald-500 animate-pulse" : status === "error" ? "bg-rose-500" : "bg-gray-400"}"
2030
+ ></span>
2031
+ ${status.charAt(0).toUpperCase() + status.slice(1)}
2032
+ </span>
2033
+ </div>
2034
+ </div>
2035
+ ${stats.lastActivity ? lit.html`<span class="text-xs text-gray-500"
2036
+ >Last activity:
2037
+ ${new Date(stats.lastActivity).toLocaleTimeString()}</span
2038
+ >` : lit.nothing}
2039
+ </div>
2040
+ <div class="grid grid-cols-2 gap-4 md:grid-cols-4">
2041
+ <button
2042
+ type="button"
2043
+ class="rounded-md bg-gray-50 px-3 py-2 text-left transition hover:bg-gray-100 cursor-pointer overflow-hidden"
2044
+ @click=${() => this.handleMenuSelect("ag-ui-events")}
2045
+ title="View all events in AG-UI Events"
2046
+ >
2047
+ <div class="truncate whitespace-nowrap text-xs text-gray-600">
2048
+ Total Events
2049
+ </div>
2050
+ <div class="text-lg font-semibold text-gray-900">
2051
+ ${stats.totalEvents}
2052
+ </div>
2053
+ </button>
2054
+ <div class="rounded-md bg-gray-50 px-3 py-2 overflow-hidden">
2055
+ <div class="truncate whitespace-nowrap text-xs text-gray-600">
2056
+ Messages
2057
+ </div>
2058
+ <div class="text-lg font-semibold text-gray-900">
2059
+ ${stats.messages}
2060
+ </div>
2061
+ </div>
2062
+ <div class="rounded-md bg-gray-50 px-3 py-2 overflow-hidden">
2063
+ <div class="truncate whitespace-nowrap text-xs text-gray-600">
2064
+ Tool Calls
2065
+ </div>
2066
+ <div class="text-lg font-semibold text-gray-900">
2067
+ ${stats.toolCalls}
2068
+ </div>
2069
+ </div>
2070
+ <div class="rounded-md bg-gray-50 px-3 py-2 overflow-hidden">
2071
+ <div class="truncate whitespace-nowrap text-xs text-gray-600">
2072
+ Errors
2073
+ </div>
2074
+ <div class="text-lg font-semibold text-gray-900">
2075
+ ${stats.errors}
2076
+ </div>
2077
+ </div>
2078
+ </div>
2079
+ </div>
2080
+
2081
+ <!-- Current State Section -->
2082
+ <div class="rounded-lg border border-gray-200 bg-white">
2083
+ <div class="border-b border-gray-200 px-4 py-3">
2084
+ <h4 class="text-sm font-semibold text-gray-900">Current State</h4>
2085
+ </div>
2086
+ <div class="overflow-auto p-4">
2087
+ ${this.hasRenderableState(state) ? lit.html`
2088
+ <pre
2089
+ class="overflow-auto rounded-md bg-gray-50 p-3 text-xs text-gray-800 max-h-64"
2090
+ ><code>${this.formatStateForDisplay(state)}</code></pre>
2091
+ ` : lit.html`
2092
+ <div
2093
+ class="flex h-40 items-center justify-center text-xs text-gray-500"
2094
+ >
2095
+ <div class="flex items-center gap-2 text-gray-500">
2096
+ <span class="text-lg text-gray-400"
2097
+ >${this.renderIcon("Database")}</span
2098
+ >
2099
+ <span>State is empty</span>
2100
+ </div>
2101
+ </div>
2102
+ `}
2103
+ </div>
2104
+ </div>
2105
+
2106
+ <!-- Current Messages Section -->
2107
+ <div class="rounded-lg border border-gray-200 bg-white">
2108
+ <div class="border-b border-gray-200 px-4 py-3">
2109
+ <h4 class="text-sm font-semibold text-gray-900">
2110
+ Current Messages
2111
+ </h4>
2112
+ </div>
2113
+ <div class="overflow-auto">
2114
+ ${messages && messages.length > 0 ? lit.html`
2115
+ <table class="w-full text-xs">
2116
+ <thead class="bg-gray-50">
2117
+ <tr>
2118
+ <th
2119
+ class="px-4 py-2 text-left font-medium text-gray-700"
2120
+ >
2121
+ Role
2122
+ </th>
2123
+ <th
2124
+ class="px-4 py-2 text-left font-medium text-gray-700"
2125
+ >
2126
+ Content
2127
+ </th>
2128
+ </tr>
2129
+ </thead>
2130
+ <tbody class="divide-y divide-gray-200">
2131
+ ${messages.map((msg) => {
2132
+ const role = msg.role || "unknown";
2133
+ const roleColors = {
2134
+ user: "bg-blue-100 text-blue-800",
2135
+ assistant: "bg-green-100 text-green-800",
2136
+ system: "bg-gray-100 text-gray-800",
2137
+ tool: "bg-amber-100 text-amber-800",
2138
+ unknown: "bg-gray-100 text-gray-600"
2139
+ };
2140
+ const rawContent = msg.contentText ?? "";
2141
+ const toolCalls = msg.toolCalls ?? [];
2142
+ const hasContent = rawContent.trim().length > 0;
2143
+ const contentFallback = toolCalls.length > 0 ? "Invoked tool call" : "—";
2144
+ return lit.html`
2145
+ <tr>
2146
+ <td class="px-4 py-2 align-top">
2147
+ <span
2148
+ class="inline-flex rounded px-2 py-0.5 text-[10px] font-medium ${roleColors[role] || roleColors.unknown}"
2149
+ >
2150
+ ${role}
2151
+ </span>
2152
+ </td>
2153
+ <td class="px-4 py-2">
2154
+ ${hasContent ? lit.html`<div
2155
+ class="max-w-2xl whitespace-pre-wrap break-words text-gray-700"
2156
+ >
2157
+ ${rawContent}
2158
+ </div>` : lit.html`<div
2159
+ class="text-xs italic text-gray-400"
2160
+ >
2161
+ ${contentFallback}
2162
+ </div>`}
2163
+ ${role === "assistant" && toolCalls.length > 0 ? this.renderToolCallDetails(toolCalls) : lit.nothing}
2164
+ </td>
2165
+ </tr>
2166
+ `;
2167
+ })}
2168
+ </tbody>
2169
+ </table>
2170
+ ` : lit.html`
2171
+ <div
2172
+ class="flex h-40 items-center justify-center text-xs text-gray-500"
2173
+ >
2174
+ <div class="flex items-center gap-2 text-gray-500">
2175
+ <span class="text-lg text-gray-400"
2176
+ >${this.renderIcon("MessageSquare")}</span
2177
+ >
2178
+ <span>No messages available</span>
2179
+ </div>
2180
+ </div>
2181
+ `}
2182
+ </div>
2183
+ </div>
2184
+ </div>
2185
+ `;
2186
+ }
2187
+ renderContextDropdown() {
2188
+ const filteredOptions = this.selectedMenu === "agents" ? this.contextOptions.filter((opt) => opt.key !== "all-agents") : this.contextOptions;
2189
+ const selectedLabel = filteredOptions.find((opt) => opt.key === this.selectedContext)?.label ?? "";
2190
+ return lit.html`
2191
+ <div
2192
+ class="relative z-40 min-w-0 flex-1"
2193
+ data-context-dropdown-root="true"
2194
+ >
2195
+ <button
2196
+ type="button"
2197
+ class="relative z-40 flex w-full min-w-0 max-w-[240px] items-center gap-1.5 rounded-md border border-gray-200 px-2 py-1 text-xs font-medium text-gray-700 transition hover:border-gray-300 hover:bg-gray-50"
2198
+ @pointerdown=${this.handleContextDropdownToggle}
2199
+ >
2200
+ <span class="truncate flex-1 text-left">${selectedLabel}</span>
2201
+ <span class="shrink-0 text-gray-400"
2202
+ >${this.renderIcon("ChevronDown")}</span
2203
+ >
2204
+ </button>
2205
+ ${this.contextMenuOpen ? lit.html`
2206
+ <div
2207
+ class="absolute left-0 z-50 mt-1.5 w-40 rounded-md border border-gray-200 bg-white py-1 shadow-md ring-1 ring-black/5"
2208
+ data-context-dropdown-root="true"
2209
+ >
2210
+ ${filteredOptions.map((option) => lit.html`
2211
+ <button
2212
+ type="button"
2213
+ class="flex w-full items-center justify-between px-3 py-1.5 text-left text-xs transition hover:bg-gray-50 focus:bg-gray-50 focus:outline-none"
2214
+ data-context-dropdown-root="true"
2215
+ @click=${() => this.handleContextOptionSelect(option.key)}
2216
+ >
2217
+ <span
2218
+ class="truncate ${option.key === this.selectedContext ? "text-gray-900 font-medium" : "text-gray-600"}"
2219
+ >${option.label}</span
2220
+ >
2221
+ ${option.key === this.selectedContext ? lit.html`<span class="text-gray-500"
2222
+ >${this.renderIcon("Check")}</span
2223
+ >` : lit.nothing}
2224
+ </button>
2225
+ `)}
2226
+ </div>
2227
+ ` : lit.nothing}
2228
+ </div>
2229
+ `;
2230
+ }
2231
+ handleMenuSelect(key) {
2232
+ if (!this.menuItems.some((item) => item.key === key)) return;
2233
+ this.selectedMenu = key;
2234
+ if (key === "agents" && this.selectedContext === "all-agents") {
2235
+ const agentOptions = this.contextOptions.filter((opt) => opt.key !== "all-agents");
2236
+ if (agentOptions.length > 0) {
2237
+ const defaultAgent = agentOptions.find((opt) => opt.key === "default");
2238
+ this.selectedContext = defaultAgent ? defaultAgent.key : agentOptions[0].key;
2239
+ }
2240
+ }
2241
+ this.contextMenuOpen = false;
2242
+ this.persistState();
2243
+ this.requestUpdate();
2244
+ }
2245
+ handleContextDropdownToggle(event) {
2246
+ event.preventDefault();
2247
+ event.stopPropagation();
2248
+ this.contextMenuOpen = !this.contextMenuOpen;
2249
+ this.requestUpdate();
2250
+ }
2251
+ handleContextOptionSelect(key) {
2252
+ if (!this.contextOptions.some((option) => option.key === key)) return;
2253
+ if (this.selectedContext !== key) {
2254
+ this.selectedContext = key;
2255
+ this.expandedRows.clear();
2256
+ }
2257
+ this.contextMenuOpen = false;
2258
+ this.persistState();
2259
+ this.requestUpdate();
2260
+ }
2261
+ renderToolsView() {
2262
+ if (!this._core) return lit.html`
2263
+ <div
2264
+ class="flex h-full items-center justify-center px-4 py-8 text-xs text-gray-500"
2265
+ >
2266
+ No core instance available
2267
+ </div>
2268
+ `;
2269
+ this.refreshToolsSnapshot();
2270
+ const allTools = this.cachedTools;
2271
+ if (allTools.length === 0) return lit.html`
2272
+ <div
2273
+ class="flex h-full items-center justify-center px-4 py-8 text-center"
2274
+ >
2275
+ <div class="max-w-md">
2276
+ <div
2277
+ class="mb-3 flex justify-center text-gray-300 [&>svg]:!h-8 [&>svg]:!w-8"
2278
+ >
2279
+ ${this.renderIcon("Hammer")}
2280
+ </div>
2281
+ <p class="text-sm text-gray-600">No tools available</p>
2282
+ <p class="mt-2 text-xs text-gray-500">
2283
+ Tools will appear here once agents are configured with tool
2284
+ handlers or renderers.
2285
+ </p>
2286
+ </div>
2287
+ </div>
2288
+ `;
2289
+ return lit.html`
2290
+ <div class="flex h-full flex-col overflow-hidden">
2291
+ <div class="overflow-auto p-4">
2292
+ <div class="space-y-3">
2293
+ ${(this.selectedContext === "all-agents" ? allTools : allTools.filter((tool) => !tool.agentId || tool.agentId === this.selectedContext)).map((tool) => this.renderToolCard(tool))}
2294
+ </div>
2295
+ </div>
2296
+ </div>
2297
+ `;
2298
+ }
2299
+ extractToolsFromAgents() {
2300
+ if (!this._core) return [];
2301
+ const tools = [];
2302
+ for (const coreTool of this._core.tools ?? []) tools.push({
2303
+ agentId: coreTool.agentId ?? "",
2304
+ name: coreTool.name,
2305
+ description: coreTool.description,
2306
+ parameters: coreTool.parameters,
2307
+ type: "handler"
2308
+ });
2309
+ for (const [agentId, agent] of Object.entries(this._core.agents)) {
2310
+ if (!agent) continue;
2311
+ const handlers = agent.toolHandlers;
2312
+ if (handlers && typeof handlers === "object") {
2313
+ for (const [toolName, handler] of Object.entries(handlers)) if (handler && typeof handler === "object") {
2314
+ const handlerObj = handler;
2315
+ tools.push({
2316
+ agentId,
2317
+ name: toolName,
2318
+ description: typeof handlerObj.description === "string" && handlerObj.description || handlerObj.tool?.description,
2319
+ parameters: handlerObj.parameters ?? handlerObj.tool?.parameters,
2320
+ type: "handler"
2321
+ });
2322
+ }
2323
+ }
2324
+ const renderers = agent.toolRenderers;
2325
+ if (renderers && typeof renderers === "object") {
2326
+ for (const [toolName, renderer] of Object.entries(renderers)) if (!tools.some((t) => t.agentId === agentId && t.name === toolName)) {
2327
+ if (renderer && typeof renderer === "object") {
2328
+ const rendererObj = renderer;
2329
+ tools.push({
2330
+ agentId,
2331
+ name: toolName,
2332
+ description: typeof rendererObj.description === "string" && rendererObj.description || rendererObj.tool?.description,
2333
+ parameters: rendererObj.parameters ?? rendererObj.tool?.parameters,
2334
+ type: "renderer"
2335
+ });
2336
+ }
2337
+ }
2338
+ }
2339
+ }
2340
+ return tools.sort((a, b) => {
2341
+ const agentCompare = a.agentId.localeCompare(b.agentId);
2342
+ if (agentCompare !== 0) return agentCompare;
2343
+ return a.name.localeCompare(b.name);
2344
+ });
2345
+ }
2346
+ renderToolCard(tool) {
2347
+ const isExpanded = this.expandedTools.has(`${tool.agentId}:${tool.name}`);
2348
+ const schema = this.extractSchemaInfo(tool.parameters);
2349
+ return lit.html`
2350
+ <div class="rounded-lg border border-gray-200 bg-white overflow-hidden">
2351
+ <button
2352
+ type="button"
2353
+ class="w-full px-4 py-3 text-left transition hover:bg-gray-50"
2354
+ @click=${() => this.toggleToolExpansion(`${tool.agentId}:${tool.name}`)}
2355
+ >
2356
+ <div class="flex items-start justify-between gap-3">
2357
+ <div class="flex-1 min-w-0">
2358
+ <div class="flex items-center gap-2 mb-1">
2359
+ <span class="font-mono text-sm font-semibold text-gray-900"
2360
+ >${tool.name}</span
2361
+ >
2362
+ <span
2363
+ class="inline-flex items-center rounded-sm border px-1.5 py-0.5 text-[10px] font-medium ${{
2364
+ handler: "bg-blue-50 text-blue-700 border-blue-200",
2365
+ renderer: "bg-purple-50 text-purple-700 border-purple-200"
2366
+ }[tool.type]}"
2367
+ >
2368
+ ${tool.type}
2369
+ </span>
2370
+ </div>
2371
+ <div class="flex items-center gap-2 text-xs text-gray-500">
2372
+ <span class="flex items-center gap-1">
2373
+ ${this.renderIcon("Bot")}
2374
+ <span class="font-mono">${tool.agentId}</span>
2375
+ </span>
2376
+ ${schema.properties.length > 0 ? lit.html`
2377
+ <span class="text-gray-300">•</span>
2378
+ <span
2379
+ >${schema.properties.length}
2380
+ parameter${schema.properties.length !== 1 ? "s" : ""}</span
2381
+ >
2382
+ ` : lit.nothing}
2383
+ </div>
2384
+ ${tool.description ? lit.html`<p class="mt-2 text-xs text-gray-600">
2385
+ ${tool.description}
2386
+ </p>` : lit.nothing}
2387
+ </div>
2388
+ <span
2389
+ class="shrink-0 text-gray-400 transition ${isExpanded ? "rotate-180" : ""}"
2390
+ >
2391
+ ${this.renderIcon("ChevronDown")}
2392
+ </span>
2393
+ </div>
2394
+ </button>
2395
+
2396
+ ${isExpanded ? lit.html`
2397
+ <div class="border-t border-gray-200 bg-gray-50/50 px-4 py-3">
2398
+ ${schema.properties.length > 0 ? lit.html`
2399
+ <h5 class="mb-3 text-xs font-semibold text-gray-700">
2400
+ Parameters
2401
+ </h5>
2402
+ <div class="space-y-3">
2403
+ ${schema.properties.map((prop) => lit.html`
2404
+ <div
2405
+ class="rounded-md border border-gray-200 bg-white p-3"
2406
+ >
2407
+ <div
2408
+ class="flex items-start justify-between gap-2 mb-1"
2409
+ >
2410
+ <span
2411
+ class="font-mono text-xs font-medium text-gray-900"
2412
+ >${prop.name}</span
2413
+ >
2414
+ <div class="flex items-center gap-1.5 shrink-0">
2415
+ ${prop.required ? lit.html`
2416
+ <span
2417
+ class="text-[9px] rounded border border-rose-200 bg-rose-50 px-1 py-0.5 font-medium text-rose-700"
2418
+ >required</span
2419
+ >
2420
+ ` : lit.html`
2421
+ <span
2422
+ class="text-[9px] rounded border border-gray-200 bg-gray-50 px-1 py-0.5 font-medium text-gray-600"
2423
+ >optional</span
2424
+ >
2425
+ `}
2426
+ ${prop.type ? lit.html`<span
2427
+ class="text-[9px] rounded border border-gray-200 bg-gray-50 px-1 py-0.5 font-mono text-gray-600"
2428
+ >${prop.type}</span
2429
+ >` : lit.nothing}
2430
+ </div>
2431
+ </div>
2432
+ ${prop.description ? lit.html`<p class="mt-1 text-xs text-gray-600">
2433
+ ${prop.description}
2434
+ </p>` : lit.nothing}
2435
+ ${prop.defaultValue !== void 0 ? lit.html`
2436
+ <div
2437
+ class="mt-2 flex items-center gap-1.5 text-[10px] text-gray-500"
2438
+ >
2439
+ <span>Default:</span>
2440
+ <code
2441
+ class="rounded bg-gray-100 px-1 py-0.5 font-mono"
2442
+ >${JSON.stringify(prop.defaultValue)}</code
2443
+ >
2444
+ </div>
2445
+ ` : lit.nothing}
2446
+ ${prop.enum && prop.enum.length > 0 ? lit.html`
2447
+ <div class="mt-2">
2448
+ <span class="text-[10px] text-gray-500"
2449
+ >Allowed values:</span
2450
+ >
2451
+ <div class="mt-1 flex flex-wrap gap-1">
2452
+ ${prop.enum.map((val) => lit.html`
2453
+ <code
2454
+ class="rounded border border-gray-200 bg-gray-50 px-1.5 py-0.5 text-[10px] font-mono text-gray-700"
2455
+ >${JSON.stringify(val)}</code
2456
+ >
2457
+ `)}
2458
+ </div>
2459
+ </div>
2460
+ ` : lit.nothing}
2461
+ </div>
2462
+ `)}
2463
+ </div>
2464
+ ` : lit.html`
2465
+ <div class="flex items-center justify-center py-4 text-xs text-gray-500">
2466
+ <span>No parameters defined</span>
2467
+ </div>
2468
+ `}
2469
+ </div>
2470
+ ` : lit.nothing}
2471
+ </div>
2472
+ `;
2473
+ }
2474
+ extractSchemaInfo(parameters) {
2475
+ const result = { properties: [] };
2476
+ if (!parameters || typeof parameters !== "object") return result;
2477
+ const zodDef = parameters._def;
2478
+ if (zodDef && typeof zodDef === "object") {
2479
+ if (zodDef.typeName === "ZodObject") {
2480
+ const rawShape = zodDef.shape;
2481
+ const shape = typeof rawShape === "function" ? rawShape() : rawShape;
2482
+ if (!shape || typeof shape !== "object") return result;
2483
+ const requiredKeys = /* @__PURE__ */ new Set();
2484
+ if (zodDef.unknownKeys === "strict" || !zodDef.catchall) Object.keys(shape || {}).forEach((key) => {
2485
+ const candidate = shape[key];
2486
+ if (candidate?._def && !this.isZodOptional(candidate)) requiredKeys.add(key);
2487
+ });
2488
+ for (const [key, value] of Object.entries(shape || {})) {
2489
+ const fieldInfo = this.extractZodFieldInfo(value);
2490
+ result.properties.push({
2491
+ name: key,
2492
+ type: fieldInfo.type,
2493
+ description: fieldInfo.description,
2494
+ required: requiredKeys.has(key),
2495
+ defaultValue: fieldInfo.defaultValue,
2496
+ enum: fieldInfo.enum
2497
+ });
2498
+ }
2499
+ }
2500
+ } else if (parameters.type === "object" && parameters.properties) {
2501
+ const props = parameters.properties;
2502
+ const required = new Set(Array.isArray(parameters.required) ? parameters.required : []);
2503
+ for (const [key, value] of Object.entries(props ?? {})) {
2504
+ const prop = value;
2505
+ result.properties.push({
2506
+ name: key,
2507
+ type: prop.type,
2508
+ description: typeof prop.description === "string" ? prop.description : void 0,
2509
+ required: required.has(key),
2510
+ defaultValue: prop.default,
2511
+ enum: Array.isArray(prop.enum) ? prop.enum : void 0
2512
+ });
2513
+ }
2514
+ }
2515
+ return result;
2516
+ }
2517
+ isZodOptional(zodSchema) {
2518
+ const schema = zodSchema;
2519
+ if (!schema?._def) return false;
2520
+ const def = schema._def;
2521
+ if (def.typeName === "ZodOptional" || def.typeName === "ZodNullable") return true;
2522
+ if (def.defaultValue !== void 0) return true;
2523
+ return false;
2524
+ }
2525
+ extractZodFieldInfo(zodSchema) {
2526
+ const info = {};
2527
+ const schema = zodSchema;
2528
+ if (!schema?._def) return info;
2529
+ let currentSchema = schema;
2530
+ let def = currentSchema._def;
2531
+ while (def.typeName === "ZodOptional" || def.typeName === "ZodNullable" || def.typeName === "ZodDefault") {
2532
+ if (def.typeName === "ZodDefault" && def.defaultValue !== void 0) info.defaultValue = typeof def.defaultValue === "function" ? def.defaultValue() : def.defaultValue;
2533
+ currentSchema = def.innerType ?? currentSchema;
2534
+ if (!currentSchema?._def) break;
2535
+ def = currentSchema._def;
2536
+ }
2537
+ info.description = typeof def.description === "string" ? def.description : void 0;
2538
+ const typeName = typeof def.typeName === "string" ? def.typeName : void 0;
2539
+ info.type = typeName ? {
2540
+ ZodString: "string",
2541
+ ZodNumber: "number",
2542
+ ZodBoolean: "boolean",
2543
+ ZodArray: "array",
2544
+ ZodObject: "object",
2545
+ ZodEnum: "enum",
2546
+ ZodLiteral: "literal",
2547
+ ZodUnion: "union",
2548
+ ZodAny: "any",
2549
+ ZodUnknown: "unknown"
2550
+ }[typeName] || typeName.replace("Zod", "").toLowerCase() : void 0;
2551
+ if (typeName === "ZodEnum" && Array.isArray(def.values)) info.enum = def.values;
2552
+ else if (typeName === "ZodLiteral" && def.value !== void 0) info.enum = [def.value];
2553
+ return info;
2554
+ }
2555
+ toggleToolExpansion(toolId) {
2556
+ if (this.expandedTools.has(toolId)) this.expandedTools.delete(toolId);
2557
+ else this.expandedTools.add(toolId);
2558
+ this.requestUpdate();
2559
+ }
2560
+ renderContextView() {
2561
+ const contextEntries = Object.entries(this.contextStore);
2562
+ if (contextEntries.length === 0) return lit.html`
2563
+ <div
2564
+ class="flex h-full items-center justify-center px-4 py-8 text-center"
2565
+ >
2566
+ <div class="max-w-md">
2567
+ <div
2568
+ class="mb-3 flex justify-center text-gray-300 [&>svg]:!h-8 [&>svg]:!w-8"
2569
+ >
2570
+ ${this.renderIcon("FileText")}
2571
+ </div>
2572
+ <p class="text-sm text-gray-600">No context available</p>
2573
+ <p class="mt-2 text-xs text-gray-500">
2574
+ Context will appear here once added to CopilotKit.
2575
+ </p>
2576
+ </div>
2577
+ </div>
2578
+ `;
2579
+ return lit.html`
2580
+ <div class="flex h-full flex-col overflow-hidden">
2581
+ <div class="overflow-auto p-4">
2582
+ <div class="space-y-3">
2583
+ ${contextEntries.map(([id, context]) => this.renderContextCard(id, context))}
2584
+ </div>
2585
+ </div>
2586
+ </div>
2587
+ `;
2588
+ }
2589
+ renderContextCard(id, context) {
2590
+ const isExpanded = this.expandedContextItems.has(id);
2591
+ const valuePreview = this.getContextValuePreview(context.value);
2592
+ const hasValue = context.value !== void 0 && context.value !== null;
2593
+ return lit.html`
2594
+ <div class="rounded-lg border border-gray-200 bg-white overflow-hidden">
2595
+ <button
2596
+ type="button"
2597
+ class="w-full px-4 py-3 text-left transition hover:bg-gray-50"
2598
+ @click=${() => this.toggleContextExpansion(id)}
2599
+ >
2600
+ <div class="flex items-start justify-between gap-3">
2601
+ <div class="flex-1 min-w-0">
2602
+ <p class="text-sm font-medium text-gray-900 mb-1">${context.description?.trim() || id}</p>
2603
+ <div class="flex items-center gap-2 text-xs text-gray-500">
2604
+ <span
2605
+ class="font-mono truncate inline-block align-middle"
2606
+ style="max-width: 180px;"
2607
+ >${id}</span
2608
+ >
2609
+ ${hasValue ? lit.html`
2610
+ <span class="text-gray-300">•</span>
2611
+ <span class="truncate">${valuePreview}</span>
2612
+ ` : lit.nothing}
2613
+ </div>
2614
+ </div>
2615
+ <span
2616
+ class="shrink-0 text-gray-400 transition ${isExpanded ? "rotate-180" : ""}"
2617
+ >
2618
+ ${this.renderIcon("ChevronDown")}
2619
+ </span>
2620
+ </div>
2621
+ </button>
2622
+
2623
+ ${isExpanded ? lit.html`
2624
+ <div class="border-t border-gray-200 bg-gray-50/50 px-4 py-3">
2625
+ <div class="mb-3">
2626
+ <h5 class="mb-1 text-xs font-semibold text-gray-700">ID</h5>
2627
+ <code
2628
+ class="block rounded bg-white border border-gray-200 px-2 py-1 text-[10px] font-mono text-gray-600"
2629
+ >${id}</code
2630
+ >
2631
+ </div>
2632
+ ${hasValue ? lit.html`
2633
+ <div class="mb-2 flex items-center justify-between gap-2">
2634
+ <h5 class="text-xs font-semibold text-gray-700">
2635
+ Value
2636
+ </h5>
2637
+ <button
2638
+ class="flex items-center gap-1 rounded-md border border-gray-200 bg-white px-2 py-1 text-[10px] font-medium text-gray-700 transition hover:bg-gray-50"
2639
+ type="button"
2640
+ @click=${(e) => {
2641
+ e.stopPropagation();
2642
+ this.copyContextValue(context.value, id);
2643
+ }}
2644
+ >
2645
+ ${this.copiedContextItems.has(id) ? "Copied" : "Copy JSON"}
2646
+ </button>
2647
+ </div>
2648
+ <div
2649
+ class="rounded-md border border-gray-200 bg-white p-3"
2650
+ >
2651
+ <pre
2652
+ class="overflow-auto text-xs text-gray-800 max-h-96"
2653
+ ><code>${this.formatContextValue(context.value)}</code></pre>
2654
+ </div>
2655
+ ` : lit.html`
2656
+ <div class="flex items-center justify-center py-4 text-xs text-gray-500">
2657
+ <span>No value available</span>
2658
+ </div>
2659
+ `}
2660
+ </div>
2661
+ ` : lit.nothing}
2662
+ </div>
2663
+ `;
2664
+ }
2665
+ getContextValuePreview(value) {
2666
+ if (value === void 0 || value === null) return "—";
2667
+ if (typeof value === "string") return value.length > 50 ? `${value.substring(0, 50)}...` : value;
2668
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
2669
+ if (Array.isArray(value)) return `Array(${value.length})`;
2670
+ if (typeof value === "object") {
2671
+ const keys = Object.keys(value);
2672
+ return `Object with ${keys.length} key${keys.length !== 1 ? "s" : ""}`;
2673
+ }
2674
+ if (typeof value === "function") return "Function";
2675
+ return String(value);
2676
+ }
2677
+ formatContextValue(value) {
2678
+ if (value === void 0) return "undefined";
2679
+ if (value === null) return "null";
2680
+ if (typeof value === "function") return value.toString();
2681
+ try {
2682
+ return JSON.stringify(value, null, 2);
2683
+ } catch {
2684
+ return String(value);
2685
+ }
2686
+ }
2687
+ async copyContextValue(value, contextId) {
2688
+ if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) {
2689
+ console.warn("Clipboard API is not available in this environment.");
2690
+ return;
2691
+ }
2692
+ const serialized = this.formatContextValue(value);
2693
+ try {
2694
+ await navigator.clipboard.writeText(serialized);
2695
+ this.copiedContextItems.add(contextId);
2696
+ this.requestUpdate();
2697
+ setTimeout(() => {
2698
+ this.copiedContextItems.delete(contextId);
2699
+ this.requestUpdate();
2700
+ }, 1500);
2701
+ } catch (error) {
2702
+ console.error("Failed to copy context value:", error);
2703
+ }
2704
+ }
2705
+ toggleContextExpansion(contextId) {
2706
+ if (this.expandedContextItems.has(contextId)) this.expandedContextItems.delete(contextId);
2707
+ else this.expandedContextItems.add(contextId);
2708
+ this.requestUpdate();
2709
+ }
2710
+ toggleRowExpansion(eventId) {
2711
+ const selection = window.getSelection();
2712
+ if (selection && selection.toString().length > 0) return;
2713
+ if (this.expandedRows.has(eventId)) this.expandedRows.delete(eventId);
2714
+ else this.expandedRows.add(eventId);
2715
+ this.requestUpdate();
2716
+ }
2717
+ renderAnnouncementPanel() {
2718
+ if (!this.isOpen) return lit.nothing;
2719
+ this.ensureAnnouncementLoading();
2720
+ if (!this.hasUnseenAnnouncement) return lit.nothing;
2721
+ if (!this.announcementLoaded && !this.announcementMarkdown) return lit.html`<div
2722
+ class="mx-4 my-3 rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-800 shadow-[0_12px_30px_rgba(15,23,42,0.12)]"
2723
+ >
2724
+ <div class="flex items-center gap-2 font-semibold">
2725
+ <span
2726
+ class="inline-flex h-6 w-6 items-center justify-center rounded-md bg-slate-900 text-white shadow-sm"
2727
+ >
2728
+ ${this.renderIcon("Megaphone")}
2729
+ </span>
2730
+ <span>Loading latest announcement…</span>
2731
+ </div>
2732
+ </div>`;
2733
+ if (this.announcementLoadError) return lit.html`<div
2734
+ class="mx-4 my-3 rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-900 shadow-[0_12px_30px_rgba(15,23,42,0.12)]"
2735
+ >
2736
+ <div class="flex items-center gap-2 font-semibold">
2737
+ <span
2738
+ class="inline-flex h-6 w-6 items-center justify-center rounded-md bg-rose-600 text-white shadow-sm"
2739
+ >
2740
+ ${this.renderIcon("Megaphone")}
2741
+ </span>
2742
+ <span>Announcement unavailable</span>
2743
+ </div>
2744
+ <p class="mt-2 text-xs text-rose-800">
2745
+ We couldn’t load the latest notice. Please try opening the inspector
2746
+ again.
2747
+ </p>
2748
+ </div>`;
2749
+ if (!this.announcementMarkdown) return lit.nothing;
2750
+ const content = this.announcementHtml ? (0, lit_directives_unsafe_html_js.unsafeHTML)(this.announcementHtml) : lit.html`<pre class="whitespace-pre-wrap text-sm text-gray-900">
2751
+ ${this.announcementMarkdown}</pre
2752
+ >`;
2753
+ return lit.html`<div
2754
+ class="mx-4 my-3 rounded-xl border border-slate-200 bg-white px-4 py-4 shadow-[0_12px_30px_rgba(15,23,42,0.12)]"
2755
+ >
2756
+ <div
2757
+ class="mb-3 flex items-center gap-2 text-sm font-semibold text-slate-900"
2758
+ >
2759
+ <span
2760
+ class="inline-flex h-7 w-7 items-center justify-center rounded-md bg-slate-900 text-white shadow-sm"
2761
+ >
2762
+ ${this.renderIcon("Megaphone")}
2763
+ </span>
2764
+ <span>Announcement</span>
2765
+ <button
2766
+ class="announcement-dismiss ml-auto"
2767
+ type="button"
2768
+ @click=${this.handleDismissAnnouncement}
2769
+ aria-label="Dismiss announcement"
2770
+ >
2771
+ Dismiss
2772
+ </button>
2773
+ </div>
2774
+ <div class="announcement-content text-sm leading-relaxed text-gray-900">
2775
+ ${content}
2776
+ </div>
2777
+ </div>`;
2778
+ }
2779
+ ensureAnnouncementLoading() {
2780
+ if (this.announcementPromise || typeof window === "undefined" || typeof fetch === "undefined") return;
2781
+ this.announcementPromise = this.fetchAnnouncement();
2782
+ }
2783
+ renderAnnouncementPreview() {
2784
+ if (!this.hasUnseenAnnouncement || !this.showAnnouncementPreview || !this.announcementPreviewText) return lit.nothing;
2785
+ return lit.html`<div
2786
+ class="announcement-preview"
2787
+ data-side=${this.contextState.button.anchor.horizontal === "left" ? "right" : "left"}
2788
+ role="note"
2789
+ @click=${() => this.handleAnnouncementPreviewClick()}
2790
+ >
2791
+ <span>${this.announcementPreviewText}</span>
2792
+ <span class="announcement-preview__arrow"></span>
2793
+ </div>`;
2794
+ }
2795
+ handleAnnouncementPreviewClick() {
2796
+ this.showAnnouncementPreview = false;
2797
+ this.openInspector();
2798
+ }
2799
+ async fetchAnnouncement() {
2800
+ try {
2801
+ const response = await fetch(ANNOUNCEMENT_URL, { cache: "no-cache" });
2802
+ if (!response.ok) throw new Error(`Failed to load announcement (${response.status})`);
2803
+ const data = await response.json();
2804
+ const timestamp = typeof data?.timestamp === "string" ? data.timestamp : null;
2805
+ const previewText = typeof data?.previewText === "string" ? data.previewText : null;
2806
+ const markdown = typeof data?.announcement === "string" ? data.announcement : null;
2807
+ if (!timestamp || !markdown) throw new Error("Malformed announcement payload");
2808
+ const storedTimestamp = this.loadStoredAnnouncementTimestamp();
2809
+ this.announcementTimestamp = timestamp;
2810
+ this.announcementPreviewText = previewText ?? "";
2811
+ this.announcementMarkdown = markdown;
2812
+ this.hasUnseenAnnouncement = (!storedTimestamp || storedTimestamp !== timestamp) && !!this.announcementPreviewText;
2813
+ this.showAnnouncementPreview = this.hasUnseenAnnouncement;
2814
+ this.announcementHtml = await this.convertMarkdownToHtml(markdown);
2815
+ this.announcementLoaded = true;
2816
+ this.requestUpdate();
2817
+ } catch (error) {
2818
+ this.announcementLoadError = error;
2819
+ this.announcementLoaded = true;
2820
+ this.requestUpdate();
2821
+ }
2822
+ }
2823
+ async convertMarkdownToHtml(markdown) {
2824
+ const renderer = new marked.marked.Renderer();
2825
+ renderer.link = (href, title, text) => {
2826
+ return `<a href="${this.escapeHtmlAttr(this.appendRefParam(href ?? ""))}" target="_blank" rel="noopener"${title ? ` title="${this.escapeHtmlAttr(title)}"` : ""}>${text}</a>`;
2827
+ };
2828
+ return marked.marked.parse(markdown, { renderer });
2829
+ }
2830
+ appendRefParam(href) {
2831
+ try {
2832
+ const url = new URL(href, typeof window !== "undefined" ? window.location.href : "https://copilotkit.ai");
2833
+ if (!url.searchParams.has("ref")) url.searchParams.append("ref", "cpk-inspector");
2834
+ return url.toString();
2835
+ } catch {
2836
+ return href;
2837
+ }
2838
+ }
2839
+ escapeHtmlAttr(value) {
2840
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\"/g, "&quot;").replace(/'/g, "&#39;");
2841
+ }
2842
+ loadStoredAnnouncementTimestamp() {
2843
+ if (typeof window === "undefined" || !window.localStorage) return null;
2844
+ try {
2845
+ const raw = window.localStorage.getItem(ANNOUNCEMENT_STORAGE_KEY);
2846
+ if (!raw) return null;
2847
+ const parsed = JSON.parse(raw);
2848
+ if (parsed && typeof parsed.timestamp === "string") return parsed.timestamp;
2849
+ return null;
2850
+ } catch {}
2851
+ return null;
2852
+ }
2853
+ persistAnnouncementTimestamp(timestamp) {
2854
+ if (typeof window === "undefined" || !window.localStorage) return;
2855
+ try {
2856
+ const payload = JSON.stringify({ timestamp });
2857
+ window.localStorage.setItem(ANNOUNCEMENT_STORAGE_KEY, payload);
2858
+ } catch {}
2859
+ }
2860
+ markAnnouncementSeen() {
2861
+ this.hasUnseenAnnouncement = false;
2862
+ this.showAnnouncementPreview = false;
2863
+ if (!this.announcementTimestamp) {
2864
+ if (this.announcementPromise && !this.announcementLoaded) this.announcementPromise.then(() => this.markAnnouncementSeen()).catch(() => void 0);
2865
+ this.requestUpdate();
2866
+ return;
2867
+ }
2868
+ this.persistAnnouncementTimestamp(this.announcementTimestamp);
2869
+ this.requestUpdate();
2870
+ }
2871
+ };
2872
+ function defineWebInspector() {
2873
+ if (!customElements.get(WEB_INSPECTOR_TAG)) customElements.define(WEB_INSPECTOR_TAG, WebInspectorElement);
2874
+ }
2875
+ defineWebInspector();
2876
+
2877
+ //#endregion
2878
+ exports.WEB_INSPECTOR_TAG = WEB_INSPECTOR_TAG;
2879
+ exports.WebInspectorElement = WebInspectorElement;
2880
+ exports.defineWebInspector = defineWebInspector;
2881
+ //# sourceMappingURL=index.cjs.map