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