@copilotkitnext/web-inspector 0.0.0-max-changeset-20260109174803

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.
package/src/index.ts ADDED
@@ -0,0 +1,3659 @@
1
+ import { LitElement, css, html, nothing, unsafeCSS } from "lit";
2
+ import { styleMap } from "lit/directives/style-map.js";
3
+ import tailwindStyles from "./styles/generated.css";
4
+ import inspectorLogoUrl from "./assets/inspector-logo.svg";
5
+ import inspectorLogoIconUrl from "./assets/inspector-logo-icon.svg";
6
+ import { unsafeHTML } from "lit/directives/unsafe-html.js";
7
+ import { marked } from "marked";
8
+ import { icons } from "lucide";
9
+ import {
10
+ CopilotKitCore,
11
+ CopilotKitCoreRuntimeConnectionStatus,
12
+ type CopilotKitCoreSubscriber,
13
+ type CopilotKitCoreErrorCode,
14
+ } from "@copilotkitnext/core";
15
+ import type { AbstractAgent, AgentSubscriber } from "@ag-ui/client";
16
+ import type { Anchor, ContextKey, ContextState, DockMode, Position, Size } from "./lib/types";
17
+ import {
18
+ applyAnchorPosition as applyAnchorPositionHelper,
19
+ centerContext as centerContextHelper,
20
+ constrainToViewport,
21
+ keepPositionWithinViewport,
22
+ updateAnchorFromPosition as updateAnchorFromPositionHelper,
23
+ updateSizeFromElement,
24
+ clampSize as clampSizeToViewport,
25
+ } from "./lib/context-helpers";
26
+ import {
27
+ loadInspectorState,
28
+ saveInspectorState,
29
+ type PersistedState,
30
+ isValidAnchor,
31
+ isValidPosition,
32
+ isValidSize,
33
+ isValidDockMode,
34
+ } from "./lib/persistence";
35
+
36
+ export const WEB_INSPECTOR_TAG = "cpk-web-inspector" as const;
37
+
38
+ type LucideIconName = keyof typeof icons;
39
+
40
+ type MenuKey = "ag-ui-events" | "agents" | "frontend-tools" | "agent-context";
41
+
42
+ type MenuItem = {
43
+ key: MenuKey;
44
+ label: string;
45
+ icon: LucideIconName;
46
+ };
47
+
48
+ const EDGE_MARGIN = 16;
49
+ const DRAG_THRESHOLD = 6;
50
+ const MIN_WINDOW_WIDTH = 600;
51
+ const MIN_WINDOW_WIDTH_DOCKED_LEFT = 420;
52
+ const MIN_WINDOW_HEIGHT = 200;
53
+ const INSPECTOR_STORAGE_KEY = "cpk:inspector:state";
54
+ const ANNOUNCEMENT_STORAGE_KEY = "cpk:inspector:announcements";
55
+ const ANNOUNCEMENT_URL = "https://cdn.copilotkit.ai/announcements.json";
56
+ const DEFAULT_BUTTON_SIZE: Size = { width: 48, height: 48 };
57
+ const DEFAULT_WINDOW_SIZE: Size = { width: 840, height: 560 };
58
+ const DOCKED_LEFT_WIDTH = 500; // Sensible width for left dock with collapsed sidebar
59
+ const MAX_AGENT_EVENTS = 200;
60
+ const MAX_TOTAL_EVENTS = 500;
61
+
62
+ type InspectorAgentEventType =
63
+ | "RUN_STARTED"
64
+ | "RUN_FINISHED"
65
+ | "RUN_ERROR"
66
+ | "TEXT_MESSAGE_START"
67
+ | "TEXT_MESSAGE_CONTENT"
68
+ | "TEXT_MESSAGE_END"
69
+ | "TOOL_CALL_START"
70
+ | "TOOL_CALL_ARGS"
71
+ | "TOOL_CALL_END"
72
+ | "TOOL_CALL_RESULT"
73
+ | "STATE_SNAPSHOT"
74
+ | "STATE_DELTA"
75
+ | "MESSAGES_SNAPSHOT"
76
+ | "RAW_EVENT"
77
+ | "CUSTOM_EVENT";
78
+
79
+ const AGENT_EVENT_TYPES: readonly InspectorAgentEventType[] = [
80
+ "RUN_STARTED",
81
+ "RUN_FINISHED",
82
+ "RUN_ERROR",
83
+ "TEXT_MESSAGE_START",
84
+ "TEXT_MESSAGE_CONTENT",
85
+ "TEXT_MESSAGE_END",
86
+ "TOOL_CALL_START",
87
+ "TOOL_CALL_ARGS",
88
+ "TOOL_CALL_END",
89
+ "TOOL_CALL_RESULT",
90
+ "STATE_SNAPSHOT",
91
+ "STATE_DELTA",
92
+ "MESSAGES_SNAPSHOT",
93
+ "RAW_EVENT",
94
+ "CUSTOM_EVENT",
95
+ ] as const;
96
+
97
+ type SanitizedValue =
98
+ | string
99
+ | number
100
+ | boolean
101
+ | null
102
+ | SanitizedValue[]
103
+ | { [key: string]: SanitizedValue };
104
+
105
+ type InspectorToolCall = {
106
+ id?: string;
107
+ function?: {
108
+ name?: string;
109
+ arguments?: SanitizedValue | string;
110
+ };
111
+ toolName?: string;
112
+ status?: string;
113
+ };
114
+
115
+ type InspectorMessage = {
116
+ id?: string;
117
+ role: string;
118
+ contentText: string;
119
+ contentRaw?: SanitizedValue;
120
+ toolCalls: InspectorToolCall[];
121
+ };
122
+
123
+ type InspectorToolDefinition = {
124
+ agentId: string;
125
+ name: string;
126
+ description?: string;
127
+ parameters?: unknown;
128
+ type: "handler" | "renderer";
129
+ };
130
+
131
+ type InspectorEvent = {
132
+ id: string;
133
+ agentId: string;
134
+ type: InspectorAgentEventType;
135
+ timestamp: number;
136
+ payload: SanitizedValue;
137
+ };
138
+
139
+ export class WebInspectorElement extends LitElement {
140
+ static properties = {
141
+ core: { attribute: false },
142
+ autoAttachCore: { type: Boolean, attribute: "auto-attach-core" },
143
+ } as const;
144
+
145
+ private _core: CopilotKitCore | null = null;
146
+ private coreSubscriber: CopilotKitCoreSubscriber | null = null;
147
+ private coreUnsubscribe: (() => void) | null = null;
148
+ private runtimeStatus: CopilotKitCoreRuntimeConnectionStatus | null = null;
149
+ private coreProperties: Readonly<Record<string, unknown>> = {};
150
+ private lastCoreError: { code: CopilotKitCoreErrorCode; message: string } | null = null;
151
+ private agentSubscriptions: Map<string, () => void> = new Map();
152
+ private agentEvents: Map<string, InspectorEvent[]> = new Map();
153
+ private agentMessages: Map<string, InspectorMessage[]> = new Map();
154
+ private agentStates: Map<string, SanitizedValue> = new Map();
155
+ private flattenedEvents: InspectorEvent[] = [];
156
+ private eventCounter = 0;
157
+ private contextStore: Record<string, { description?: string; value: unknown }> = {};
158
+
159
+ private pointerId: number | null = null;
160
+ private dragStart: Position | null = null;
161
+ private dragOffset: Position = { x: 0, y: 0 };
162
+ private isDragging = false;
163
+ private pointerContext: ContextKey | null = null;
164
+ private isOpen = false;
165
+ private draggedDuringInteraction = false;
166
+ private ignoreNextButtonClick = false;
167
+ private selectedMenu: MenuKey = "ag-ui-events";
168
+ private contextMenuOpen = false;
169
+ private dockMode: DockMode = "floating";
170
+ private previousBodyMargins: { left: string; bottom: string } | null = null;
171
+ private transitionTimeoutId: ReturnType<typeof setTimeout> | null = null;
172
+ private pendingSelectedContext: string | null = null;
173
+ private autoAttachCore = true;
174
+ private attemptedAutoAttach = false;
175
+ private cachedTools: InspectorToolDefinition[] = [];
176
+ private toolSignature = "";
177
+ private eventFilterText = "";
178
+ private eventTypeFilter: InspectorAgentEventType | "all" = "all";
179
+
180
+ private announcementMarkdown: string | null = null;
181
+ private announcementHtml: string | null = null;
182
+ private announcementTimestamp: string | null = null;
183
+ private announcementPreviewText: string | null = null;
184
+ private hasUnseenAnnouncement = false;
185
+ private announcementLoaded = false;
186
+ private announcementLoadError: unknown = null;
187
+ private announcementPromise: Promise<void> | null = null;
188
+ private showAnnouncementPreview = true;
189
+
190
+ get core(): CopilotKitCore | null {
191
+ return this._core;
192
+ }
193
+
194
+ set core(value: CopilotKitCore | null) {
195
+ const oldValue = this._core;
196
+ if (oldValue === value) {
197
+ return;
198
+ }
199
+
200
+ this.detachFromCore();
201
+
202
+ this._core = value ?? null;
203
+ this.requestUpdate("core", oldValue);
204
+
205
+ if (this._core) {
206
+ this.attachToCore(this._core);
207
+ }
208
+ }
209
+
210
+ private readonly contextState: Record<ContextKey, ContextState> = {
211
+ button: {
212
+ position: { x: EDGE_MARGIN, y: EDGE_MARGIN },
213
+ size: { ...DEFAULT_BUTTON_SIZE },
214
+ anchor: { horizontal: "right", vertical: "top" },
215
+ anchorOffset: { x: EDGE_MARGIN, y: EDGE_MARGIN },
216
+ },
217
+ window: {
218
+ position: { x: EDGE_MARGIN, y: EDGE_MARGIN },
219
+ size: { ...DEFAULT_WINDOW_SIZE },
220
+ anchor: { horizontal: "right", vertical: "top" },
221
+ anchorOffset: { x: EDGE_MARGIN, y: EDGE_MARGIN },
222
+ },
223
+ };
224
+
225
+ private hasCustomPosition: Record<ContextKey, boolean> = {
226
+ button: false,
227
+ window: false,
228
+ };
229
+
230
+ private resizePointerId: number | null = null;
231
+ private resizeStart: Position | null = null;
232
+ private resizeInitialSize: { width: number; height: number } | null = null;
233
+ private isResizing = false;
234
+
235
+ private readonly menuItems: MenuItem[] = [
236
+ { key: "ag-ui-events", label: "AG-UI Events", icon: "Zap" },
237
+ { key: "agents", label: "Agent", icon: "Bot" },
238
+ { key: "frontend-tools", label: "Frontend Tools", icon: "Hammer" },
239
+ { key: "agent-context", label: "Context", icon: "FileText" },
240
+ ];
241
+
242
+ private attachToCore(core: CopilotKitCore): void {
243
+ this.runtimeStatus = core.runtimeConnectionStatus;
244
+ this.coreProperties = core.properties;
245
+ this.lastCoreError = null;
246
+
247
+ this.coreSubscriber = {
248
+ onRuntimeConnectionStatusChanged: ({ status }) => {
249
+ this.runtimeStatus = status;
250
+ this.requestUpdate();
251
+ },
252
+ onPropertiesChanged: ({ properties }) => {
253
+ this.coreProperties = properties;
254
+ this.requestUpdate();
255
+ },
256
+ onError: ({ code, error }) => {
257
+ this.lastCoreError = { code, message: error.message };
258
+ this.requestUpdate();
259
+ },
260
+ onAgentsChanged: ({ agents }) => {
261
+ this.processAgentsChanged(agents);
262
+ },
263
+ onContextChanged: ({ context }) => {
264
+ this.contextStore = this.normalizeContextStore(context);
265
+ this.requestUpdate();
266
+ },
267
+ } satisfies CopilotKitCoreSubscriber;
268
+
269
+ this.coreUnsubscribe = core.subscribe(this.coreSubscriber).unsubscribe;
270
+ this.processAgentsChanged(core.agents);
271
+
272
+ // Initialize context from core
273
+ if (core.context) {
274
+ this.contextStore = this.normalizeContextStore(core.context);
275
+ }
276
+ }
277
+
278
+ private detachFromCore(): void {
279
+ if (this.coreUnsubscribe) {
280
+ this.coreUnsubscribe();
281
+ this.coreUnsubscribe = null;
282
+ }
283
+ this.coreSubscriber = null;
284
+ this.runtimeStatus = null;
285
+ this.lastCoreError = null;
286
+ this.coreProperties = {};
287
+ this.cachedTools = [];
288
+ this.toolSignature = "";
289
+ this.teardownAgentSubscriptions();
290
+ }
291
+
292
+ private teardownAgentSubscriptions(): void {
293
+ for (const unsubscribe of this.agentSubscriptions.values()) {
294
+ unsubscribe();
295
+ }
296
+ this.agentSubscriptions.clear();
297
+ this.agentEvents.clear();
298
+ this.agentMessages.clear();
299
+ this.agentStates.clear();
300
+ this.flattenedEvents = [];
301
+ this.eventCounter = 0;
302
+ }
303
+
304
+ private processAgentsChanged(agents: Readonly<Record<string, AbstractAgent>>): void {
305
+ const seenAgentIds = new Set<string>();
306
+
307
+ for (const agent of Object.values(agents)) {
308
+ if (!agent?.agentId) {
309
+ continue;
310
+ }
311
+ seenAgentIds.add(agent.agentId);
312
+ this.subscribeToAgent(agent);
313
+ }
314
+
315
+ for (const agentId of Array.from(this.agentSubscriptions.keys())) {
316
+ if (!seenAgentIds.has(agentId)) {
317
+ this.unsubscribeFromAgent(agentId);
318
+ this.agentEvents.delete(agentId);
319
+ this.agentMessages.delete(agentId);
320
+ this.agentStates.delete(agentId);
321
+ }
322
+ }
323
+
324
+ this.updateContextOptions(seenAgentIds);
325
+ this.refreshToolsSnapshot();
326
+ this.requestUpdate();
327
+ }
328
+
329
+ private refreshToolsSnapshot(): void {
330
+ if (!this._core) {
331
+ if (this.cachedTools.length > 0) {
332
+ this.cachedTools = [];
333
+ this.toolSignature = "";
334
+ this.requestUpdate();
335
+ }
336
+ return;
337
+ }
338
+
339
+ const tools = this.extractToolsFromAgents();
340
+ const signature = JSON.stringify(
341
+ tools.map((tool) => ({
342
+ agentId: tool.agentId,
343
+ name: tool.name,
344
+ type: tool.type,
345
+ hasDescription: Boolean(tool.description),
346
+ hasParameters: Boolean(tool.parameters),
347
+ })),
348
+ );
349
+
350
+ if (signature !== this.toolSignature) {
351
+ this.toolSignature = signature;
352
+ this.cachedTools = tools;
353
+ this.requestUpdate();
354
+ }
355
+ }
356
+
357
+ private tryAutoAttachCore(): void {
358
+ if (this.attemptedAutoAttach || this._core || !this.autoAttachCore || typeof window === "undefined") {
359
+ return;
360
+ }
361
+
362
+ this.attemptedAutoAttach = true;
363
+
364
+ const globalWindow = window as unknown as Record<string, unknown>;
365
+ const globalCandidates: Array<unknown> = [
366
+ // Common app-level globals used during development
367
+ globalWindow.__COPILOTKIT_CORE__,
368
+ (globalWindow.copilotkit as { core?: unknown } | undefined)?.core,
369
+ globalWindow.copilotkitCore,
370
+ ];
371
+
372
+ const foundCore = globalCandidates.find(
373
+ (candidate): candidate is CopilotKitCore => !!candidate && typeof candidate === "object",
374
+ );
375
+
376
+ if (foundCore) {
377
+ this.core = foundCore;
378
+ }
379
+ }
380
+
381
+ private subscribeToAgent(agent: AbstractAgent): void {
382
+ if (!agent.agentId) {
383
+ return;
384
+ }
385
+
386
+ const agentId = agent.agentId;
387
+
388
+ this.unsubscribeFromAgent(agentId);
389
+
390
+ const subscriber: AgentSubscriber = {
391
+ onRunStartedEvent: ({ event }) => {
392
+ this.recordAgentEvent(agentId, "RUN_STARTED", event);
393
+ },
394
+ onRunFinishedEvent: ({ event, result }) => {
395
+ this.recordAgentEvent(agentId, "RUN_FINISHED", { event, result });
396
+ },
397
+ onRunErrorEvent: ({ event }) => {
398
+ this.recordAgentEvent(agentId, "RUN_ERROR", event);
399
+ },
400
+ onTextMessageStartEvent: ({ event }) => {
401
+ this.recordAgentEvent(agentId, "TEXT_MESSAGE_START", event);
402
+ },
403
+ onTextMessageContentEvent: ({ event, textMessageBuffer }) => {
404
+ this.recordAgentEvent(agentId, "TEXT_MESSAGE_CONTENT", { event, textMessageBuffer });
405
+ },
406
+ onTextMessageEndEvent: ({ event, textMessageBuffer }) => {
407
+ this.recordAgentEvent(agentId, "TEXT_MESSAGE_END", { event, textMessageBuffer });
408
+ },
409
+ onToolCallStartEvent: ({ event }) => {
410
+ this.recordAgentEvent(agentId, "TOOL_CALL_START", event);
411
+ },
412
+ onToolCallArgsEvent: ({ event, toolCallBuffer, toolCallName, partialToolCallArgs }) => {
413
+ this.recordAgentEvent(agentId, "TOOL_CALL_ARGS", { event, toolCallBuffer, toolCallName, partialToolCallArgs });
414
+ },
415
+ onToolCallEndEvent: ({ event, toolCallArgs, toolCallName }) => {
416
+ this.recordAgentEvent(agentId, "TOOL_CALL_END", { event, toolCallArgs, toolCallName });
417
+ },
418
+ onToolCallResultEvent: ({ event }) => {
419
+ this.recordAgentEvent(agentId, "TOOL_CALL_RESULT", event);
420
+ },
421
+ onStateSnapshotEvent: ({ event }) => {
422
+ this.recordAgentEvent(agentId, "STATE_SNAPSHOT", event);
423
+ this.syncAgentState(agent);
424
+ },
425
+ onStateDeltaEvent: ({ event }) => {
426
+ this.recordAgentEvent(agentId, "STATE_DELTA", event);
427
+ this.syncAgentState(agent);
428
+ },
429
+ onMessagesSnapshotEvent: ({ event }) => {
430
+ this.recordAgentEvent(agentId, "MESSAGES_SNAPSHOT", event);
431
+ this.syncAgentMessages(agent);
432
+ },
433
+ onMessagesChanged: () => {
434
+ this.syncAgentMessages(agent);
435
+ },
436
+ onRawEvent: ({ event }) => {
437
+ this.recordAgentEvent(agentId, "RAW_EVENT", event);
438
+ },
439
+ onCustomEvent: ({ event }) => {
440
+ this.recordAgentEvent(agentId, "CUSTOM_EVENT", event);
441
+ },
442
+ };
443
+
444
+ const { unsubscribe } = agent.subscribe(subscriber);
445
+ this.agentSubscriptions.set(agentId, unsubscribe);
446
+ this.syncAgentMessages(agent);
447
+ this.syncAgentState(agent);
448
+
449
+ if (!this.agentEvents.has(agentId)) {
450
+ this.agentEvents.set(agentId, []);
451
+ }
452
+ }
453
+
454
+ private unsubscribeFromAgent(agentId: string): void {
455
+ const unsubscribe = this.agentSubscriptions.get(agentId);
456
+ if (unsubscribe) {
457
+ unsubscribe();
458
+ this.agentSubscriptions.delete(agentId);
459
+ }
460
+ }
461
+
462
+ private recordAgentEvent(agentId: string, type: InspectorAgentEventType, payload: unknown): void {
463
+ const eventId = `${agentId}:${++this.eventCounter}`;
464
+ const normalizedPayload = this.normalizeEventPayload(type, payload);
465
+ const event: InspectorEvent = {
466
+ id: eventId,
467
+ agentId,
468
+ type,
469
+ timestamp: Date.now(),
470
+ payload: normalizedPayload,
471
+ };
472
+
473
+ const currentAgentEvents = this.agentEvents.get(agentId) ?? [];
474
+ const nextAgentEvents = [event, ...currentAgentEvents].slice(0, MAX_AGENT_EVENTS);
475
+ this.agentEvents.set(agentId, nextAgentEvents);
476
+
477
+ this.flattenedEvents = [event, ...this.flattenedEvents].slice(0, MAX_TOTAL_EVENTS);
478
+ this.refreshToolsSnapshot();
479
+ this.requestUpdate();
480
+ }
481
+
482
+ private syncAgentMessages(agent: AbstractAgent): void {
483
+ if (!agent?.agentId) {
484
+ return;
485
+ }
486
+
487
+ const messages = this.normalizeAgentMessages((agent as { messages?: unknown }).messages);
488
+ if (messages) {
489
+ this.agentMessages.set(agent.agentId, messages);
490
+ } else {
491
+ this.agentMessages.delete(agent.agentId);
492
+ }
493
+
494
+ this.requestUpdate();
495
+ }
496
+
497
+ private syncAgentState(agent: AbstractAgent): void {
498
+ if (!agent?.agentId) {
499
+ return;
500
+ }
501
+
502
+ const state = (agent as { state?: unknown }).state;
503
+
504
+ if (state === undefined || state === null) {
505
+ this.agentStates.delete(agent.agentId);
506
+ } else {
507
+ this.agentStates.set(agent.agentId, this.sanitizeForLogging(state));
508
+ }
509
+
510
+ this.requestUpdate();
511
+ }
512
+
513
+ private updateContextOptions(agentIds: Set<string>): void {
514
+ const nextOptions: Array<{ key: string; label: string }> = [
515
+ { key: "all-agents", label: "All Agents" },
516
+ ...Array.from(agentIds)
517
+ .sort((a, b) => a.localeCompare(b))
518
+ .map((id) => ({ key: id, label: id })),
519
+ ];
520
+
521
+ const optionsChanged =
522
+ this.contextOptions.length !== nextOptions.length ||
523
+ this.contextOptions.some((option, index) => option.key !== nextOptions[index]?.key);
524
+
525
+ if (optionsChanged) {
526
+ this.contextOptions = nextOptions;
527
+ }
528
+
529
+ const pendingContext = this.pendingSelectedContext;
530
+ if (pendingContext) {
531
+ const isPendingAvailable = pendingContext === "all-agents" || agentIds.has(pendingContext);
532
+ if (isPendingAvailable) {
533
+ if (this.selectedContext !== pendingContext) {
534
+ this.selectedContext = pendingContext;
535
+ this.expandedRows.clear();
536
+ }
537
+ this.pendingSelectedContext = null;
538
+ } else if (agentIds.size > 0) {
539
+ // Agents are loaded but the pending selection no longer exists
540
+ this.pendingSelectedContext = null;
541
+ }
542
+ }
543
+
544
+ const hasSelectedContext = nextOptions.some((option) => option.key === this.selectedContext);
545
+
546
+ if (!hasSelectedContext && this.pendingSelectedContext === null) {
547
+ // Auto-select "default" agent if it exists, otherwise first agent, otherwise "all-agents"
548
+ let nextSelected: string = "all-agents";
549
+
550
+ if (agentIds.has("default")) {
551
+ nextSelected = "default";
552
+ } else if (agentIds.size > 0) {
553
+ nextSelected = Array.from(agentIds).sort((a, b) => a.localeCompare(b))[0]!;
554
+ }
555
+
556
+ if (this.selectedContext !== nextSelected) {
557
+ this.selectedContext = nextSelected;
558
+ this.expandedRows.clear();
559
+ this.persistState();
560
+ }
561
+ }
562
+ }
563
+
564
+ private getEventsForSelectedContext(): InspectorEvent[] {
565
+ if (this.selectedContext === "all-agents") {
566
+ return this.flattenedEvents;
567
+ }
568
+
569
+ return this.agentEvents.get(this.selectedContext) ?? [];
570
+ }
571
+
572
+ private filterEvents(events: InspectorEvent[]): InspectorEvent[] {
573
+ const query = this.eventFilterText.trim().toLowerCase();
574
+
575
+ return events.filter((event) => {
576
+ if (this.eventTypeFilter !== "all" && event.type !== this.eventTypeFilter) {
577
+ return false;
578
+ }
579
+
580
+ if (!query) {
581
+ return true;
582
+ }
583
+
584
+ const payloadText = this.stringifyPayload(event.payload, false).toLowerCase();
585
+ return (
586
+ event.type.toLowerCase().includes(query) ||
587
+ event.agentId.toLowerCase().includes(query) ||
588
+ payloadText.includes(query)
589
+ );
590
+ });
591
+ }
592
+
593
+ private getLatestStateForAgent(agentId: string): SanitizedValue | null {
594
+ if (this.agentStates.has(agentId)) {
595
+ const value = this.agentStates.get(agentId);
596
+ return value === undefined ? null : value;
597
+ }
598
+
599
+ const events = this.agentEvents.get(agentId) ?? [];
600
+ const stateEvent = events.find((e) => e.type === "STATE_SNAPSHOT");
601
+ if (!stateEvent) {
602
+ return null;
603
+ }
604
+ return stateEvent.payload;
605
+ }
606
+
607
+ private getLatestMessagesForAgent(agentId: string): InspectorMessage[] | null {
608
+ const messages = this.agentMessages.get(agentId);
609
+ return messages ?? null;
610
+ }
611
+
612
+ private getAgentStatus(agentId: string): "running" | "idle" | "error" {
613
+ const events = this.agentEvents.get(agentId) ?? [];
614
+ if (events.length === 0) {
615
+ return "idle";
616
+ }
617
+
618
+ // Check most recent run-related event
619
+ const runEvent = events.find((e) => e.type === "RUN_STARTED" || e.type === "RUN_FINISHED" || e.type === "RUN_ERROR");
620
+
621
+ if (!runEvent) {
622
+ return "idle";
623
+ }
624
+
625
+ if (runEvent.type === "RUN_ERROR") {
626
+ return "error";
627
+ }
628
+
629
+ if (runEvent.type === "RUN_STARTED") {
630
+ // Check if there's a RUN_FINISHED after this
631
+ const finishedAfter = events.find(
632
+ (e) => e.type === "RUN_FINISHED" && e.timestamp > runEvent.timestamp
633
+ );
634
+ return finishedAfter ? "idle" : "running";
635
+ }
636
+
637
+ return "idle";
638
+ }
639
+
640
+ private getAgentStats(agentId: string): { totalEvents: number; lastActivity: number | null; messages: number; toolCalls: number; errors: number } {
641
+ const events = this.agentEvents.get(agentId) ?? [];
642
+
643
+ const messages = this.agentMessages.get(agentId);
644
+
645
+ const toolCallCount = messages
646
+ ? messages.reduce((count, message) => count + (message.toolCalls?.length ?? 0), 0)
647
+ : events.filter((e) => e.type === "TOOL_CALL_END").length;
648
+
649
+ const messageCount = messages?.length ?? 0;
650
+
651
+ return {
652
+ totalEvents: events.length,
653
+ lastActivity: events[0]?.timestamp ?? null,
654
+ messages: messageCount,
655
+ toolCalls: toolCallCount,
656
+ errors: events.filter((e) => e.type === "RUN_ERROR").length,
657
+ };
658
+ }
659
+
660
+ private renderToolCallDetails(toolCalls: InspectorToolCall[]) {
661
+ if (!Array.isArray(toolCalls) || toolCalls.length === 0) {
662
+ return nothing;
663
+ }
664
+
665
+ return html`
666
+ <div class="mt-2 space-y-2">
667
+ ${toolCalls.map((call, index) => {
668
+ const functionName = call.function?.name ?? call.toolName ?? "Unknown function";
669
+ const callId = typeof call?.id === "string" ? call.id : `tool-call-${index + 1}`;
670
+ const argsString = this.formatToolCallArguments(call.function?.arguments);
671
+ return html`
672
+ <div class="rounded-md border border-gray-200 bg-gray-50 p-3 text-xs text-gray-700">
673
+ <div class="flex flex-wrap items-center justify-between gap-1 font-medium text-gray-900">
674
+ <span>${functionName}</span>
675
+ <span class="text-[10px] text-gray-500">ID: ${callId}</span>
676
+ </div>
677
+ ${argsString
678
+ ? html`<pre class="mt-2 overflow-auto rounded bg-white p-2 text-[11px] leading-relaxed text-gray-800">${argsString}</pre>`
679
+ : nothing}
680
+ </div>
681
+ `;
682
+ })}
683
+ </div>
684
+ `;
685
+ }
686
+
687
+ private formatToolCallArguments(args: unknown): string | null {
688
+ if (args === undefined || args === null || args === '') {
689
+ return null;
690
+ }
691
+
692
+ if (typeof args === 'string') {
693
+ try {
694
+ const parsed = JSON.parse(args);
695
+ return JSON.stringify(parsed, null, 2);
696
+ } catch {
697
+ return args;
698
+ }
699
+ }
700
+
701
+ if (typeof args === 'object') {
702
+ try {
703
+ return JSON.stringify(args, null, 2);
704
+ } catch {
705
+ return String(args);
706
+ }
707
+ }
708
+
709
+ return String(args);
710
+ }
711
+
712
+ private hasRenderableState(state: unknown): boolean {
713
+ if (state === null || state === undefined) {
714
+ return false;
715
+ }
716
+
717
+ if (Array.isArray(state)) {
718
+ return state.length > 0;
719
+ }
720
+
721
+ if (typeof state === 'object') {
722
+ return Object.keys(state as Record<string, unknown>).length > 0;
723
+ }
724
+
725
+ if (typeof state === 'string') {
726
+ const trimmed = state.trim();
727
+ return trimmed.length > 0 && trimmed !== '{}';
728
+ }
729
+
730
+ return true;
731
+ }
732
+
733
+ private formatStateForDisplay(state: unknown): string {
734
+ if (state === null || state === undefined) {
735
+ return '';
736
+ }
737
+
738
+ if (typeof state === 'string') {
739
+ const trimmed = state.trim();
740
+ if (trimmed.length === 0) {
741
+ return '';
742
+ }
743
+ try {
744
+ const parsed = JSON.parse(trimmed);
745
+ return JSON.stringify(parsed, null, 2);
746
+ } catch {
747
+ return state;
748
+ }
749
+ }
750
+
751
+ if (typeof state === 'object') {
752
+ try {
753
+ return JSON.stringify(state, null, 2);
754
+ } catch {
755
+ return String(state);
756
+ }
757
+ }
758
+
759
+ return String(state);
760
+ }
761
+
762
+ private getEventBadgeClasses(type: string): string {
763
+ const base = "font-mono text-[10px] font-medium inline-flex items-center rounded-sm px-1.5 py-0.5 border";
764
+
765
+ if (type.startsWith("RUN_")) {
766
+ return `${base} bg-blue-50 text-blue-700 border-blue-200`;
767
+ }
768
+
769
+ if (type.startsWith("TEXT_MESSAGE")) {
770
+ return `${base} bg-emerald-50 text-emerald-700 border-emerald-200`;
771
+ }
772
+
773
+ if (type.startsWith("TOOL_CALL")) {
774
+ return `${base} bg-amber-50 text-amber-700 border-amber-200`;
775
+ }
776
+
777
+ if (type.startsWith("STATE")) {
778
+ return `${base} bg-violet-50 text-violet-700 border-violet-200`;
779
+ }
780
+
781
+ if (type.startsWith("MESSAGES")) {
782
+ return `${base} bg-sky-50 text-sky-700 border-sky-200`;
783
+ }
784
+
785
+ if (type === "RUN_ERROR") {
786
+ return `${base} bg-rose-50 text-rose-700 border-rose-200`;
787
+ }
788
+
789
+ return `${base} bg-gray-100 text-gray-600 border-gray-200`;
790
+ }
791
+
792
+ private stringifyPayload(payload: unknown, pretty: boolean): string {
793
+ try {
794
+ if (payload === undefined) {
795
+ return pretty ? "undefined" : "undefined";
796
+ }
797
+ if (typeof payload === "string") {
798
+ return payload;
799
+ }
800
+ return JSON.stringify(payload, null, pretty ? 2 : 0) ?? "";
801
+ } catch (error) {
802
+ console.warn("Failed to stringify inspector payload", error);
803
+ return String(payload);
804
+ }
805
+ }
806
+
807
+ private extractEventFromPayload(payload: unknown): unknown {
808
+ // If payload is an object with an 'event' field, extract it
809
+ if (payload && typeof payload === "object" && "event" in payload) {
810
+ return (payload as Record<string, unknown>).event;
811
+ }
812
+ // Otherwise, assume the payload itself is the event
813
+ return payload;
814
+ }
815
+
816
+ private async copyToClipboard(text: string, eventId: string): Promise<void> {
817
+ try {
818
+ await navigator.clipboard.writeText(text);
819
+ this.copiedEvents.add(eventId);
820
+ this.requestUpdate();
821
+
822
+ // Clear the "copied" state after 2 seconds
823
+ setTimeout(() => {
824
+ this.copiedEvents.delete(eventId);
825
+ this.requestUpdate();
826
+ }, 2000);
827
+ } catch (err) {
828
+ console.error("Failed to copy to clipboard:", err);
829
+ }
830
+ }
831
+
832
+ static styles = [
833
+ unsafeCSS(tailwindStyles),
834
+ css`
835
+ :host {
836
+ position: fixed;
837
+ top: 0;
838
+ left: 0;
839
+ z-index: 2147483646;
840
+ display: block;
841
+ will-change: transform;
842
+ }
843
+
844
+ :host([data-transitioning="true"]) {
845
+ transition: transform 300ms ease;
846
+ }
847
+
848
+ .console-button {
849
+ transition:
850
+ transform 300ms cubic-bezier(0.34, 1.56, 0.64, 1),
851
+ opacity 160ms ease;
852
+ }
853
+
854
+ .console-button[data-dragging="true"] {
855
+ transition: opacity 160ms ease;
856
+ }
857
+
858
+ .inspector-window[data-transitioning="true"] {
859
+ transition: width 300ms ease, height 300ms ease;
860
+ }
861
+
862
+ .inspector-window[data-docked="true"] {
863
+ border-radius: 0 !important;
864
+ box-shadow: none !important;
865
+ }
866
+
867
+ .resize-handle {
868
+ touch-action: none;
869
+ user-select: none;
870
+ }
871
+
872
+ .dock-resize-handle {
873
+ position: absolute;
874
+ top: 0;
875
+ right: 0;
876
+ width: 10px;
877
+ height: 100%;
878
+ cursor: ew-resize;
879
+ touch-action: none;
880
+ z-index: 50;
881
+ background: transparent;
882
+ }
883
+
884
+ .tooltip-target {
885
+ position: relative;
886
+ }
887
+
888
+ .tooltip-target::after {
889
+ content: attr(data-tooltip);
890
+ position: absolute;
891
+ top: calc(100% + 6px);
892
+ left: 50%;
893
+ transform: translateX(-50%) translateY(-4px);
894
+ white-space: nowrap;
895
+ background: rgba(17, 24, 39, 0.95);
896
+ color: white;
897
+ padding: 4px 8px;
898
+ border-radius: 6px;
899
+ font-size: 10px;
900
+ line-height: 1.2;
901
+ box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
902
+ opacity: 0;
903
+ pointer-events: none;
904
+ transition: opacity 120ms ease, transform 120ms ease;
905
+ z-index: 4000;
906
+ }
907
+
908
+ .tooltip-target:hover::after {
909
+ opacity: 1;
910
+ transform: translateX(-50%) translateY(0);
911
+ }
912
+
913
+ .announcement-preview {
914
+ position: absolute;
915
+ top: 50%;
916
+ transform: translateY(-50%);
917
+ min-width: 300px;
918
+ max-width: 300px;
919
+ background: white;
920
+ color: #111827;
921
+ font-size: 13px;
922
+ line-height: 1.4;
923
+ border-radius: 12px;
924
+ box-shadow: 0 12px 28px rgba(15, 23, 42, 0.22);
925
+ padding: 10px 12px;
926
+ display: inline-flex;
927
+ align-items: flex-start;
928
+ gap: 8px;
929
+ z-index: 4500;
930
+ animation: fade-slide-in 160ms ease;
931
+ border: 1px solid rgba(148, 163, 184, 0.35);
932
+ white-space: normal;
933
+ word-break: break-word;
934
+ text-align: left;
935
+ }
936
+
937
+ .announcement-preview[data-side="left"] {
938
+ right: 100%;
939
+ margin-right: 10px;
940
+ }
941
+
942
+ .announcement-preview[data-side="right"] {
943
+ left: 100%;
944
+ margin-left: 10px;
945
+ }
946
+
947
+ .announcement-preview__arrow {
948
+ position: absolute;
949
+ width: 10px;
950
+ height: 10px;
951
+ background: white;
952
+ border: 1px solid rgba(148, 163, 184, 0.35);
953
+ transform: rotate(45deg);
954
+ top: 50%;
955
+ margin-top: -5px;
956
+ z-index: -1;
957
+ }
958
+
959
+ .announcement-preview[data-side="left"] .announcement-preview__arrow {
960
+ right: -5px;
961
+ box-shadow: 6px -6px 10px rgba(15, 23, 42, 0.12);
962
+ }
963
+
964
+ .announcement-preview[data-side="right"] .announcement-preview__arrow {
965
+ left: -5px;
966
+ box-shadow: -6px 6px 10px rgba(15, 23, 42, 0.12);
967
+ }
968
+
969
+ .announcement-dismiss {
970
+ color: #6b7280;
971
+ font-size: 12px;
972
+ padding: 2px 8px;
973
+ border-radius: 8px;
974
+ border: 1px solid rgba(148, 163, 184, 0.5);
975
+ background: rgba(248, 250, 252, 0.9);
976
+ transition: background 120ms ease, color 120ms ease;
977
+ }
978
+
979
+ .announcement-dismiss:hover {
980
+ background: rgba(241, 245, 249, 1);
981
+ color: #111827;
982
+ }
983
+
984
+ .announcement-content {
985
+ color: #111827;
986
+ font-size: 14px;
987
+ line-height: 1.6;
988
+ }
989
+
990
+ .announcement-content h1,
991
+ .announcement-content h2,
992
+ .announcement-content h3 {
993
+ font-weight: 700;
994
+ margin: 0.4rem 0 0.2rem;
995
+ }
996
+
997
+ .announcement-content h1 {
998
+ font-size: 1.1rem;
999
+ }
1000
+
1001
+ .announcement-content h2 {
1002
+ font-size: 1rem;
1003
+ }
1004
+
1005
+ .announcement-content h3 {
1006
+ font-size: 0.95rem;
1007
+ }
1008
+
1009
+ .announcement-content p {
1010
+ margin: 0.25rem 0;
1011
+ }
1012
+
1013
+ .announcement-content ul {
1014
+ list-style: disc;
1015
+ padding-left: 1.25rem;
1016
+ margin: 0.3rem 0;
1017
+ }
1018
+
1019
+ .announcement-content ol {
1020
+ list-style: decimal;
1021
+ padding-left: 1.25rem;
1022
+ margin: 0.3rem 0;
1023
+ }
1024
+
1025
+ .announcement-content a {
1026
+ color: #0f766e;
1027
+ text-decoration: underline;
1028
+ }
1029
+ `,
1030
+ ];
1031
+
1032
+ connectedCallback(): void {
1033
+ super.connectedCallback();
1034
+ if (typeof window !== "undefined") {
1035
+ window.addEventListener("resize", this.handleResize);
1036
+ window.addEventListener("pointerdown", this.handleGlobalPointerDown as EventListener);
1037
+
1038
+ // Load state early (before first render) so menu selection is correct
1039
+ this.hydrateStateFromStorageEarly();
1040
+ this.tryAutoAttachCore();
1041
+ this.ensureAnnouncementLoading();
1042
+ }
1043
+ }
1044
+
1045
+ disconnectedCallback(): void {
1046
+ super.disconnectedCallback();
1047
+ if (typeof window !== "undefined") {
1048
+ window.removeEventListener("resize", this.handleResize);
1049
+ window.removeEventListener("pointerdown", this.handleGlobalPointerDown as EventListener);
1050
+ }
1051
+ this.removeDockStyles(); // Clean up any docking styles
1052
+ this.detachFromCore();
1053
+ }
1054
+
1055
+ firstUpdated(): void {
1056
+ if (typeof window === "undefined") {
1057
+ return;
1058
+ }
1059
+
1060
+ if (!this._core) {
1061
+ this.tryAutoAttachCore();
1062
+ }
1063
+
1064
+ this.measureContext("button");
1065
+ this.measureContext("window");
1066
+
1067
+ this.contextState.button.anchor = { horizontal: "right", vertical: "top" };
1068
+ this.contextState.button.anchorOffset = { x: EDGE_MARGIN, y: EDGE_MARGIN };
1069
+
1070
+ this.contextState.window.anchor = { horizontal: "right", vertical: "top" };
1071
+ this.contextState.window.anchorOffset = { x: EDGE_MARGIN, y: EDGE_MARGIN };
1072
+
1073
+ this.hydrateStateFromStorage();
1074
+
1075
+ // Apply docking styles if open and docked (skip transition on initial load)
1076
+ if (this.isOpen && this.dockMode !== 'floating') {
1077
+ this.applyDockStyles(true);
1078
+ }
1079
+
1080
+ this.applyAnchorPosition("button");
1081
+
1082
+ if (this.dockMode === 'floating') {
1083
+ if (this.hasCustomPosition.window) {
1084
+ this.applyAnchorPosition("window");
1085
+ } else {
1086
+ this.centerContext("window");
1087
+ }
1088
+ }
1089
+
1090
+ this.ensureAnnouncementLoading();
1091
+
1092
+ this.updateHostTransform(this.isOpen ? "window" : "button");
1093
+ }
1094
+
1095
+ render() {
1096
+ return this.isOpen ? this.renderWindow() : this.renderButton();
1097
+ }
1098
+
1099
+ private renderButton() {
1100
+ const buttonClasses = [
1101
+ "console-button",
1102
+ "group",
1103
+ "relative",
1104
+ "pointer-events-auto",
1105
+ "inline-flex",
1106
+ "h-12",
1107
+ "w-12",
1108
+ "items-center",
1109
+ "justify-center",
1110
+ "rounded-full",
1111
+ "border",
1112
+ "border-white/20",
1113
+ "bg-slate-950/95",
1114
+ "text-xs",
1115
+ "font-medium",
1116
+ "text-white",
1117
+ "ring-1",
1118
+ "ring-white/10",
1119
+ "backdrop-blur-md",
1120
+ "transition",
1121
+ "hover:border-white/30",
1122
+ "hover:bg-slate-900/95",
1123
+ "hover:scale-105",
1124
+ "focus-visible:outline",
1125
+ "focus-visible:outline-2",
1126
+ "focus-visible:outline-offset-2",
1127
+ "focus-visible:outline-rose-500",
1128
+ "touch-none",
1129
+ "select-none",
1130
+ this.isDragging ? "cursor-grabbing" : "cursor-grab",
1131
+ ].join(" ");
1132
+
1133
+ return html`
1134
+ <button
1135
+ class=${buttonClasses}
1136
+ type="button"
1137
+ aria-label="Web Inspector"
1138
+ data-drag-context="button"
1139
+ data-dragging=${this.isDragging && this.pointerContext === "button" ? "true" : "false"}
1140
+ @pointerdown=${this.handlePointerDown}
1141
+ @pointermove=${this.handlePointerMove}
1142
+ @pointerup=${this.handlePointerUp}
1143
+ @pointercancel=${this.handlePointerCancel}
1144
+ @click=${this.handleButtonClick}
1145
+ >
1146
+ ${this.renderAnnouncementPreview()}
1147
+ <img src=${inspectorLogoIconUrl} alt="Inspector logo" class="h-5 w-auto" loading="lazy" />
1148
+ </button>
1149
+ `;
1150
+ }
1151
+
1152
+ private renderWindow() {
1153
+ const windowState = this.contextState.window;
1154
+ const isDocked = this.dockMode !== 'floating';
1155
+ const isTransitioning = this.hasAttribute('data-transitioning');
1156
+
1157
+ const windowStyles = isDocked
1158
+ ? this.getDockedWindowStyles()
1159
+ : {
1160
+ width: `${Math.round(windowState.size.width)}px`,
1161
+ height: `${Math.round(windowState.size.height)}px`,
1162
+ minWidth: `${MIN_WINDOW_WIDTH}px`,
1163
+ minHeight: `${MIN_WINDOW_HEIGHT}px`,
1164
+ };
1165
+
1166
+ const hasContextDropdown = this.contextOptions.length > 0;
1167
+ const contextDropdown = hasContextDropdown ? this.renderContextDropdown() : nothing;
1168
+ const coreStatus = this.getCoreStatusSummary();
1169
+ const agentSelector = hasContextDropdown
1170
+ ? contextDropdown
1171
+ : html`
1172
+ <div class="flex items-center gap-2 rounded-md border border-dashed border-gray-200 px-2 py-1 text-xs text-gray-400">
1173
+ <span>${this.renderIcon("Bot")}</span>
1174
+ <span class="truncate">No agents available</span>
1175
+ </div>
1176
+ `;
1177
+
1178
+ return html`
1179
+ <section
1180
+ 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"
1181
+ style=${styleMap(windowStyles)}
1182
+ data-docked=${isDocked}
1183
+ data-transitioning=${isTransitioning}
1184
+ >
1185
+ ${isDocked
1186
+ ? html`
1187
+ <div
1188
+ class="dock-resize-handle pointer-events-auto"
1189
+ role="presentation"
1190
+ aria-hidden="true"
1191
+ @pointerdown=${this.handleResizePointerDown}
1192
+ @pointermove=${this.handleResizePointerMove}
1193
+ @pointerup=${this.handleResizePointerUp}
1194
+ @pointercancel=${this.handleResizePointerCancel}
1195
+ ></div>
1196
+ `
1197
+ : nothing}
1198
+ <div class="flex flex-1 flex-col overflow-hidden bg-white text-gray-800">
1199
+ <div
1200
+ 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')}"
1201
+ data-drag-context="window"
1202
+ @pointerdown=${isDocked ? undefined : this.handlePointerDown}
1203
+ @pointermove=${isDocked ? undefined : this.handlePointerMove}
1204
+ @pointerup=${isDocked ? undefined : this.handlePointerUp}
1205
+ @pointercancel=${isDocked ? undefined : this.handlePointerCancel}
1206
+ >
1207
+ <div class="flex flex-wrap items-center gap-3 px-4 py-3">
1208
+ <div class="flex items-center min-w-0">
1209
+ <img src=${inspectorLogoUrl} alt="Inspector logo" class="h-6 w-auto" loading="lazy" />
1210
+ </div>
1211
+ <div class="ml-auto flex min-w-0 items-center gap-2">
1212
+ <div class="min-w-[160px] max-w-xs">
1213
+ ${agentSelector}
1214
+ </div>
1215
+ <div class="flex items-center gap-1">
1216
+ ${this.renderDockControls()}
1217
+ <button
1218
+ 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"
1219
+ type="button"
1220
+ aria-label="Close Web Inspector"
1221
+ @pointerdown=${this.handleClosePointerDown}
1222
+ @click=${this.handleCloseClick}
1223
+ >
1224
+ ${this.renderIcon("X")}
1225
+ </button>
1226
+ </div>
1227
+ </div>
1228
+ </div>
1229
+ <div class="flex flex-wrap items-center gap-2 border-t border-gray-100 px-3 py-2 text-xs">
1230
+ ${this.menuItems.map(({ key, label, icon }) => {
1231
+ const isSelected = this.selectedMenu === key;
1232
+ const tabClasses = [
1233
+ "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",
1234
+ isSelected ? "bg-gray-900 text-white shadow-sm" : "text-gray-600 hover:bg-gray-100 hover:text-gray-900",
1235
+ ].join(" ");
1236
+
1237
+ return html`
1238
+ <button
1239
+ type="button"
1240
+ class=${tabClasses}
1241
+ aria-pressed=${isSelected}
1242
+ @click=${() => this.handleMenuSelect(key)}
1243
+ >
1244
+ <span class="text-gray-400 ${isSelected ? 'text-white' : ''}">
1245
+ ${this.renderIcon(icon)}
1246
+ </span>
1247
+ <span>${label}</span>
1248
+ </button>
1249
+ `;
1250
+ })}
1251
+ </div>
1252
+ </div>
1253
+ <div class="flex flex-1 flex-col overflow-hidden">
1254
+ <div class="flex-1 overflow-auto">
1255
+ ${this.renderAnnouncementPanel()}
1256
+ ${this.renderCoreWarningBanner()}
1257
+ ${this.renderMainContent()}
1258
+ <slot></slot>
1259
+ </div>
1260
+ <div class="border-t border-gray-200 bg-gray-50 px-4 py-2">
1261
+ <div
1262
+ class="flex items-center gap-2 rounded-md px-3 py-2 text-xs ${coreStatus.tone} w-full overflow-hidden my-1"
1263
+ title=${coreStatus.description}
1264
+ >
1265
+ <span class="flex h-6 w-6 items-center justify-center rounded bg-white/60">
1266
+ ${this.renderIcon("Activity")}
1267
+ </span>
1268
+ <span class="font-medium">${coreStatus.label}</span>
1269
+ <span class="truncate text-[11px] opacity-80">${coreStatus.description}</span>
1270
+ </div>
1271
+ </div>
1272
+ </div>
1273
+ </div>
1274
+ <div
1275
+ 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"
1276
+ role="presentation"
1277
+ aria-hidden="true"
1278
+ @pointerdown=${this.handleResizePointerDown}
1279
+ @pointermove=${this.handleResizePointerMove}
1280
+ @pointerup=${this.handleResizePointerUp}
1281
+ @pointercancel=${this.handleResizePointerCancel}
1282
+ >
1283
+ <svg
1284
+ class="h-3 w-3"
1285
+ viewBox="0 0 16 16"
1286
+ fill="none"
1287
+ stroke="currentColor"
1288
+ stroke-linecap="round"
1289
+ stroke-width="1.5"
1290
+ >
1291
+ <path d="M5 15L15 5" />
1292
+ <path d="M9 15L15 9" />
1293
+ </svg>
1294
+ </div>
1295
+ </section>
1296
+ `;
1297
+ }
1298
+
1299
+ private hydrateStateFromStorageEarly(): void {
1300
+ if (typeof document === "undefined" || typeof window === "undefined") {
1301
+ return;
1302
+ }
1303
+
1304
+ const persisted = loadInspectorState(INSPECTOR_STORAGE_KEY);
1305
+ if (!persisted) {
1306
+ return;
1307
+ }
1308
+
1309
+ // Restore the open/closed state
1310
+ if (typeof persisted.isOpen === "boolean") {
1311
+ this.isOpen = persisted.isOpen;
1312
+ }
1313
+
1314
+ // Restore the dock mode
1315
+ if (isValidDockMode(persisted.dockMode)) {
1316
+ this.dockMode = persisted.dockMode;
1317
+ }
1318
+
1319
+ // Restore selected menu
1320
+ if (typeof persisted.selectedMenu === "string") {
1321
+ const validMenu = this.menuItems.find((item) => item.key === persisted.selectedMenu);
1322
+ if (validMenu) {
1323
+ this.selectedMenu = validMenu.key;
1324
+ }
1325
+ }
1326
+
1327
+ // Restore selected context (agent), will be validated later against available agents
1328
+ if (typeof persisted.selectedContext === "string") {
1329
+ this.selectedContext = persisted.selectedContext;
1330
+ this.pendingSelectedContext = persisted.selectedContext;
1331
+ }
1332
+ }
1333
+
1334
+ private hydrateStateFromStorage(): void {
1335
+ if (typeof document === "undefined" || typeof window === "undefined") {
1336
+ return;
1337
+ }
1338
+
1339
+ const persisted = loadInspectorState(INSPECTOR_STORAGE_KEY);
1340
+ if (!persisted) {
1341
+ return;
1342
+ }
1343
+
1344
+ const persistedButton = persisted.button;
1345
+ if (persistedButton) {
1346
+ if (isValidAnchor(persistedButton.anchor)) {
1347
+ this.contextState.button.anchor = persistedButton.anchor;
1348
+ }
1349
+
1350
+ if (isValidPosition(persistedButton.anchorOffset)) {
1351
+ this.contextState.button.anchorOffset = persistedButton.anchorOffset;
1352
+ }
1353
+
1354
+ if (typeof persistedButton.hasCustomPosition === "boolean") {
1355
+ this.hasCustomPosition.button = persistedButton.hasCustomPosition;
1356
+ }
1357
+ }
1358
+
1359
+ const persistedWindow = persisted.window;
1360
+ if (persistedWindow) {
1361
+ if (isValidAnchor(persistedWindow.anchor)) {
1362
+ this.contextState.window.anchor = persistedWindow.anchor;
1363
+ }
1364
+
1365
+ if (isValidPosition(persistedWindow.anchorOffset)) {
1366
+ this.contextState.window.anchorOffset = persistedWindow.anchorOffset;
1367
+ }
1368
+
1369
+ if (isValidSize(persistedWindow.size)) {
1370
+ // Now clampWindowSize will use the correct minimum based on dockMode
1371
+ this.contextState.window.size = this.clampWindowSize(persistedWindow.size);
1372
+ }
1373
+
1374
+ if (typeof persistedWindow.hasCustomPosition === "boolean") {
1375
+ this.hasCustomPosition.window = persistedWindow.hasCustomPosition;
1376
+ }
1377
+ }
1378
+
1379
+ if (typeof persisted.selectedContext === "string") {
1380
+ this.selectedContext = persisted.selectedContext;
1381
+ this.pendingSelectedContext = persisted.selectedContext;
1382
+ }
1383
+ }
1384
+
1385
+ private get activeContext(): ContextKey {
1386
+ return this.isOpen ? "window" : "button";
1387
+ }
1388
+
1389
+ private handlePointerDown = (event: PointerEvent) => {
1390
+ // Don't allow dragging when docked
1391
+ if (this.dockMode !== 'floating' && this.isOpen) {
1392
+ return;
1393
+ }
1394
+
1395
+ const target = event.currentTarget as HTMLElement | null;
1396
+ const contextAttr = target?.dataset.dragContext;
1397
+ const context: ContextKey = contextAttr === "window" ? "window" : "button";
1398
+
1399
+ const eventTarget = event.target as HTMLElement | null;
1400
+ if (context === "window" && eventTarget?.closest("button")) {
1401
+ return;
1402
+ }
1403
+
1404
+ this.pointerContext = context;
1405
+ this.measureContext(context);
1406
+
1407
+ event.preventDefault();
1408
+
1409
+ this.pointerId = event.pointerId;
1410
+ this.dragStart = { x: event.clientX, y: event.clientY };
1411
+ const state = this.contextState[context];
1412
+ this.dragOffset = {
1413
+ x: event.clientX - state.position.x,
1414
+ y: event.clientY - state.position.y,
1415
+ };
1416
+ this.isDragging = false;
1417
+ this.draggedDuringInteraction = false;
1418
+ this.ignoreNextButtonClick = false;
1419
+
1420
+ target?.setPointerCapture?.(this.pointerId);
1421
+ };
1422
+
1423
+ private handlePointerMove = (event: PointerEvent) => {
1424
+ if (this.pointerId !== event.pointerId || !this.dragStart || !this.pointerContext) {
1425
+ return;
1426
+ }
1427
+
1428
+ const distance = Math.hypot(event.clientX - this.dragStart.x, event.clientY - this.dragStart.y);
1429
+ if (!this.isDragging && distance < DRAG_THRESHOLD) {
1430
+ return;
1431
+ }
1432
+
1433
+ event.preventDefault();
1434
+ this.setDragging(true);
1435
+ this.draggedDuringInteraction = true;
1436
+
1437
+ const desired: Position = {
1438
+ x: event.clientX - this.dragOffset.x,
1439
+ y: event.clientY - this.dragOffset.y,
1440
+ };
1441
+
1442
+ const constrained = this.constrainToViewport(desired, this.pointerContext);
1443
+ this.contextState[this.pointerContext].position = constrained;
1444
+ this.updateHostTransform(this.pointerContext);
1445
+ };
1446
+
1447
+ private handlePointerUp = (event: PointerEvent) => {
1448
+ if (this.pointerId !== event.pointerId) {
1449
+ return;
1450
+ }
1451
+
1452
+ const target = event.currentTarget as HTMLElement | null;
1453
+ if (target?.hasPointerCapture(this.pointerId)) {
1454
+ target.releasePointerCapture(this.pointerId);
1455
+ }
1456
+
1457
+ const context = this.pointerContext ?? this.activeContext;
1458
+
1459
+ if (this.isDragging && this.pointerContext) {
1460
+ event.preventDefault();
1461
+ this.setDragging(false);
1462
+ if (this.pointerContext === "window") {
1463
+ this.updateAnchorFromPosition(this.pointerContext);
1464
+ this.hasCustomPosition.window = true;
1465
+ this.applyAnchorPosition(this.pointerContext);
1466
+ } else if (this.pointerContext === "button") {
1467
+ // Snap button to nearest corner
1468
+ this.snapButtonToCorner();
1469
+ this.hasCustomPosition.button = true;
1470
+ if (this.draggedDuringInteraction) {
1471
+ this.ignoreNextButtonClick = true;
1472
+ }
1473
+ }
1474
+ } else if (context === "button" && !this.isOpen && !this.draggedDuringInteraction) {
1475
+ this.openInspector();
1476
+ }
1477
+
1478
+ this.resetPointerTracking();
1479
+ };
1480
+
1481
+ private handlePointerCancel = (event: PointerEvent) => {
1482
+ if (this.pointerId !== event.pointerId) {
1483
+ return;
1484
+ }
1485
+
1486
+ const target = event.currentTarget as HTMLElement | null;
1487
+ if (target?.hasPointerCapture(this.pointerId)) {
1488
+ target.releasePointerCapture(this.pointerId);
1489
+ }
1490
+
1491
+ this.resetPointerTracking();
1492
+ };
1493
+
1494
+ private handleButtonClick = (event: Event) => {
1495
+ if (this.isDragging) {
1496
+ event.preventDefault();
1497
+ return;
1498
+ }
1499
+
1500
+ if (this.ignoreNextButtonClick) {
1501
+ event.preventDefault();
1502
+ this.ignoreNextButtonClick = false;
1503
+ return;
1504
+ }
1505
+
1506
+ if (!this.isOpen) {
1507
+ event.preventDefault();
1508
+ this.openInspector();
1509
+ }
1510
+ };
1511
+
1512
+ private handleClosePointerDown = (event: PointerEvent) => {
1513
+ event.stopPropagation();
1514
+ event.preventDefault();
1515
+ };
1516
+
1517
+ private handleCloseClick = () => {
1518
+ this.closeInspector();
1519
+ };
1520
+
1521
+ private handleResizePointerDown = (event: PointerEvent) => {
1522
+ event.stopPropagation();
1523
+ event.preventDefault();
1524
+
1525
+ this.hasCustomPosition.window = true;
1526
+ this.isResizing = true;
1527
+ this.resizePointerId = event.pointerId;
1528
+ this.resizeStart = { x: event.clientX, y: event.clientY };
1529
+ this.resizeInitialSize = { ...this.contextState.window.size };
1530
+
1531
+ // Remove transition from body during resize to prevent lag
1532
+ if (document.body && this.dockMode !== 'floating') {
1533
+ document.body.style.transition = '';
1534
+ }
1535
+
1536
+ const target = event.currentTarget as HTMLElement | null;
1537
+ target?.setPointerCapture?.(event.pointerId);
1538
+ };
1539
+
1540
+ private handleResizePointerMove = (event: PointerEvent) => {
1541
+ if (!this.isResizing || this.resizePointerId !== event.pointerId || !this.resizeStart || !this.resizeInitialSize) {
1542
+ return;
1543
+ }
1544
+
1545
+ event.preventDefault();
1546
+
1547
+ const deltaX = event.clientX - this.resizeStart.x;
1548
+ const deltaY = event.clientY - this.resizeStart.y;
1549
+ const state = this.contextState.window;
1550
+
1551
+ // For docked states, only resize in the appropriate dimension
1552
+ if (this.dockMode === 'docked-left') {
1553
+ // Only resize width for left dock
1554
+ state.size = this.clampWindowSize({
1555
+ width: this.resizeInitialSize.width + deltaX,
1556
+ height: state.size.height,
1557
+ });
1558
+ // Update the body margin
1559
+ if (document.body) {
1560
+ document.body.style.marginLeft = `${state.size.width}px`;
1561
+ }
1562
+ } else {
1563
+ // Full resize for floating mode
1564
+ state.size = this.clampWindowSize({
1565
+ width: this.resizeInitialSize.width + deltaX,
1566
+ height: this.resizeInitialSize.height + deltaY,
1567
+ });
1568
+ this.keepPositionWithinViewport("window");
1569
+ this.updateAnchorFromPosition("window");
1570
+ }
1571
+
1572
+ this.requestUpdate();
1573
+ this.updateHostTransform("window");
1574
+ };
1575
+
1576
+ private handleResizePointerUp = (event: PointerEvent) => {
1577
+ if (this.resizePointerId !== event.pointerId) {
1578
+ return;
1579
+ }
1580
+
1581
+ const target = event.currentTarget as HTMLElement | null;
1582
+ if (target?.hasPointerCapture(this.resizePointerId)) {
1583
+ target.releasePointerCapture(this.resizePointerId);
1584
+ }
1585
+
1586
+ // Only update anchor position for floating mode
1587
+ if (this.dockMode === 'floating') {
1588
+ this.updateAnchorFromPosition("window");
1589
+ this.applyAnchorPosition("window");
1590
+ }
1591
+
1592
+ // Persist the new size after resize completes
1593
+ this.persistState();
1594
+ this.resetResizeTracking();
1595
+ };
1596
+
1597
+ private handleResizePointerCancel = (event: PointerEvent) => {
1598
+ if (this.resizePointerId !== event.pointerId) {
1599
+ return;
1600
+ }
1601
+
1602
+ const target = event.currentTarget as HTMLElement | null;
1603
+ if (target?.hasPointerCapture(this.resizePointerId)) {
1604
+ target.releasePointerCapture(this.resizePointerId);
1605
+ }
1606
+
1607
+ // Only update anchor position for floating mode
1608
+ if (this.dockMode === 'floating') {
1609
+ this.updateAnchorFromPosition("window");
1610
+ this.applyAnchorPosition("window");
1611
+ }
1612
+
1613
+ // Persist the new size after resize completes
1614
+ this.persistState();
1615
+ this.resetResizeTracking();
1616
+ };
1617
+
1618
+ private handleResize = () => {
1619
+ this.measureContext("button");
1620
+ this.applyAnchorPosition("button");
1621
+
1622
+ this.measureContext("window");
1623
+ if (this.hasCustomPosition.window) {
1624
+ this.applyAnchorPosition("window");
1625
+ } else {
1626
+ this.centerContext("window");
1627
+ }
1628
+
1629
+ this.updateHostTransform();
1630
+ };
1631
+
1632
+ private measureContext(context: ContextKey): void {
1633
+ const selector = context === "window" ? ".inspector-window" : ".console-button";
1634
+ const element = this.renderRoot?.querySelector(selector) as HTMLElement | null;
1635
+ if (!element) {
1636
+ return;
1637
+ }
1638
+ const fallback = context === "window" ? DEFAULT_WINDOW_SIZE : DEFAULT_BUTTON_SIZE;
1639
+ updateSizeFromElement(this.contextState[context], element, fallback);
1640
+ }
1641
+
1642
+ private centerContext(context: ContextKey): void {
1643
+ if (typeof window === "undefined") {
1644
+ return;
1645
+ }
1646
+
1647
+ const viewport = this.getViewportSize();
1648
+ centerContextHelper(this.contextState[context], viewport, EDGE_MARGIN);
1649
+
1650
+ if (context === this.activeContext) {
1651
+ this.updateHostTransform(context);
1652
+ }
1653
+
1654
+ this.hasCustomPosition[context] = false;
1655
+ this.persistState();
1656
+ }
1657
+
1658
+ private ensureWindowPlacement(): void {
1659
+ if (typeof window === "undefined") {
1660
+ return;
1661
+ }
1662
+
1663
+ if (!this.hasCustomPosition.window) {
1664
+ this.centerContext("window");
1665
+ return;
1666
+ }
1667
+
1668
+ const viewport = this.getViewportSize();
1669
+ keepPositionWithinViewport(this.contextState.window, viewport, EDGE_MARGIN);
1670
+ updateAnchorFromPositionHelper(this.contextState.window, viewport, EDGE_MARGIN);
1671
+ this.updateHostTransform("window");
1672
+ this.persistState();
1673
+ }
1674
+
1675
+ private constrainToViewport(position: Position, context: ContextKey): Position {
1676
+ if (typeof window === "undefined") {
1677
+ return position;
1678
+ }
1679
+
1680
+ const viewport = this.getViewportSize();
1681
+ return constrainToViewport(this.contextState[context], position, viewport, EDGE_MARGIN);
1682
+ }
1683
+
1684
+ private keepPositionWithinViewport(context: ContextKey): void {
1685
+ if (typeof window === "undefined") {
1686
+ return;
1687
+ }
1688
+
1689
+ const viewport = this.getViewportSize();
1690
+ keepPositionWithinViewport(this.contextState[context], viewport, EDGE_MARGIN);
1691
+ }
1692
+
1693
+ private getViewportSize(): Size {
1694
+ if (typeof window === "undefined") {
1695
+ return { ...DEFAULT_WINDOW_SIZE };
1696
+ }
1697
+
1698
+ return { width: window.innerWidth, height: window.innerHeight };
1699
+ }
1700
+
1701
+ private persistState(): void {
1702
+ const state: PersistedState = {
1703
+ button: {
1704
+ anchor: this.contextState.button.anchor,
1705
+ anchorOffset: this.contextState.button.anchorOffset,
1706
+ hasCustomPosition: this.hasCustomPosition.button,
1707
+ },
1708
+ window: {
1709
+ anchor: this.contextState.window.anchor,
1710
+ anchorOffset: this.contextState.window.anchorOffset,
1711
+ size: {
1712
+ width: Math.round(this.contextState.window.size.width),
1713
+ height: Math.round(this.contextState.window.size.height),
1714
+ },
1715
+ hasCustomPosition: this.hasCustomPosition.window,
1716
+ },
1717
+ isOpen: this.isOpen,
1718
+ dockMode: this.dockMode,
1719
+ selectedMenu: this.selectedMenu,
1720
+ selectedContext: this.selectedContext,
1721
+ };
1722
+ saveInspectorState(INSPECTOR_STORAGE_KEY, state);
1723
+ this.pendingSelectedContext = state.selectedContext ?? null;
1724
+ }
1725
+
1726
+ private clampWindowSize(size: Size): Size {
1727
+ // Use smaller minimum width when docked left
1728
+ const minWidth = this.dockMode === 'docked-left' ? MIN_WINDOW_WIDTH_DOCKED_LEFT : MIN_WINDOW_WIDTH;
1729
+
1730
+ if (typeof window === "undefined") {
1731
+ return {
1732
+ width: Math.max(minWidth, size.width),
1733
+ height: Math.max(MIN_WINDOW_HEIGHT, size.height),
1734
+ };
1735
+ }
1736
+
1737
+ const viewport = this.getViewportSize();
1738
+ return clampSizeToViewport(size, viewport, EDGE_MARGIN, minWidth, MIN_WINDOW_HEIGHT);
1739
+ }
1740
+
1741
+ private setDockMode(mode: DockMode): void {
1742
+ if (this.dockMode === mode) {
1743
+ return;
1744
+ }
1745
+
1746
+ // Add transition class for smooth dock mode changes
1747
+ this.startHostTransition();
1748
+
1749
+ // Clean up previous dock state
1750
+ this.removeDockStyles();
1751
+
1752
+ this.dockMode = mode;
1753
+
1754
+ if (mode !== 'floating') {
1755
+ // For docking, set the target size immediately so body margins are correct
1756
+ if (mode === 'docked-left') {
1757
+ this.contextState.window.size.width = DOCKED_LEFT_WIDTH;
1758
+ }
1759
+
1760
+ // Then apply dock styles with correct sizes
1761
+ this.applyDockStyles();
1762
+ } else {
1763
+ // When floating, set size first then center
1764
+ this.contextState.window.size = { ...DEFAULT_WINDOW_SIZE };
1765
+ this.centerContext('window');
1766
+ }
1767
+
1768
+ this.persistState();
1769
+ this.requestUpdate();
1770
+ this.updateHostTransform('window');
1771
+ }
1772
+
1773
+ private startHostTransition(duration = 300): void {
1774
+ this.setAttribute('data-transitioning', 'true');
1775
+
1776
+ if (this.transitionTimeoutId !== null) {
1777
+ clearTimeout(this.transitionTimeoutId);
1778
+ }
1779
+
1780
+ this.transitionTimeoutId = setTimeout(() => {
1781
+ this.removeAttribute('data-transitioning');
1782
+ this.transitionTimeoutId = null;
1783
+ }, duration);
1784
+ }
1785
+
1786
+ private applyDockStyles(skipTransition = false): void {
1787
+ if (typeof document === 'undefined' || !document.body) {
1788
+ return;
1789
+ }
1790
+
1791
+ // Save original body margins
1792
+ const computedStyle = window.getComputedStyle(document.body);
1793
+ this.previousBodyMargins = {
1794
+ left: computedStyle.marginLeft,
1795
+ bottom: computedStyle.marginBottom,
1796
+ };
1797
+
1798
+ // Apply transition to body for smooth animation (only when docking, not during resize or initial load)
1799
+ if (!this.isResizing && !skipTransition) {
1800
+ document.body.style.transition = 'margin 300ms ease';
1801
+ }
1802
+
1803
+ // Apply body margins with the actual window sizes
1804
+ if (this.dockMode === 'docked-left') {
1805
+ document.body.style.marginLeft = `${this.contextState.window.size.width}px`;
1806
+ }
1807
+
1808
+ // Remove transition after animation completes
1809
+ if (!this.isResizing && !skipTransition) {
1810
+ setTimeout(() => {
1811
+ if (document.body) {
1812
+ document.body.style.transition = '';
1813
+ }
1814
+ }, 300);
1815
+ }
1816
+ }
1817
+
1818
+ private removeDockStyles(): void {
1819
+ if (typeof document === 'undefined' || !document.body) {
1820
+ return;
1821
+ }
1822
+
1823
+ // Only add transition if not resizing
1824
+ if (!this.isResizing) {
1825
+ document.body.style.transition = 'margin 300ms ease';
1826
+ }
1827
+
1828
+ // Restore original margins if saved
1829
+ if (this.previousBodyMargins) {
1830
+ document.body.style.marginLeft = this.previousBodyMargins.left;
1831
+ document.body.style.marginBottom = this.previousBodyMargins.bottom;
1832
+ this.previousBodyMargins = null;
1833
+ } else {
1834
+ // Reset to default if no previous values
1835
+ document.body.style.marginLeft = '';
1836
+ document.body.style.marginBottom = '';
1837
+ }
1838
+
1839
+ // Clean up transition after animation completes
1840
+ setTimeout(() => {
1841
+ if (document.body) {
1842
+ document.body.style.transition = '';
1843
+ }
1844
+ }, 300);
1845
+ }
1846
+
1847
+ private updateHostTransform(context: ContextKey = this.activeContext): void {
1848
+ if (context !== this.activeContext) {
1849
+ return;
1850
+ }
1851
+
1852
+ // For docked states, CSS handles positioning with fixed positioning
1853
+ if (this.isOpen && this.dockMode === 'docked-left') {
1854
+ this.style.transform = `translate3d(0, 0, 0)`;
1855
+ } else {
1856
+ const { position } = this.contextState[context];
1857
+ this.style.transform = `translate3d(${position.x}px, ${position.y}px, 0)`;
1858
+ }
1859
+ }
1860
+
1861
+ private setDragging(value: boolean): void {
1862
+ if (this.isDragging !== value) {
1863
+ this.isDragging = value;
1864
+ this.requestUpdate();
1865
+ }
1866
+ }
1867
+
1868
+ private updateAnchorFromPosition(context: ContextKey): void {
1869
+ if (typeof window === "undefined") {
1870
+ return;
1871
+ }
1872
+ const viewport = this.getViewportSize();
1873
+ updateAnchorFromPositionHelper(this.contextState[context], viewport, EDGE_MARGIN);
1874
+ }
1875
+
1876
+ private snapButtonToCorner(): void {
1877
+ if (typeof window === "undefined") {
1878
+ return;
1879
+ }
1880
+
1881
+ const viewport = this.getViewportSize();
1882
+ const state = this.contextState.button;
1883
+
1884
+ // Determine which corner is closest based on center of button
1885
+ const centerX = state.position.x + state.size.width / 2;
1886
+ const centerY = state.position.y + state.size.height / 2;
1887
+
1888
+ const horizontal: Anchor['horizontal'] = centerX < viewport.width / 2 ? 'left' : 'right';
1889
+ const vertical: Anchor['vertical'] = centerY < viewport.height / 2 ? 'top' : 'bottom';
1890
+
1891
+ // Set anchor to nearest corner
1892
+ state.anchor = { horizontal, vertical };
1893
+
1894
+ // Always use EDGE_MARGIN as offset (pinned to corner)
1895
+ state.anchorOffset = { x: EDGE_MARGIN, y: EDGE_MARGIN };
1896
+
1897
+ // Apply the anchor position to snap to corner
1898
+ this.startHostTransition();
1899
+ this.applyAnchorPosition('button');
1900
+ }
1901
+
1902
+ private applyAnchorPosition(context: ContextKey): void {
1903
+ if (typeof window === "undefined") {
1904
+ return;
1905
+ }
1906
+ const viewport = this.getViewportSize();
1907
+ applyAnchorPositionHelper(this.contextState[context], viewport, EDGE_MARGIN);
1908
+ this.updateHostTransform(context);
1909
+ this.persistState();
1910
+ }
1911
+
1912
+ private resetResizeTracking(): void {
1913
+ this.resizePointerId = null;
1914
+ this.resizeStart = null;
1915
+ this.resizeInitialSize = null;
1916
+ this.isResizing = false;
1917
+ }
1918
+
1919
+ private resetPointerTracking(): void {
1920
+ this.pointerId = null;
1921
+ this.dragStart = null;
1922
+ this.pointerContext = null;
1923
+ this.setDragging(false);
1924
+ this.draggedDuringInteraction = false;
1925
+ }
1926
+
1927
+ private openInspector(): void {
1928
+ if (this.isOpen) {
1929
+ return;
1930
+ }
1931
+
1932
+ this.showAnnouncementPreview = false; // hide the bubble once the inspector is opened
1933
+
1934
+ this.ensureAnnouncementLoading();
1935
+
1936
+ this.isOpen = true;
1937
+ this.persistState(); // Save the open state
1938
+
1939
+ // Apply docking styles if in docked mode
1940
+ if (this.dockMode !== 'floating') {
1941
+ this.applyDockStyles();
1942
+ }
1943
+
1944
+ this.ensureWindowPlacement();
1945
+ this.requestUpdate();
1946
+ void this.updateComplete.then(() => {
1947
+ this.measureContext("window");
1948
+ if (this.dockMode === 'floating') {
1949
+ if (this.hasCustomPosition.window) {
1950
+ this.applyAnchorPosition("window");
1951
+ } else {
1952
+ this.centerContext("window");
1953
+ }
1954
+ } else {
1955
+ // Update transform for docked position
1956
+ this.updateHostTransform("window");
1957
+ }
1958
+
1959
+ });
1960
+ }
1961
+
1962
+ private closeInspector(): void {
1963
+ if (!this.isOpen) {
1964
+ return;
1965
+ }
1966
+
1967
+ this.isOpen = false;
1968
+
1969
+ // Remove docking styles when closing
1970
+ if (this.dockMode !== 'floating') {
1971
+ this.removeDockStyles();
1972
+ }
1973
+
1974
+ this.persistState(); // Save the closed state
1975
+ this.updateHostTransform("button");
1976
+ this.requestUpdate();
1977
+ void this.updateComplete.then(() => {
1978
+ this.measureContext("button");
1979
+ this.applyAnchorPosition("button");
1980
+ });
1981
+ }
1982
+
1983
+ private renderIcon(name: LucideIconName) {
1984
+ const iconNode = icons[name];
1985
+ if (!iconNode) {
1986
+ return nothing;
1987
+ }
1988
+
1989
+ const svgAttrs: Record<string, string | number> = {
1990
+ xmlns: "http://www.w3.org/2000/svg",
1991
+ viewBox: "0 0 24 24",
1992
+ fill: "none",
1993
+ stroke: "currentColor",
1994
+ "stroke-width": "1.5",
1995
+ "stroke-linecap": "round",
1996
+ "stroke-linejoin": "round",
1997
+ class: "h-3.5 w-3.5",
1998
+ };
1999
+
2000
+ const svgMarkup = `<svg ${this.serializeAttributes(svgAttrs)}>${iconNode
2001
+ .map(([tag, attrs]) => `<${tag} ${this.serializeAttributes(attrs)} />`)
2002
+ .join("")}</svg>`;
2003
+
2004
+ return unsafeHTML(svgMarkup);
2005
+ }
2006
+
2007
+ private renderDockControls() {
2008
+ if (this.dockMode === 'floating') {
2009
+ // Show dock left button
2010
+ return html`
2011
+ <button
2012
+ 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"
2013
+ type="button"
2014
+ aria-label="Dock to left"
2015
+ title="Dock Left"
2016
+ @click=${() => this.handleDockClick('docked-left')}
2017
+ >
2018
+ ${this.renderIcon("PanelLeft")}
2019
+ </button>
2020
+ `;
2021
+ } else {
2022
+ // Show float button
2023
+ return html`
2024
+ <button
2025
+ 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"
2026
+ type="button"
2027
+ aria-label="Float window"
2028
+ title="Float"
2029
+ @click=${() => this.handleDockClick('floating')}
2030
+ >
2031
+ ${this.renderIcon("Maximize2")}
2032
+ </button>
2033
+ `;
2034
+ }
2035
+ }
2036
+
2037
+ private getDockedWindowStyles(): Record<string, string> {
2038
+ if (this.dockMode === 'docked-left') {
2039
+ return {
2040
+ position: 'fixed',
2041
+ top: '0',
2042
+ left: '0',
2043
+ bottom: '0',
2044
+ width: `${Math.round(this.contextState.window.size.width)}px`,
2045
+ height: '100vh',
2046
+ minWidth: `${MIN_WINDOW_WIDTH_DOCKED_LEFT}px`,
2047
+ borderRadius: '0',
2048
+ };
2049
+ }
2050
+ // Default to floating styles
2051
+ return {
2052
+ width: `${Math.round(this.contextState.window.size.width)}px`,
2053
+ height: `${Math.round(this.contextState.window.size.height)}px`,
2054
+ minWidth: `${MIN_WINDOW_WIDTH}px`,
2055
+ minHeight: `${MIN_WINDOW_HEIGHT}px`,
2056
+ };
2057
+ }
2058
+
2059
+ private handleDockClick(mode: DockMode): void {
2060
+ this.setDockMode(mode);
2061
+ }
2062
+
2063
+ private serializeAttributes(attributes: Record<string, string | number | undefined>): string {
2064
+ return Object.entries(attributes)
2065
+ .filter(([key, value]) => key !== "key" && value !== undefined && value !== null && value !== "")
2066
+ .map(([key, value]) => `${key}="${String(value).replace(/"/g, "&quot;")}"`)
2067
+ .join(" ");
2068
+ }
2069
+
2070
+ private sanitizeForLogging(value: unknown, depth = 0, seen = new WeakSet<object>()): SanitizedValue {
2071
+ if (value === undefined) {
2072
+ return "[undefined]";
2073
+ }
2074
+
2075
+ if (value === null || typeof value === "number" || typeof value === "boolean") {
2076
+ return value;
2077
+ }
2078
+
2079
+ if (typeof value === "string") {
2080
+ return value;
2081
+ }
2082
+
2083
+ if (typeof value === "bigint" || typeof value === "symbol" || typeof value === "function") {
2084
+ return String(value);
2085
+ }
2086
+
2087
+ if (value instanceof Date) {
2088
+ return value.toISOString();
2089
+ }
2090
+
2091
+ if (Array.isArray(value)) {
2092
+ if (depth >= 4) {
2093
+ return "[Truncated depth]" as SanitizedValue;
2094
+ }
2095
+ return value.map((item) => this.sanitizeForLogging(item, depth + 1, seen));
2096
+ }
2097
+
2098
+ if (typeof value === "object") {
2099
+ if (seen.has(value as object)) {
2100
+ return "[Circular]" as SanitizedValue;
2101
+ }
2102
+ seen.add(value as object);
2103
+
2104
+ if (depth >= 4) {
2105
+ return "[Truncated depth]" as SanitizedValue;
2106
+ }
2107
+
2108
+ const result: Record<string, SanitizedValue> = {};
2109
+ for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
2110
+ result[key] = this.sanitizeForLogging(entry, depth + 1, seen);
2111
+ }
2112
+ return result;
2113
+ }
2114
+
2115
+ return String(value);
2116
+ }
2117
+
2118
+ private normalizeEventPayload(_type: InspectorAgentEventType, payload: unknown): SanitizedValue {
2119
+ if (payload && typeof payload === "object" && "event" in payload) {
2120
+ const { event, ...rest } = payload as Record<string, unknown>;
2121
+ const cleaned = Object.keys(rest).length === 0 ? event : { event, ...rest };
2122
+ return this.sanitizeForLogging(cleaned);
2123
+ }
2124
+
2125
+ return this.sanitizeForLogging(payload);
2126
+ }
2127
+
2128
+ private normalizeMessageContent(content: unknown): string {
2129
+ if (typeof content === "string") {
2130
+ return content;
2131
+ }
2132
+
2133
+ if (content && typeof content === "object" && "text" in (content as Record<string, unknown>)) {
2134
+ const maybeText = (content as Record<string, unknown>).text;
2135
+ if (typeof maybeText === "string") {
2136
+ return maybeText;
2137
+ }
2138
+ }
2139
+
2140
+ if (content === null || content === undefined) {
2141
+ return "";
2142
+ }
2143
+
2144
+ if (typeof content === "object") {
2145
+ try {
2146
+ return JSON.stringify(this.sanitizeForLogging(content));
2147
+ } catch {
2148
+ return "";
2149
+ }
2150
+ }
2151
+
2152
+ return String(content);
2153
+ }
2154
+
2155
+ private normalizeToolCalls(raw: unknown): InspectorToolCall[] {
2156
+ if (!Array.isArray(raw)) {
2157
+ return [];
2158
+ }
2159
+
2160
+ return raw
2161
+ .map((entry) => {
2162
+ if (!entry || typeof entry !== "object") {
2163
+ return null;
2164
+ }
2165
+ const call = entry as Record<string, unknown>;
2166
+ const fn = call.function as Record<string, unknown> | undefined;
2167
+ const functionName = typeof fn?.name === "string" ? fn.name : typeof call.toolName === "string" ? call.toolName : undefined;
2168
+ const args = fn && "arguments" in fn ? (fn as Record<string, unknown>).arguments : call.arguments;
2169
+
2170
+ const normalized: InspectorToolCall = {
2171
+ id: typeof call.id === "string" ? call.id : undefined,
2172
+ toolName: typeof call.toolName === "string" ? call.toolName : functionName,
2173
+ status: typeof call.status === "string" ? call.status : undefined,
2174
+ };
2175
+
2176
+ if (functionName) {
2177
+ normalized.function = {
2178
+ name: functionName,
2179
+ arguments: this.sanitizeForLogging(args),
2180
+ };
2181
+ }
2182
+
2183
+ return normalized;
2184
+ })
2185
+ .filter((call): call is InspectorToolCall => Boolean(call));
2186
+ }
2187
+
2188
+ private normalizeAgentMessage(message: unknown): InspectorMessage | null {
2189
+ if (!message || typeof message !== "object") {
2190
+ return null;
2191
+ }
2192
+
2193
+ const raw = message as Record<string, unknown>;
2194
+ const role = typeof raw.role === "string" ? raw.role : "unknown";
2195
+ const contentText = this.normalizeMessageContent(raw.content);
2196
+ const toolCalls = this.normalizeToolCalls(raw.toolCalls);
2197
+
2198
+ return {
2199
+ id: typeof raw.id === "string" ? raw.id : undefined,
2200
+ role,
2201
+ contentText,
2202
+ contentRaw: raw.content !== undefined ? this.sanitizeForLogging(raw.content) : undefined,
2203
+ toolCalls,
2204
+ };
2205
+ }
2206
+
2207
+ private normalizeAgentMessages(messages: unknown): InspectorMessage[] | null {
2208
+ if (!Array.isArray(messages)) {
2209
+ return null;
2210
+ }
2211
+
2212
+ const normalized = messages
2213
+ .map((message) => this.normalizeAgentMessage(message))
2214
+ .filter((msg): msg is InspectorMessage => msg !== null);
2215
+
2216
+ return normalized;
2217
+ }
2218
+
2219
+ private normalizeContextStore(
2220
+ context: Readonly<Record<string, unknown>> | null | undefined,
2221
+ ): Record<string, { description?: string; value: unknown }> {
2222
+ if (!context || typeof context !== "object") {
2223
+ return {};
2224
+ }
2225
+
2226
+ const normalized: Record<string, { description?: string; value: unknown }> = {};
2227
+ for (const [key, entry] of Object.entries(context)) {
2228
+ if (entry && typeof entry === "object" && "value" in (entry as Record<string, unknown>)) {
2229
+ const candidate = entry as Record<string, unknown>;
2230
+ const description =
2231
+ typeof candidate.description === "string" && candidate.description.trim().length > 0
2232
+ ? candidate.description
2233
+ : undefined;
2234
+ normalized[key] = { description, value: candidate.value };
2235
+ } else {
2236
+ normalized[key] = { value: entry };
2237
+ }
2238
+ }
2239
+
2240
+ return normalized;
2241
+ }
2242
+
2243
+ private contextOptions: Array<{ key: string; label: string }> = [
2244
+ { key: "all-agents", label: "All Agents" },
2245
+ ];
2246
+
2247
+ private selectedContext = "all-agents";
2248
+ private expandedRows: Set<string> = new Set();
2249
+ private copiedEvents: Set<string> = new Set();
2250
+ private expandedTools: Set<string> = new Set();
2251
+ private expandedContextItems: Set<string> = new Set();
2252
+ private copiedContextItems: Set<string> = new Set();
2253
+
2254
+ private getSelectedMenu(): MenuItem {
2255
+ const found = this.menuItems.find((item) => item.key === this.selectedMenu);
2256
+ return found ?? this.menuItems[0]!;
2257
+ }
2258
+
2259
+ private renderCoreWarningBanner() {
2260
+ if (this._core) {
2261
+ return nothing;
2262
+ }
2263
+
2264
+ return html`
2265
+ <div 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">
2266
+ <span class="mt-0.5 shrink-0 text-amber-600">${this.renderIcon("AlertTriangle")}</span>
2267
+ <div class="space-y-1">
2268
+ <div class="font-semibold text-amber-900">CopilotKit core not attached</div>
2269
+ <p class="text-[11px] leading-snug text-amber-800">
2270
+ Pass a live <code>CopilotKitCore</code> instance to <code>&lt;cpk-web-inspector&gt;</code> or expose it on
2271
+ <code>window.__COPILOTKIT_CORE__</code> for auto-attach.
2272
+ </p>
2273
+ </div>
2274
+ </div>
2275
+ `;
2276
+ }
2277
+
2278
+ private getCoreStatusSummary(): { label: string; tone: string; description: string } {
2279
+ if (!this._core) {
2280
+ return {
2281
+ label: "Core not attached",
2282
+ tone: "border border-amber-200 bg-amber-50 text-amber-800",
2283
+ description: "Pass a CopilotKitCore instance to <cpk-web-inspector> or enable auto-attach.",
2284
+ };
2285
+ }
2286
+
2287
+ const status = this.runtimeStatus ?? CopilotKitCoreRuntimeConnectionStatus.Disconnected;
2288
+ const lastErrorMessage = this.lastCoreError?.message;
2289
+
2290
+ if (status === CopilotKitCoreRuntimeConnectionStatus.Error) {
2291
+ return {
2292
+ label: "Runtime error",
2293
+ tone: "border border-rose-200 bg-rose-50 text-rose-700",
2294
+ description: lastErrorMessage ?? "CopilotKit runtime reported an error.",
2295
+ };
2296
+ }
2297
+
2298
+ if (status === CopilotKitCoreRuntimeConnectionStatus.Connecting) {
2299
+ return {
2300
+ label: "Connecting",
2301
+ tone: "border border-amber-200 bg-amber-50 text-amber-800",
2302
+ description: "Waiting for CopilotKit runtime to finish connecting.",
2303
+ };
2304
+ }
2305
+
2306
+ if (status === CopilotKitCoreRuntimeConnectionStatus.Connected) {
2307
+ return {
2308
+ label: "Connected",
2309
+ tone: "border border-emerald-200 bg-emerald-50 text-emerald-700",
2310
+ description: "Live runtime connection established.",
2311
+ };
2312
+ }
2313
+
2314
+ return {
2315
+ label: "Disconnected",
2316
+ tone: "border border-gray-200 bg-gray-50 text-gray-700",
2317
+ description: lastErrorMessage ?? "Waiting for CopilotKit runtime to connect.",
2318
+ };
2319
+ }
2320
+
2321
+ private renderMainContent() {
2322
+ if (this.selectedMenu === "ag-ui-events") {
2323
+ return this.renderEventsTable();
2324
+ }
2325
+
2326
+ if (this.selectedMenu === "agents") {
2327
+ return this.renderAgentsView();
2328
+ }
2329
+
2330
+ if (this.selectedMenu === "frontend-tools") {
2331
+ return this.renderToolsView();
2332
+ }
2333
+
2334
+ if (this.selectedMenu === "agent-context") {
2335
+ return this.renderContextView();
2336
+ }
2337
+
2338
+ return nothing;
2339
+ }
2340
+
2341
+ private renderEventsTable() {
2342
+ const events = this.getEventsForSelectedContext();
2343
+ const filteredEvents = this.filterEvents(events);
2344
+ const selectedLabel = this.selectedContext === "all-agents" ? "all agents" : `agent ${this.selectedContext}`;
2345
+
2346
+ if (events.length === 0) {
2347
+ return html`
2348
+ <div class="flex h-full items-center justify-center px-4 py-8 text-center">
2349
+ <div class="max-w-md">
2350
+ <div class="mb-3 flex justify-center text-gray-300 [&>svg]:!h-8 [&>svg]:!w-8">
2351
+ ${this.renderIcon("Zap")}
2352
+ </div>
2353
+ <p class="text-sm text-gray-600">No events yet</p>
2354
+ <p class="mt-2 text-xs text-gray-500">Trigger an agent run to see live activity.</p>
2355
+ </div>
2356
+ </div>
2357
+ `;
2358
+ }
2359
+
2360
+ if (filteredEvents.length === 0) {
2361
+ return html`
2362
+ <div class="flex h-full items-center justify-center px-4 py-8 text-center">
2363
+ <div class="max-w-md space-y-3">
2364
+ <div class="flex justify-center text-gray-300 [&>svg]:!h-8 [&>svg]:!w-8">
2365
+ ${this.renderIcon("Filter")}
2366
+ </div>
2367
+ <p class="text-sm text-gray-600">No events match the current filters.</p>
2368
+ <div>
2369
+ <button
2370
+ type="button"
2371
+ 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"
2372
+ @click=${this.resetEventFilters}
2373
+ >
2374
+ ${this.renderIcon("RefreshCw")}
2375
+ <span>Reset filters</span>
2376
+ </button>
2377
+ </div>
2378
+ </div>
2379
+ </div>
2380
+ `;
2381
+ }
2382
+
2383
+ return html`
2384
+ <div class="flex h-full flex-col">
2385
+ <div class="flex flex-col gap-1.5 border-b border-gray-200 bg-white px-4 py-2.5">
2386
+ <div class="flex flex-wrap items-center gap-2">
2387
+ <div class="relative min-w-[200px] flex-1">
2388
+ <input
2389
+ type="search"
2390
+ 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"
2391
+ placeholder="Search agent, type, payload"
2392
+ .value=${this.eventFilterText}
2393
+ @input=${this.handleEventFilterInput}
2394
+ />
2395
+ </div>
2396
+ <select
2397
+ 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"
2398
+ .value=${this.eventTypeFilter}
2399
+ @change=${this.handleEventTypeChange}
2400
+ >
2401
+ <option value="all">All event types</option>
2402
+ ${AGENT_EVENT_TYPES.map(
2403
+ (type) =>
2404
+ html`<option value=${type}>${type.toLowerCase().replace(/_/g, " ")}</option>`,
2405
+ )}
2406
+ </select>
2407
+ <div class="flex items-center gap-1 text-[11px]">
2408
+ <button
2409
+ type="button"
2410
+ 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"
2411
+ title="Reset filters"
2412
+ data-tooltip="Reset filters"
2413
+ aria-label="Reset filters"
2414
+ @click=${this.resetEventFilters}
2415
+ ?disabled=${!this.eventFilterText && this.eventTypeFilter === "all"}
2416
+ >
2417
+ ${this.renderIcon("RotateCw")}
2418
+ </button>
2419
+ <button
2420
+ type="button"
2421
+ 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"
2422
+ title="Export JSON"
2423
+ data-tooltip="Export JSON"
2424
+ aria-label="Export JSON"
2425
+ @click=${() => this.exportEvents(filteredEvents)}
2426
+ ?disabled=${filteredEvents.length === 0}
2427
+ >
2428
+ ${this.renderIcon("Download")}
2429
+ </button>
2430
+ <button
2431
+ type="button"
2432
+ 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"
2433
+ title="Clear events"
2434
+ data-tooltip="Clear events"
2435
+ aria-label="Clear events"
2436
+ @click=${this.handleClearEvents}
2437
+ ?disabled=${events.length === 0}
2438
+ >
2439
+ ${this.renderIcon("Trash2")}
2440
+ </button>
2441
+ </div>
2442
+ </div>
2443
+ <div class="text-[11px] text-gray-500">
2444
+ Showing ${filteredEvents.length} of ${events.length}${this.selectedContext === "all-agents" ? "" : ` for ${selectedLabel}`}
2445
+ </div>
2446
+ </div>
2447
+ <div class="relative h-full w-full overflow-y-auto overflow-x-hidden">
2448
+ <table class="w-full table-fixed border-collapse text-xs box-border">
2449
+ <thead class="sticky top-0 z-10">
2450
+ <tr class="bg-white">
2451
+ <th class="border-b border-gray-200 bg-white px-3 py-2 text-left font-medium text-gray-900">
2452
+ Agent
2453
+ </th>
2454
+ <th class="border-b border-gray-200 bg-white px-3 py-2 text-left font-medium text-gray-900">
2455
+ Time
2456
+ </th>
2457
+ <th class="border-b border-gray-200 bg-white px-3 py-2 text-left font-medium text-gray-900">
2458
+ Event Type
2459
+ </th>
2460
+ <th class="border-b border-gray-200 bg-white px-3 py-2 text-left font-medium text-gray-900">
2461
+ AG-UI Event
2462
+ </th>
2463
+ </tr>
2464
+ </thead>
2465
+ <tbody>
2466
+ ${filteredEvents.map((event, index) => {
2467
+ const rowBg = index % 2 === 0 ? "bg-white" : "bg-gray-50/50";
2468
+ const badgeClasses = this.getEventBadgeClasses(event.type);
2469
+ const extractedEvent = this.extractEventFromPayload(event.payload);
2470
+ const inlineEvent = this.stringifyPayload(extractedEvent, false) || "—";
2471
+ const prettyEvent = this.stringifyPayload(extractedEvent, true) || inlineEvent;
2472
+ const isExpanded = this.expandedRows.has(event.id);
2473
+
2474
+ return html`
2475
+ <tr
2476
+ class="${rowBg} cursor-pointer transition hover:bg-blue-50/50"
2477
+ @click=${() => this.toggleRowExpansion(event.id)}
2478
+ >
2479
+ <td class="border-l border-r border-b border-gray-200 px-3 py-2">
2480
+ <span class="font-mono text-[11px] text-gray-600">${event.agentId}</span>
2481
+ </td>
2482
+ <td class="border-r border-b border-gray-200 px-3 py-2 font-mono text-[11px] text-gray-600">
2483
+ <span title=${new Date(event.timestamp).toLocaleString()}>
2484
+ ${new Date(event.timestamp).toLocaleTimeString()}
2485
+ </span>
2486
+ </td>
2487
+ <td class="border-r border-b border-gray-200 px-3 py-2">
2488
+ <span class=${badgeClasses}>${event.type}</span>
2489
+ </td>
2490
+ <td class="border-r border-b border-gray-200 px-3 py-2 font-mono text-[10px] text-gray-600 ${isExpanded ? '' : 'truncate max-w-xs'}">
2491
+ ${isExpanded
2492
+ ? html`
2493
+ <div class="group relative">
2494
+ <pre class="m-0 whitespace-pre-wrap break-words text-[10px] font-mono text-gray-600">${prettyEvent}</pre>
2495
+ <button
2496
+ class="absolute right-0 top-0 cursor-pointer rounded px-2 py-1 text-[10px] opacity-0 transition group-hover:opacity-100 ${
2497
+ this.copiedEvents.has(event.id)
2498
+ ? 'bg-green-100 text-green-700'
2499
+ : 'bg-gray-100 text-gray-600 hover:bg-gray-200 hover:text-gray-900'
2500
+ }"
2501
+ @click=${(e: Event) => {
2502
+ e.stopPropagation();
2503
+ this.copyToClipboard(prettyEvent, event.id);
2504
+ }}
2505
+ >
2506
+ ${this.copiedEvents.has(event.id)
2507
+ ? html`<span>✓ Copied</span>`
2508
+ : html`<span>Copy</span>`}
2509
+ </button>
2510
+ </div>
2511
+ `
2512
+ : inlineEvent}
2513
+ </td>
2514
+ </tr>
2515
+ `;
2516
+ })}
2517
+ </tbody>
2518
+ </table>
2519
+ </div>
2520
+ </div>
2521
+ `;
2522
+ }
2523
+
2524
+ private handleEventFilterInput(event: Event): void {
2525
+ const target = event.target as HTMLInputElement | null;
2526
+ this.eventFilterText = target?.value ?? "";
2527
+ this.requestUpdate();
2528
+ }
2529
+
2530
+ private handleEventTypeChange(event: Event): void {
2531
+ const target = event.target as HTMLSelectElement | null;
2532
+ const value = target?.value as InspectorAgentEventType | "all" | undefined;
2533
+ if (!value) {
2534
+ return;
2535
+ }
2536
+ this.eventTypeFilter = value;
2537
+ this.requestUpdate();
2538
+ }
2539
+
2540
+ private resetEventFilters(): void {
2541
+ this.eventFilterText = "";
2542
+ this.eventTypeFilter = "all";
2543
+ this.requestUpdate();
2544
+ }
2545
+
2546
+ private handleClearEvents = (): void => {
2547
+ if (this.selectedContext === "all-agents") {
2548
+ this.agentEvents.clear();
2549
+ this.flattenedEvents = [];
2550
+ } else {
2551
+ this.agentEvents.delete(this.selectedContext);
2552
+ this.flattenedEvents = this.flattenedEvents.filter((event) => event.agentId !== this.selectedContext);
2553
+ }
2554
+
2555
+ this.expandedRows.clear();
2556
+ this.copiedEvents.clear();
2557
+ this.requestUpdate();
2558
+ };
2559
+
2560
+ private exportEvents(events: InspectorEvent[]): void {
2561
+ try {
2562
+ const payload = JSON.stringify(events, null, 2);
2563
+ const blob = new Blob([payload], { type: "application/json" });
2564
+ const url = URL.createObjectURL(blob);
2565
+ const anchor = document.createElement("a");
2566
+ anchor.href = url;
2567
+ anchor.download = `copilotkit-events-${Date.now()}.json`;
2568
+ anchor.click();
2569
+ URL.revokeObjectURL(url);
2570
+ } catch (error) {
2571
+ console.error("Failed to export events", error);
2572
+ }
2573
+ }
2574
+
2575
+ private renderAgentsView() {
2576
+ // Show message if "all-agents" is selected or no agents available
2577
+ if (this.selectedContext === "all-agents") {
2578
+ return html`
2579
+ <div class="flex h-full items-center justify-center px-4 py-8 text-center">
2580
+ <div class="max-w-md">
2581
+ <div class="mb-3 flex justify-center text-gray-300 [&>svg]:!h-8 [&>svg]:!w-8">
2582
+ ${this.renderIcon("Bot")}
2583
+ </div>
2584
+ <p class="text-sm text-gray-600">No agent selected</p>
2585
+ <p class="mt-2 text-xs text-gray-500">Select an agent from the dropdown above to view details.</p>
2586
+ </div>
2587
+ </div>
2588
+ `;
2589
+ }
2590
+
2591
+ const agentId = this.selectedContext;
2592
+ const status = this.getAgentStatus(agentId);
2593
+ const stats = this.getAgentStats(agentId);
2594
+ const state = this.getLatestStateForAgent(agentId);
2595
+ const messages = this.getLatestMessagesForAgent(agentId);
2596
+
2597
+ const statusColors = {
2598
+ running: "bg-emerald-50 text-emerald-700",
2599
+ idle: "bg-gray-100 text-gray-600",
2600
+ error: "bg-rose-50 text-rose-700",
2601
+ };
2602
+
2603
+ return html`
2604
+ <div class="flex flex-col gap-4 p-4 overflow-auto">
2605
+ <!-- Agent Overview Card -->
2606
+ <div class="rounded-lg border border-gray-200 bg-white p-4">
2607
+ <div class="flex items-start justify-between mb-4">
2608
+ <div class="flex items-center gap-3">
2609
+ <div class="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-100 text-blue-600">
2610
+ ${this.renderIcon("Bot")}
2611
+ </div>
2612
+ <div>
2613
+ <h3 class="font-semibold text-sm text-gray-900">${agentId}</h3>
2614
+ <span class="inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-medium ${statusColors[status]} relative -translate-y-[2px]">
2615
+ <span class="h-1.5 w-1.5 rounded-full ${status === 'running' ? 'bg-emerald-500 animate-pulse' : status === 'error' ? 'bg-rose-500' : 'bg-gray-400'}"></span>
2616
+ ${status.charAt(0).toUpperCase() + status.slice(1)}
2617
+ </span>
2618
+ </div>
2619
+ </div>
2620
+ ${stats.lastActivity
2621
+ ? html`<span class="text-xs text-gray-500">Last activity: ${new Date(stats.lastActivity).toLocaleTimeString()}</span>`
2622
+ : nothing}
2623
+ </div>
2624
+ <div class="grid grid-cols-2 gap-4 md:grid-cols-4">
2625
+ <button
2626
+ type="button"
2627
+ class="rounded-md bg-gray-50 px-3 py-2 text-left transition hover:bg-gray-100 cursor-pointer overflow-hidden"
2628
+ @click=${() => this.handleMenuSelect("ag-ui-events")}
2629
+ title="View all events in AG-UI Events"
2630
+ >
2631
+ <div class="truncate whitespace-nowrap text-xs text-gray-600">Total Events</div>
2632
+ <div class="text-lg font-semibold text-gray-900">${stats.totalEvents}</div>
2633
+ </button>
2634
+ <div class="rounded-md bg-gray-50 px-3 py-2 overflow-hidden">
2635
+ <div class="truncate whitespace-nowrap text-xs text-gray-600">Messages</div>
2636
+ <div class="text-lg font-semibold text-gray-900">${stats.messages}</div>
2637
+ </div>
2638
+ <div class="rounded-md bg-gray-50 px-3 py-2 overflow-hidden">
2639
+ <div class="truncate whitespace-nowrap text-xs text-gray-600">Tool Calls</div>
2640
+ <div class="text-lg font-semibold text-gray-900">${stats.toolCalls}</div>
2641
+ </div>
2642
+ <div class="rounded-md bg-gray-50 px-3 py-2 overflow-hidden">
2643
+ <div class="truncate whitespace-nowrap text-xs text-gray-600">Errors</div>
2644
+ <div class="text-lg font-semibold text-gray-900">${stats.errors}</div>
2645
+ </div>
2646
+ </div>
2647
+ </div>
2648
+
2649
+ <!-- Current State Section -->
2650
+ <div class="rounded-lg border border-gray-200 bg-white">
2651
+ <div class="border-b border-gray-200 px-4 py-3">
2652
+ <h4 class="text-sm font-semibold text-gray-900">Current State</h4>
2653
+ </div>
2654
+ <div class="overflow-auto p-4">
2655
+ ${this.hasRenderableState(state)
2656
+ ? html`
2657
+ <pre class="overflow-auto rounded-md bg-gray-50 p-3 text-xs text-gray-800 max-h-64"><code>${this.formatStateForDisplay(state)}</code></pre>
2658
+ `
2659
+ : html`
2660
+ <div class="flex h-40 items-center justify-center text-xs text-gray-500">
2661
+ <div class="flex items-center gap-2 text-gray-500">
2662
+ <span class="text-lg text-gray-400">${this.renderIcon("Database")}</span>
2663
+ <span>State is empty</span>
2664
+ </div>
2665
+ </div>
2666
+ `}
2667
+ </div>
2668
+ </div>
2669
+
2670
+ <!-- Current Messages Section -->
2671
+ <div class="rounded-lg border border-gray-200 bg-white">
2672
+ <div class="border-b border-gray-200 px-4 py-3">
2673
+ <h4 class="text-sm font-semibold text-gray-900">Current Messages</h4>
2674
+ </div>
2675
+ <div class="overflow-auto">
2676
+ ${messages && messages.length > 0
2677
+ ? html`
2678
+ <table class="w-full text-xs">
2679
+ <thead class="bg-gray-50">
2680
+ <tr>
2681
+ <th class="px-4 py-2 text-left font-medium text-gray-700">Role</th>
2682
+ <th class="px-4 py-2 text-left font-medium text-gray-700">Content</th>
2683
+ </tr>
2684
+ </thead>
2685
+ <tbody class="divide-y divide-gray-200">
2686
+ ${messages.map((msg) => {
2687
+ const role = msg.role || "unknown";
2688
+ const roleColors: Record<string, string> = {
2689
+ user: "bg-blue-100 text-blue-800",
2690
+ assistant: "bg-green-100 text-green-800",
2691
+ system: "bg-gray-100 text-gray-800",
2692
+ tool: "bg-amber-100 text-amber-800",
2693
+ unknown: "bg-gray-100 text-gray-600",
2694
+ };
2695
+
2696
+ const rawContent = msg.contentText ?? "";
2697
+ const toolCalls = msg.toolCalls ?? [];
2698
+ const hasContent = rawContent.trim().length > 0;
2699
+ const contentFallback = toolCalls.length > 0 ? "Invoked tool call" : "—";
2700
+
2701
+ return html`
2702
+ <tr>
2703
+ <td class="px-4 py-2 align-top">
2704
+ <span class="inline-flex rounded px-2 py-0.5 text-[10px] font-medium ${roleColors[role] || roleColors.unknown}">
2705
+ ${role}
2706
+ </span>
2707
+ </td>
2708
+ <td class="px-4 py-2">
2709
+ ${hasContent
2710
+ ? html`<div class="max-w-2xl whitespace-pre-wrap break-words text-gray-700">${rawContent}</div>`
2711
+ : html`<div class="text-xs italic text-gray-400">${contentFallback}</div>`}
2712
+ ${role === 'assistant' && toolCalls.length > 0
2713
+ ? this.renderToolCallDetails(toolCalls)
2714
+ : nothing}
2715
+ </td>
2716
+ </tr>
2717
+ `;
2718
+ })}
2719
+ </tbody>
2720
+ </table>
2721
+ `
2722
+ : html`
2723
+ <div class="flex h-40 items-center justify-center text-xs text-gray-500">
2724
+ <div class="flex items-center gap-2 text-gray-500">
2725
+ <span class="text-lg text-gray-400">${this.renderIcon("MessageSquare")}</span>
2726
+ <span>No messages available</span>
2727
+ </div>
2728
+ </div>
2729
+ `}
2730
+ </div>
2731
+ </div>
2732
+ </div>
2733
+ `;
2734
+ }
2735
+
2736
+ private renderContextDropdown() {
2737
+ // Filter out "all-agents" when in agents view
2738
+ const filteredOptions = this.selectedMenu === "agents"
2739
+ ? this.contextOptions.filter((opt) => opt.key !== "all-agents")
2740
+ : this.contextOptions;
2741
+
2742
+ const selectedLabel = filteredOptions.find((opt) => opt.key === this.selectedContext)?.label ?? "";
2743
+
2744
+ return html`
2745
+ <div class="relative z-40 min-w-0 flex-1" data-context-dropdown-root="true">
2746
+ <button
2747
+ type="button"
2748
+ 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"
2749
+ @pointerdown=${this.handleContextDropdownToggle}
2750
+ >
2751
+ <span class="truncate flex-1 text-left">${selectedLabel}</span>
2752
+ <span class="shrink-0 text-gray-400">${this.renderIcon("ChevronDown")}</span>
2753
+ </button>
2754
+ ${this.contextMenuOpen
2755
+ ? html`
2756
+ <div
2757
+ 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"
2758
+ data-context-dropdown-root="true"
2759
+ >
2760
+ ${filteredOptions.map(
2761
+ (option) => html`
2762
+ <button
2763
+ type="button"
2764
+ 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"
2765
+ data-context-dropdown-root="true"
2766
+ @click=${() => this.handleContextOptionSelect(option.key)}
2767
+ >
2768
+ <span class="truncate ${option.key === this.selectedContext ? 'text-gray-900 font-medium' : 'text-gray-600'}">${option.label}</span>
2769
+ ${option.key === this.selectedContext
2770
+ ? html`<span class="text-gray-500">${this.renderIcon("Check")}</span>`
2771
+ : nothing}
2772
+ </button>
2773
+ `,
2774
+ )}
2775
+ </div>
2776
+ `
2777
+ : nothing}
2778
+ </div>
2779
+ `;
2780
+ }
2781
+
2782
+ private handleMenuSelect(key: MenuKey): void {
2783
+ if (!this.menuItems.some((item) => item.key === key)) {
2784
+ return;
2785
+ }
2786
+
2787
+ this.selectedMenu = key;
2788
+
2789
+ // If switching to agents view and "all-agents" is selected, switch to default or first agent
2790
+ if (key === "agents" && this.selectedContext === "all-agents") {
2791
+ const agentOptions = this.contextOptions.filter((opt) => opt.key !== "all-agents");
2792
+ if (agentOptions.length > 0) {
2793
+ // Try to find "default" agent first
2794
+ const defaultAgent = agentOptions.find((opt) => opt.key === "default");
2795
+ this.selectedContext = defaultAgent ? defaultAgent.key : agentOptions[0]!.key;
2796
+ }
2797
+ }
2798
+
2799
+ this.contextMenuOpen = false;
2800
+ this.persistState();
2801
+ this.requestUpdate();
2802
+ }
2803
+
2804
+ private handleContextDropdownToggle(event: PointerEvent): void {
2805
+ event.preventDefault();
2806
+ event.stopPropagation();
2807
+ this.contextMenuOpen = !this.contextMenuOpen;
2808
+ this.requestUpdate();
2809
+ }
2810
+
2811
+ private handleContextOptionSelect(key: string): void {
2812
+ if (!this.contextOptions.some((option) => option.key === key)) {
2813
+ return;
2814
+ }
2815
+
2816
+ if (this.selectedContext !== key) {
2817
+ this.selectedContext = key;
2818
+ this.expandedRows.clear();
2819
+ }
2820
+
2821
+ this.contextMenuOpen = false;
2822
+ this.persistState();
2823
+ this.requestUpdate();
2824
+ }
2825
+
2826
+ private renderToolsView() {
2827
+ if (!this._core) {
2828
+ return html`
2829
+ <div class="flex h-full items-center justify-center px-4 py-8 text-xs text-gray-500">
2830
+ No core instance available
2831
+ </div>
2832
+ `;
2833
+ }
2834
+
2835
+ this.refreshToolsSnapshot();
2836
+ const allTools = this.cachedTools;
2837
+
2838
+ if (allTools.length === 0) {
2839
+ return html`
2840
+ <div class="flex h-full items-center justify-center px-4 py-8 text-center">
2841
+ <div class="max-w-md">
2842
+ <div class="mb-3 flex justify-center text-gray-300 [&>svg]:!h-8 [&>svg]:!w-8">
2843
+ ${this.renderIcon("Hammer")}
2844
+ </div>
2845
+ <p class="text-sm text-gray-600">No tools available</p>
2846
+ <p class="mt-2 text-xs text-gray-500">Tools will appear here once agents are configured with tool handlers or renderers.</p>
2847
+ </div>
2848
+ </div>
2849
+ `;
2850
+ }
2851
+
2852
+ // Filter tools by selected agent
2853
+ const filteredTools = this.selectedContext === "all-agents"
2854
+ ? allTools
2855
+ : allTools.filter((tool) => !tool.agentId || tool.agentId === this.selectedContext);
2856
+
2857
+ return html`
2858
+ <div class="flex h-full flex-col overflow-hidden">
2859
+ <div class="overflow-auto p-4">
2860
+ <div class="space-y-3">
2861
+ ${filteredTools.map(tool => this.renderToolCard(tool))}
2862
+ </div>
2863
+ </div>
2864
+ </div>
2865
+ `;
2866
+ }
2867
+
2868
+ private extractToolsFromAgents(): InspectorToolDefinition[] {
2869
+ if (!this._core) {
2870
+ return [];
2871
+ }
2872
+
2873
+ const tools: InspectorToolDefinition[] = [];
2874
+
2875
+ // Start with tools registered on the core (frontend tools / HIL)
2876
+ for (const coreTool of this._core.tools ?? []) {
2877
+ tools.push({
2878
+ agentId: coreTool.agentId ?? "",
2879
+ name: coreTool.name,
2880
+ description: coreTool.description,
2881
+ parameters: coreTool.parameters,
2882
+ type: 'handler',
2883
+ });
2884
+ }
2885
+
2886
+ // Augment with agent-level tool handlers/renderers
2887
+ for (const [agentId, agent] of Object.entries(this._core.agents)) {
2888
+ if (!agent) continue;
2889
+
2890
+ // Try to extract tool handlers
2891
+ const handlers = (agent as { toolHandlers?: Record<string, unknown> }).toolHandlers;
2892
+ if (handlers && typeof handlers === 'object') {
2893
+ for (const [toolName, handler] of Object.entries(handlers)) {
2894
+ if (handler && typeof handler === 'object') {
2895
+ const handlerObj = handler as Record<string, unknown>;
2896
+ tools.push({
2897
+ agentId,
2898
+ name: toolName,
2899
+ description:
2900
+ (typeof handlerObj.description === "string" && handlerObj.description) ||
2901
+ (handlerObj.tool as { description?: string } | undefined)?.description,
2902
+ parameters:
2903
+ handlerObj.parameters ??
2904
+ (handlerObj.tool as { parameters?: unknown } | undefined)?.parameters,
2905
+ type: 'handler',
2906
+ });
2907
+ }
2908
+ }
2909
+ }
2910
+
2911
+ // Try to extract tool renderers
2912
+ const renderers = (agent as { toolRenderers?: Record<string, unknown> }).toolRenderers;
2913
+ if (renderers && typeof renderers === 'object') {
2914
+ for (const [toolName, renderer] of Object.entries(renderers)) {
2915
+ // Don't duplicate if we already have it as a handler
2916
+ if (!tools.some(t => t.agentId === agentId && t.name === toolName)) {
2917
+ if (renderer && typeof renderer === 'object') {
2918
+ const rendererObj = renderer as Record<string, unknown>;
2919
+ tools.push({
2920
+ agentId,
2921
+ name: toolName,
2922
+ description:
2923
+ (typeof rendererObj.description === "string" && rendererObj.description) ||
2924
+ (rendererObj.tool as { description?: string } | undefined)?.description,
2925
+ parameters:
2926
+ rendererObj.parameters ??
2927
+ (rendererObj.tool as { parameters?: unknown } | undefined)?.parameters,
2928
+ type: 'renderer',
2929
+ });
2930
+ }
2931
+ }
2932
+ }
2933
+ }
2934
+ }
2935
+
2936
+ return tools.sort((a, b) => {
2937
+ const agentCompare = a.agentId.localeCompare(b.agentId);
2938
+ if (agentCompare !== 0) return agentCompare;
2939
+ return a.name.localeCompare(b.name);
2940
+ });
2941
+ }
2942
+
2943
+ private renderToolCard(tool: InspectorToolDefinition) {
2944
+ const isExpanded = this.expandedTools.has(`${tool.agentId}:${tool.name}`);
2945
+ const schema = this.extractSchemaInfo(tool.parameters);
2946
+
2947
+ const typeColors = {
2948
+ handler: "bg-blue-50 text-blue-700 border-blue-200",
2949
+ renderer: "bg-purple-50 text-purple-700 border-purple-200",
2950
+ };
2951
+
2952
+ return html`
2953
+ <div class="rounded-lg border border-gray-200 bg-white overflow-hidden">
2954
+ <button
2955
+ type="button"
2956
+ class="w-full px-4 py-3 text-left transition hover:bg-gray-50"
2957
+ @click=${() => this.toggleToolExpansion(`${tool.agentId}:${tool.name}`)}
2958
+ >
2959
+ <div class="flex items-start justify-between gap-3">
2960
+ <div class="flex-1 min-w-0">
2961
+ <div class="flex items-center gap-2 mb-1">
2962
+ <span class="font-mono text-sm font-semibold text-gray-900">${tool.name}</span>
2963
+ <span class="inline-flex items-center rounded-sm border px-1.5 py-0.5 text-[10px] font-medium ${typeColors[tool.type]}">
2964
+ ${tool.type}
2965
+ </span>
2966
+ </div>
2967
+ <div class="flex items-center gap-2 text-xs text-gray-500">
2968
+ <span class="flex items-center gap-1">
2969
+ ${this.renderIcon("Bot")}
2970
+ <span class="font-mono">${tool.agentId}</span>
2971
+ </span>
2972
+ ${schema.properties.length > 0
2973
+ ? html`
2974
+ <span class="text-gray-300">•</span>
2975
+ <span>${schema.properties.length} parameter${schema.properties.length !== 1 ? 's' : ''}</span>
2976
+ `
2977
+ : nothing}
2978
+ </div>
2979
+ ${tool.description
2980
+ ? html`<p class="mt-2 text-xs text-gray-600">${tool.description}</p>`
2981
+ : nothing}
2982
+ </div>
2983
+ <span class="shrink-0 text-gray-400 transition ${isExpanded ? 'rotate-180' : ''}">
2984
+ ${this.renderIcon("ChevronDown")}
2985
+ </span>
2986
+ </div>
2987
+ </button>
2988
+
2989
+ ${isExpanded
2990
+ ? html`
2991
+ <div class="border-t border-gray-200 bg-gray-50/50 px-4 py-3">
2992
+ ${schema.properties.length > 0
2993
+ ? html`
2994
+ <h5 class="mb-3 text-xs font-semibold text-gray-700">Parameters</h5>
2995
+ <div class="space-y-3">
2996
+ ${schema.properties.map(prop => html`
2997
+ <div class="rounded-md border border-gray-200 bg-white p-3">
2998
+ <div class="flex items-start justify-between gap-2 mb-1">
2999
+ <span class="font-mono text-xs font-medium text-gray-900">${prop.name}</span>
3000
+ <div class="flex items-center gap-1.5 shrink-0">
3001
+ ${prop.required
3002
+ ? html`<span class="text-[9px] rounded border border-rose-200 bg-rose-50 px-1 py-0.5 font-medium text-rose-700">required</span>`
3003
+ : html`<span class="text-[9px] rounded border border-gray-200 bg-gray-50 px-1 py-0.5 font-medium text-gray-600">optional</span>`}
3004
+ ${prop.type
3005
+ ? html`<span class="text-[9px] rounded border border-gray-200 bg-gray-50 px-1 py-0.5 font-mono text-gray-600">${prop.type}</span>`
3006
+ : nothing}
3007
+ </div>
3008
+ </div>
3009
+ ${prop.description
3010
+ ? html`<p class="mt-1 text-xs text-gray-600">${prop.description}</p>`
3011
+ : nothing}
3012
+ ${prop.defaultValue !== undefined
3013
+ ? html`
3014
+ <div class="mt-2 flex items-center gap-1.5 text-[10px] text-gray-500">
3015
+ <span>Default:</span>
3016
+ <code class="rounded bg-gray-100 px-1 py-0.5 font-mono">${JSON.stringify(prop.defaultValue)}</code>
3017
+ </div>
3018
+ `
3019
+ : nothing}
3020
+ ${prop.enum && prop.enum.length > 0
3021
+ ? html`
3022
+ <div class="mt-2">
3023
+ <span class="text-[10px] text-gray-500">Allowed values:</span>
3024
+ <div class="mt-1 flex flex-wrap gap-1">
3025
+ ${prop.enum.map(val => html`
3026
+ <code class="rounded border border-gray-200 bg-gray-50 px-1.5 py-0.5 text-[10px] font-mono text-gray-700">${JSON.stringify(val)}</code>
3027
+ `)}
3028
+ </div>
3029
+ </div>
3030
+ `
3031
+ : nothing}
3032
+ </div>
3033
+ `)}
3034
+ </div>
3035
+ `
3036
+ : html`
3037
+ <div class="flex items-center justify-center py-4 text-xs text-gray-500">
3038
+ <span>No parameters defined</span>
3039
+ </div>
3040
+ `}
3041
+ </div>
3042
+ `
3043
+ : nothing}
3044
+ </div>
3045
+ `;
3046
+ }
3047
+
3048
+ private extractSchemaInfo(parameters: unknown): {
3049
+ properties: Array<{
3050
+ name: string;
3051
+ type?: string;
3052
+ description?: string;
3053
+ required: boolean;
3054
+ defaultValue?: unknown;
3055
+ enum?: unknown[];
3056
+ }>;
3057
+ } {
3058
+ const result: {
3059
+ properties: Array<{
3060
+ name: string;
3061
+ type?: string;
3062
+ description?: string;
3063
+ required: boolean;
3064
+ defaultValue?: unknown;
3065
+ enum?: unknown[];
3066
+ }>;
3067
+ } = { properties: [] };
3068
+
3069
+ if (!parameters || typeof parameters !== 'object') {
3070
+ return result;
3071
+ }
3072
+
3073
+ // Try Zod schema introspection
3074
+ const zodDef = (parameters as { _def?: Record<string, unknown> })._def;
3075
+ if (zodDef && typeof zodDef === "object") {
3076
+ // Handle Zod object schema
3077
+ if (zodDef.typeName === 'ZodObject') {
3078
+ const rawShape = zodDef.shape;
3079
+ const shape =
3080
+ typeof rawShape === "function"
3081
+ ? (rawShape as () => Record<string, unknown>)()
3082
+ : (rawShape as Record<string, unknown> | undefined);
3083
+
3084
+ if (!shape || typeof shape !== "object") {
3085
+ return result;
3086
+ }
3087
+ const requiredKeys = new Set<string>();
3088
+
3089
+ // Get required fields
3090
+ if (zodDef.unknownKeys === 'strict' || !zodDef.catchall) {
3091
+ Object.keys(shape || {}).forEach((key) => {
3092
+ const candidate = (shape as Record<string, unknown>)[key];
3093
+ const fieldDef = (candidate as { _def?: Record<string, unknown> } | undefined)?._def;
3094
+ if (fieldDef && !this.isZodOptional(candidate)) {
3095
+ requiredKeys.add(key);
3096
+ }
3097
+ });
3098
+ }
3099
+
3100
+ // Extract properties
3101
+ for (const [key, value] of Object.entries(shape || {})) {
3102
+ const fieldInfo = this.extractZodFieldInfo(value);
3103
+ result.properties.push({
3104
+ name: key,
3105
+ type: fieldInfo.type,
3106
+ description: fieldInfo.description,
3107
+ required: requiredKeys.has(key),
3108
+ defaultValue: fieldInfo.defaultValue,
3109
+ enum: fieldInfo.enum,
3110
+ });
3111
+ }
3112
+ }
3113
+ } else if (
3114
+ (parameters as { type?: string; properties?: Record<string, unknown> }).type === 'object' &&
3115
+ (parameters as { properties?: Record<string, unknown> }).properties
3116
+ ) {
3117
+ // Handle JSON Schema format
3118
+ const props = (parameters as { properties?: Record<string, unknown> }).properties;
3119
+ const required = new Set(
3120
+ Array.isArray((parameters as { required?: string[] }).required)
3121
+ ? (parameters as { required?: string[] }).required
3122
+ : [],
3123
+ );
3124
+
3125
+ for (const [key, value] of Object.entries(props ?? {})) {
3126
+ const prop = value as Record<string, unknown>;
3127
+ result.properties.push({
3128
+ name: key,
3129
+ type: prop.type as string | undefined,
3130
+ description: typeof prop.description === "string" ? prop.description : undefined,
3131
+ required: required.has(key),
3132
+ defaultValue: prop.default,
3133
+ enum: Array.isArray(prop.enum) ? prop.enum : undefined,
3134
+ });
3135
+ }
3136
+ }
3137
+
3138
+ return result;
3139
+ }
3140
+
3141
+ private isZodOptional(zodSchema: unknown): boolean {
3142
+ const schema = zodSchema as { _def?: Record<string, unknown> };
3143
+ if (!schema?._def) return false;
3144
+
3145
+ const def = schema._def;
3146
+
3147
+ // Check if it's explicitly optional or nullable
3148
+ if (def.typeName === 'ZodOptional' || def.typeName === 'ZodNullable') {
3149
+ return true;
3150
+ }
3151
+
3152
+ // Check if it has a default value
3153
+ if (def.defaultValue !== undefined) {
3154
+ return true;
3155
+ }
3156
+
3157
+ return false;
3158
+ }
3159
+
3160
+ private extractZodFieldInfo(zodSchema: unknown): {
3161
+ type?: string;
3162
+ description?: string;
3163
+ defaultValue?: unknown;
3164
+ enum?: unknown[];
3165
+ } {
3166
+ const info: {
3167
+ type?: string;
3168
+ description?: string;
3169
+ defaultValue?: unknown;
3170
+ enum?: unknown[];
3171
+ } = {};
3172
+
3173
+ const schema = zodSchema as { _def?: Record<string, unknown> };
3174
+ if (!schema?._def) return info;
3175
+
3176
+ let currentSchema = schema as { _def?: Record<string, unknown> };
3177
+ let def = currentSchema._def as Record<string, unknown>;
3178
+
3179
+ // Unwrap optional/nullable
3180
+ while (def.typeName === 'ZodOptional' || def.typeName === 'ZodNullable' || def.typeName === 'ZodDefault') {
3181
+ if (def.typeName === 'ZodDefault' && def.defaultValue !== undefined) {
3182
+ info.defaultValue = typeof def.defaultValue === 'function' ? def.defaultValue() : def.defaultValue;
3183
+ }
3184
+ currentSchema = (def.innerType as { _def?: Record<string, unknown> }) ?? currentSchema;
3185
+ if (!currentSchema?._def) break;
3186
+ def = currentSchema._def as Record<string, unknown>;
3187
+ }
3188
+
3189
+ // Extract description
3190
+ info.description = typeof def.description === "string" ? def.description : undefined;
3191
+
3192
+ const typeName = typeof def.typeName === "string" ? def.typeName : undefined;
3193
+
3194
+ // Extract type
3195
+ const typeMap: Record<string, string> = {
3196
+ ZodString: 'string',
3197
+ ZodNumber: 'number',
3198
+ ZodBoolean: 'boolean',
3199
+ ZodArray: 'array',
3200
+ ZodObject: 'object',
3201
+ ZodEnum: 'enum',
3202
+ ZodLiteral: 'literal',
3203
+ ZodUnion: 'union',
3204
+ ZodAny: 'any',
3205
+ ZodUnknown: 'unknown',
3206
+ };
3207
+ info.type = typeName ? typeMap[typeName] || typeName.replace('Zod', '').toLowerCase() : undefined;
3208
+
3209
+ // Extract enum values
3210
+ if (typeName === 'ZodEnum' && Array.isArray(def.values)) {
3211
+ info.enum = def.values as unknown[];
3212
+ } else if (typeName === 'ZodLiteral' && def.value !== undefined) {
3213
+ info.enum = [def.value];
3214
+ }
3215
+
3216
+ return info;
3217
+ }
3218
+
3219
+ private toggleToolExpansion(toolId: string): void {
3220
+ if (this.expandedTools.has(toolId)) {
3221
+ this.expandedTools.delete(toolId);
3222
+ } else {
3223
+ this.expandedTools.add(toolId);
3224
+ }
3225
+ this.requestUpdate();
3226
+ }
3227
+
3228
+ private renderContextView() {
3229
+ const contextEntries = Object.entries(this.contextStore);
3230
+
3231
+ if (contextEntries.length === 0) {
3232
+ return html`
3233
+ <div class="flex h-full items-center justify-center px-4 py-8 text-center">
3234
+ <div class="max-w-md">
3235
+ <div class="mb-3 flex justify-center text-gray-300 [&>svg]:!h-8 [&>svg]:!w-8">
3236
+ ${this.renderIcon("FileText")}
3237
+ </div>
3238
+ <p class="text-sm text-gray-600">No context available</p>
3239
+ <p class="mt-2 text-xs text-gray-500">Context will appear here once added to CopilotKit.</p>
3240
+ </div>
3241
+ </div>
3242
+ `;
3243
+ }
3244
+
3245
+ return html`
3246
+ <div class="flex h-full flex-col overflow-hidden">
3247
+ <div class="overflow-auto p-4">
3248
+ <div class="space-y-3">
3249
+ ${contextEntries.map(([id, context]) => this.renderContextCard(id, context))}
3250
+ </div>
3251
+ </div>
3252
+ </div>
3253
+ `;
3254
+ }
3255
+
3256
+ private renderContextCard(id: string, context: { description?: string; value: unknown }) {
3257
+ const isExpanded = this.expandedContextItems.has(id);
3258
+ const valuePreview = this.getContextValuePreview(context.value);
3259
+ const hasValue = context.value !== undefined && context.value !== null;
3260
+ const title = context.description?.trim() || id;
3261
+
3262
+ return html`
3263
+ <div class="rounded-lg border border-gray-200 bg-white overflow-hidden">
3264
+ <button
3265
+ type="button"
3266
+ class="w-full px-4 py-3 text-left transition hover:bg-gray-50"
3267
+ @click=${() => this.toggleContextExpansion(id)}
3268
+ >
3269
+ <div class="flex items-start justify-between gap-3">
3270
+ <div class="flex-1 min-w-0">
3271
+ <p class="text-sm font-medium text-gray-900 mb-1">${title}</p>
3272
+ <div class="flex items-center gap-2 text-xs text-gray-500">
3273
+ <span class="font-mono truncate inline-block align-middle" style="max-width: 180px;">${id}</span>
3274
+ ${hasValue
3275
+ ? html`
3276
+ <span class="text-gray-300">•</span>
3277
+ <span class="truncate">${valuePreview}</span>
3278
+ `
3279
+ : nothing}
3280
+ </div>
3281
+ </div>
3282
+ <span class="shrink-0 text-gray-400 transition ${isExpanded ? 'rotate-180' : ''}">
3283
+ ${this.renderIcon("ChevronDown")}
3284
+ </span>
3285
+ </div>
3286
+ </button>
3287
+
3288
+ ${isExpanded
3289
+ ? html`
3290
+ <div class="border-t border-gray-200 bg-gray-50/50 px-4 py-3">
3291
+ <div class="mb-3">
3292
+ <h5 class="mb-1 text-xs font-semibold text-gray-700">ID</h5>
3293
+ <code class="block rounded bg-white border border-gray-200 px-2 py-1 text-[10px] font-mono text-gray-600">${id}</code>
3294
+ </div>
3295
+ ${hasValue
3296
+ ? html`
3297
+ <div class="mb-2 flex items-center justify-between gap-2">
3298
+ <h5 class="text-xs font-semibold text-gray-700">Value</h5>
3299
+ <button
3300
+ 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"
3301
+ type="button"
3302
+ @click=${(e: Event) => {
3303
+ e.stopPropagation();
3304
+ void this.copyContextValue(context.value, id);
3305
+ }}
3306
+ >
3307
+ ${this.copiedContextItems.has(id) ? "Copied" : "Copy JSON"}
3308
+ </button>
3309
+ </div>
3310
+ <div class="rounded-md border border-gray-200 bg-white p-3">
3311
+ <pre class="overflow-auto text-xs text-gray-800 max-h-96"><code>${this.formatContextValue(context.value)}</code></pre>
3312
+ </div>
3313
+ `
3314
+ : html`
3315
+ <div class="flex items-center justify-center py-4 text-xs text-gray-500">
3316
+ <span>No value available</span>
3317
+ </div>
3318
+ `}
3319
+ </div>
3320
+ `
3321
+ : nothing}
3322
+ </div>
3323
+ `;
3324
+ }
3325
+
3326
+ private getContextValuePreview(value: unknown): string {
3327
+ if (value === undefined || value === null) {
3328
+ return '—';
3329
+ }
3330
+
3331
+ if (typeof value === 'string') {
3332
+ return value.length > 50 ? `${value.substring(0, 50)}...` : value;
3333
+ }
3334
+
3335
+ if (typeof value === 'number' || typeof value === 'boolean') {
3336
+ return String(value);
3337
+ }
3338
+
3339
+ if (Array.isArray(value)) {
3340
+ return `Array(${value.length})`;
3341
+ }
3342
+
3343
+ if (typeof value === 'object') {
3344
+ const keys = Object.keys(value);
3345
+ return `Object with ${keys.length} key${keys.length !== 1 ? 's' : ''}`;
3346
+ }
3347
+
3348
+ if (typeof value === 'function') {
3349
+ return 'Function';
3350
+ }
3351
+
3352
+ return String(value);
3353
+ }
3354
+
3355
+ private formatContextValue(value: unknown): string {
3356
+ if (value === undefined) {
3357
+ return 'undefined';
3358
+ }
3359
+
3360
+ if (value === null) {
3361
+ return 'null';
3362
+ }
3363
+
3364
+ if (typeof value === 'function') {
3365
+ return value.toString();
3366
+ }
3367
+
3368
+ try {
3369
+ return JSON.stringify(value, null, 2);
3370
+ } catch {
3371
+ return String(value);
3372
+ }
3373
+ }
3374
+
3375
+ private async copyContextValue(value: unknown, contextId: string): Promise<void> {
3376
+ if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) {
3377
+ console.warn("Clipboard API is not available in this environment.");
3378
+ return;
3379
+ }
3380
+
3381
+ const serialized = this.formatContextValue(value);
3382
+ try {
3383
+ await navigator.clipboard.writeText(serialized);
3384
+ this.copiedContextItems.add(contextId);
3385
+ this.requestUpdate();
3386
+ setTimeout(() => {
3387
+ this.copiedContextItems.delete(contextId);
3388
+ this.requestUpdate();
3389
+ }, 1500);
3390
+ } catch (error) {
3391
+ console.error("Failed to copy context value:", error);
3392
+ }
3393
+ }
3394
+
3395
+ private toggleContextExpansion(contextId: string): void {
3396
+ if (this.expandedContextItems.has(contextId)) {
3397
+ this.expandedContextItems.delete(contextId);
3398
+ } else {
3399
+ this.expandedContextItems.add(contextId);
3400
+ }
3401
+ this.requestUpdate();
3402
+ }
3403
+
3404
+ private handleGlobalPointerDown = (event: PointerEvent): void => {
3405
+ if (!this.contextMenuOpen) {
3406
+ return;
3407
+ }
3408
+
3409
+ const clickedDropdown = event.composedPath().some((node) => {
3410
+ return node instanceof HTMLElement && node.dataset?.contextDropdownRoot === "true";
3411
+ });
3412
+
3413
+ if (!clickedDropdown) {
3414
+ this.contextMenuOpen = false;
3415
+ this.requestUpdate();
3416
+ }
3417
+ };
3418
+
3419
+ private toggleRowExpansion(eventId: string): void {
3420
+ // Don't toggle if user is selecting text
3421
+ const selection = window.getSelection();
3422
+ if (selection && selection.toString().length > 0) {
3423
+ return;
3424
+ }
3425
+
3426
+ if (this.expandedRows.has(eventId)) {
3427
+ this.expandedRows.delete(eventId);
3428
+ } else {
3429
+ this.expandedRows.add(eventId);
3430
+ }
3431
+ this.requestUpdate();
3432
+ }
3433
+
3434
+ private renderAnnouncementPanel() {
3435
+ if (!this.isOpen) {
3436
+ return nothing;
3437
+ }
3438
+
3439
+ // Ensure loading is triggered even if we mounted in an already-open state
3440
+ this.ensureAnnouncementLoading();
3441
+
3442
+ if (!this.hasUnseenAnnouncement) {
3443
+ return nothing;
3444
+ }
3445
+
3446
+ if (!this.announcementLoaded && !this.announcementMarkdown) {
3447
+ return html`<div 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)]">
3448
+ <div class="flex items-center gap-2 font-semibold">
3449
+ <span class="inline-flex h-6 w-6 items-center justify-center rounded-md bg-slate-900 text-white shadow-sm">
3450
+ ${this.renderIcon("Megaphone")}
3451
+ </span>
3452
+ <span>Loading latest announcement…</span>
3453
+ </div>
3454
+ </div>`;
3455
+ }
3456
+
3457
+ if (this.announcementLoadError) {
3458
+ return html`<div 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)]">
3459
+ <div class="flex items-center gap-2 font-semibold">
3460
+ <span class="inline-flex h-6 w-6 items-center justify-center rounded-md bg-rose-600 text-white shadow-sm">
3461
+ ${this.renderIcon("Megaphone")}
3462
+ </span>
3463
+ <span>Announcement unavailable</span>
3464
+ </div>
3465
+ <p class="mt-2 text-xs text-rose-800">We couldn’t load the latest notice. Please try opening the inspector again.</p>
3466
+ </div>`;
3467
+ }
3468
+
3469
+ if (!this.announcementMarkdown) {
3470
+ return nothing;
3471
+ }
3472
+
3473
+ const content = this.announcementHtml
3474
+ ? unsafeHTML(this.announcementHtml)
3475
+ : html`<pre class="whitespace-pre-wrap text-sm text-gray-900">${this.announcementMarkdown}</pre>`;
3476
+
3477
+ return html`<div 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)]">
3478
+ <div class="mb-3 flex items-center gap-2 text-sm font-semibold text-slate-900">
3479
+ <span class="inline-flex h-7 w-7 items-center justify-center rounded-md bg-slate-900 text-white shadow-sm">
3480
+ ${this.renderIcon("Megaphone")}
3481
+ </span>
3482
+ <span>Announcement</span>
3483
+ <button class="announcement-dismiss ml-auto" type="button" @click=${this.handleDismissAnnouncement} aria-label="Dismiss announcement">
3484
+ Dismiss
3485
+ </button>
3486
+ </div>
3487
+ <div class="announcement-content text-sm leading-relaxed text-gray-900">${content}</div>
3488
+ </div>`;
3489
+ }
3490
+
3491
+ private ensureAnnouncementLoading(): void {
3492
+ if (this.announcementPromise || typeof window === "undefined" || typeof fetch === "undefined") {
3493
+ return;
3494
+ }
3495
+ this.announcementPromise = this.fetchAnnouncement();
3496
+ }
3497
+
3498
+ private renderAnnouncementPreview() {
3499
+ if (!this.hasUnseenAnnouncement || !this.showAnnouncementPreview || !this.announcementPreviewText) {
3500
+ return nothing;
3501
+ }
3502
+
3503
+ const side = this.contextState.button.anchor.horizontal === "left" ? "right" : "left";
3504
+
3505
+ return html`<div
3506
+ class="announcement-preview"
3507
+ data-side=${side}
3508
+ role="note"
3509
+ @click=${() => this.handleAnnouncementPreviewClick()}
3510
+ >
3511
+ <span>${this.announcementPreviewText}</span>
3512
+ <span class="announcement-preview__arrow"></span>
3513
+ </div>`;
3514
+ }
3515
+
3516
+ private handleAnnouncementPreviewClick(): void {
3517
+ this.showAnnouncementPreview = false;
3518
+ this.openInspector();
3519
+ }
3520
+
3521
+ private handleDismissAnnouncement = (): void => {
3522
+ this.markAnnouncementSeen();
3523
+ };
3524
+
3525
+ private async fetchAnnouncement(): Promise<void> {
3526
+ try {
3527
+ const response = await fetch(ANNOUNCEMENT_URL, { cache: "no-cache" });
3528
+ if (!response.ok) {
3529
+ throw new Error(`Failed to load announcement (${response.status})`);
3530
+ }
3531
+
3532
+ const data = (await response.json()) as {
3533
+ timestamp?: unknown;
3534
+ previewText?: unknown;
3535
+ announcement?: unknown;
3536
+ };
3537
+
3538
+ const timestamp = typeof data?.timestamp === "string" ? data.timestamp : null;
3539
+ const previewText = typeof data?.previewText === "string" ? data.previewText : null;
3540
+ const markdown = typeof data?.announcement === "string" ? data.announcement : null;
3541
+
3542
+ if (!timestamp || !markdown) {
3543
+ throw new Error("Malformed announcement payload");
3544
+ }
3545
+
3546
+ const storedTimestamp = this.loadStoredAnnouncementTimestamp();
3547
+
3548
+ this.announcementTimestamp = timestamp;
3549
+ this.announcementPreviewText = previewText ?? "";
3550
+ this.announcementMarkdown = markdown;
3551
+ this.hasUnseenAnnouncement = (!storedTimestamp || storedTimestamp !== timestamp) && !!this.announcementPreviewText;
3552
+ this.showAnnouncementPreview = this.hasUnseenAnnouncement;
3553
+ this.announcementHtml = await this.convertMarkdownToHtml(markdown);
3554
+ this.announcementLoaded = true;
3555
+
3556
+ this.requestUpdate();
3557
+ } catch (error) {
3558
+ this.announcementLoadError = error;
3559
+ this.announcementLoaded = true;
3560
+ this.requestUpdate();
3561
+ }
3562
+ }
3563
+
3564
+ private async convertMarkdownToHtml(markdown: string): Promise<string | null> {
3565
+ const renderer = new marked.Renderer();
3566
+ renderer.link = (href, title, text) => {
3567
+ const safeHref = this.escapeHtmlAttr(this.appendRefParam(href ?? ""));
3568
+ const titleAttr = title ? ` title="${this.escapeHtmlAttr(title)}"` : "";
3569
+ return `<a href="${safeHref}" target="_blank" rel="noopener"${titleAttr}>${text}</a>`;
3570
+ };
3571
+ return marked.parse(markdown, { renderer });
3572
+ }
3573
+
3574
+ private appendRefParam(href: string): string {
3575
+ try {
3576
+ const url = new URL(href, typeof window !== "undefined" ? window.location.href : "https://copilotkit.ai");
3577
+ if (!url.searchParams.has("ref")) {
3578
+ url.searchParams.append("ref", "cpk-inspector");
3579
+ }
3580
+ return url.toString();
3581
+ } catch {
3582
+ return href;
3583
+ }
3584
+ }
3585
+
3586
+ private escapeHtmlAttr(value: string): string {
3587
+ return value
3588
+ .replace(/&/g, "&amp;")
3589
+ .replace(/</g, "&lt;")
3590
+ .replace(/>/g, "&gt;")
3591
+ .replace(/\"/g, "&quot;")
3592
+ .replace(/'/g, "&#39;");
3593
+ }
3594
+
3595
+ private loadStoredAnnouncementTimestamp(): string | null {
3596
+ if (typeof window === "undefined" || !window.localStorage) {
3597
+ return null;
3598
+ }
3599
+ try {
3600
+ const raw = window.localStorage.getItem(ANNOUNCEMENT_STORAGE_KEY);
3601
+ if (!raw) {
3602
+ return null;
3603
+ }
3604
+ const parsed = JSON.parse(raw);
3605
+ if (parsed && typeof parsed.timestamp === "string") {
3606
+ return parsed.timestamp;
3607
+ }
3608
+ // Backward compatibility: previous shape { hash }
3609
+ return null;
3610
+ } catch {
3611
+ // ignore malformed storage
3612
+ }
3613
+ return null;
3614
+ }
3615
+
3616
+ private persistAnnouncementTimestamp(timestamp: string): void {
3617
+ if (typeof window === "undefined" || !window.localStorage) {
3618
+ return;
3619
+ }
3620
+ try {
3621
+ const payload = JSON.stringify({ timestamp });
3622
+ window.localStorage.setItem(ANNOUNCEMENT_STORAGE_KEY, payload);
3623
+ } catch {
3624
+ // Non-fatal if storage is unavailable
3625
+ }
3626
+ }
3627
+
3628
+ private markAnnouncementSeen(): void {
3629
+ // Clear badge only when explicitly dismissed
3630
+ this.hasUnseenAnnouncement = false;
3631
+ this.showAnnouncementPreview = false;
3632
+
3633
+ if (!this.announcementTimestamp) {
3634
+ // If still loading, attempt once more after promise resolves; avoid infinite requeues
3635
+ if (this.announcementPromise && !this.announcementLoaded) {
3636
+ void this.announcementPromise.then(() => this.markAnnouncementSeen()).catch(() => undefined);
3637
+ }
3638
+ this.requestUpdate();
3639
+ return;
3640
+ }
3641
+
3642
+ this.persistAnnouncementTimestamp(this.announcementTimestamp);
3643
+ this.requestUpdate();
3644
+ }
3645
+ }
3646
+
3647
+ export function defineWebInspector(): void {
3648
+ if (!customElements.get(WEB_INSPECTOR_TAG)) {
3649
+ customElements.define(WEB_INSPECTOR_TAG, WebInspectorElement);
3650
+ }
3651
+ }
3652
+
3653
+ defineWebInspector();
3654
+
3655
+ declare global {
3656
+ interface HTMLElementTagNameMap {
3657
+ "cpk-web-inspector": WebInspectorElement;
3658
+ }
3659
+ }