@copilotkit/web-inspector 1.55.0-next.7

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