@copilotkit/web-inspector 1.55.0-next.7

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