@iwsdk/vite-plugin-dev 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,15 +1,887 @@
1
- import { spawn, execFile } from 'child_process';
2
1
  import { randomUUID } from 'crypto';
3
2
  import * as fs from 'fs';
4
- import { existsSync, readFileSync } from 'fs';
5
- import { readFile, mkdir, writeFile, unlink } from 'fs/promises';
3
+ import { realpathSync, existsSync, readFileSync } from 'fs';
6
4
  import * as path from 'path';
7
- import { WebSocketServer } from 'ws';
5
+ import path__default from 'path';
6
+ import { WebSocketServer, WebSocket } from 'ws';
7
+ import { spawn } from 'child_process';
8
8
  import * as os from 'os';
9
9
  import { chromium } from 'playwright';
10
10
  import sharp from 'sharp';
11
+ import { readFile, rm, mkdir, writeFile, rename } from 'fs/promises';
11
12
  import { fileURLToPath } from 'url';
12
13
 
14
+ /**
15
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
16
+ *
17
+ * This source code is licensed under the MIT license found in the
18
+ * LICENSE file in the root directory of this source tree.
19
+ */
20
+ const IWSDK_RUNTIME_SESSION_PATH = '.iwsdk/runtime/session.json';
21
+ const IWSDK_RUNTIME_STATE_SCHEMA_VERSION = 2;
22
+ const INTERNAL_BROWSER_PROBE_METHOD = '__iwsdk_browser_probe';
23
+ const RUNTIME_MCP_TOOLS = [
24
+ // =============================================================================
25
+ // Session Management
26
+ // =============================================================================
27
+ {
28
+ name: 'xr_get_session_status',
29
+ description: 'Get XR session and device status',
30
+ inputSchema: {
31
+ type: 'object',
32
+ properties: {},
33
+ required: [],
34
+ },
35
+ },
36
+ {
37
+ name: 'xr_accept_session',
38
+ description: 'Accept an offered XR session (equivalent to clicking "Enter XR" button)',
39
+ inputSchema: {
40
+ type: 'object',
41
+ properties: {},
42
+ required: [],
43
+ },
44
+ },
45
+ {
46
+ name: 'xr_end_session',
47
+ description: 'End the current active XR session',
48
+ inputSchema: {
49
+ type: 'object',
50
+ properties: {},
51
+ required: [],
52
+ },
53
+ },
54
+ // =============================================================================
55
+ // Transform Control
56
+ // =============================================================================
57
+ {
58
+ name: 'xr_get_transform',
59
+ description: 'Get position and orientation of a tracked device',
60
+ inputSchema: {
61
+ type: 'object',
62
+ properties: {
63
+ device: {
64
+ type: 'string',
65
+ enum: [
66
+ 'headset',
67
+ 'controller-left',
68
+ 'controller-right',
69
+ 'hand-left',
70
+ 'hand-right',
71
+ ],
72
+ description: 'The device to query',
73
+ },
74
+ },
75
+ required: ['device'],
76
+ },
77
+ },
78
+ {
79
+ name: 'xr_set_transform',
80
+ description: 'Set position and/or orientation of a tracked device. Position is in meters, orientation can be quaternion or euler angles (degrees).',
81
+ inputSchema: {
82
+ type: 'object',
83
+ properties: {
84
+ device: {
85
+ type: 'string',
86
+ enum: [
87
+ 'headset',
88
+ 'controller-left',
89
+ 'controller-right',
90
+ 'hand-left',
91
+ 'hand-right',
92
+ ],
93
+ description: 'The device to move',
94
+ },
95
+ position: {
96
+ type: 'object',
97
+ description: 'World position in meters',
98
+ properties: {
99
+ x: { type: 'number', description: 'X position (left/right)' },
100
+ y: {
101
+ type: 'number',
102
+ description: 'Y position (up/down, 1.6 is standing height)',
103
+ },
104
+ z: {
105
+ type: 'number',
106
+ description: 'Z position (forward/back, negative is forward)',
107
+ },
108
+ },
109
+ },
110
+ orientation: {
111
+ type: 'object',
112
+ description: 'Rotation as quaternion {x,y,z,w} or euler angles {pitch,yaw,roll} in degrees',
113
+ properties: {
114
+ x: { type: 'number', description: 'Quaternion X component' },
115
+ y: { type: 'number', description: 'Quaternion Y component' },
116
+ z: { type: 'number', description: 'Quaternion Z component' },
117
+ w: { type: 'number', description: 'Quaternion W component' },
118
+ pitch: {
119
+ type: 'number',
120
+ description: 'Pitch in degrees (X rotation)',
121
+ },
122
+ yaw: { type: 'number', description: 'Yaw in degrees (Y rotation)' },
123
+ roll: {
124
+ type: 'number',
125
+ description: 'Roll in degrees (Z rotation)',
126
+ },
127
+ },
128
+ },
129
+ },
130
+ required: ['device'],
131
+ },
132
+ },
133
+ {
134
+ name: 'xr_look_at',
135
+ description: 'Orient a device to look at a specific world position',
136
+ inputSchema: {
137
+ type: 'object',
138
+ properties: {
139
+ device: {
140
+ type: 'string',
141
+ enum: [
142
+ 'headset',
143
+ 'controller-left',
144
+ 'controller-right',
145
+ 'hand-left',
146
+ 'hand-right',
147
+ ],
148
+ description: 'The device to orient',
149
+ },
150
+ target: {
151
+ type: 'object',
152
+ description: 'World position to look at',
153
+ properties: {
154
+ x: { type: 'number' },
155
+ y: { type: 'number' },
156
+ z: { type: 'number' },
157
+ },
158
+ required: ['x', 'y', 'z'],
159
+ },
160
+ moveToDistance: {
161
+ type: 'number',
162
+ description: 'Optional: move device to this distance from target',
163
+ },
164
+ },
165
+ required: ['device', 'target'],
166
+ },
167
+ },
168
+ {
169
+ name: 'xr_animate_to',
170
+ description: 'Smoothly animate a device to a new position/orientation over time',
171
+ inputSchema: {
172
+ type: 'object',
173
+ properties: {
174
+ device: {
175
+ type: 'string',
176
+ enum: [
177
+ 'headset',
178
+ 'controller-left',
179
+ 'controller-right',
180
+ 'hand-left',
181
+ 'hand-right',
182
+ ],
183
+ description: 'The device to animate',
184
+ },
185
+ position: {
186
+ type: 'object',
187
+ description: 'Target world position in meters',
188
+ properties: {
189
+ x: { type: 'number' },
190
+ y: { type: 'number' },
191
+ z: { type: 'number' },
192
+ },
193
+ },
194
+ orientation: {
195
+ type: 'object',
196
+ description: 'Target rotation as quaternion {x,y,z,w} or euler angles {pitch,yaw,roll} in degrees',
197
+ properties: {
198
+ x: { type: 'number', description: 'Quaternion X component' },
199
+ y: { type: 'number', description: 'Quaternion Y component' },
200
+ z: { type: 'number', description: 'Quaternion Z component' },
201
+ w: { type: 'number', description: 'Quaternion W component' },
202
+ pitch: {
203
+ type: 'number',
204
+ description: 'Pitch in degrees (X rotation)',
205
+ },
206
+ yaw: { type: 'number', description: 'Yaw in degrees (Y rotation)' },
207
+ roll: {
208
+ type: 'number',
209
+ description: 'Roll in degrees (Z rotation)',
210
+ },
211
+ },
212
+ },
213
+ duration: {
214
+ type: 'number',
215
+ description: 'Animation duration in seconds (default: 0.5)',
216
+ },
217
+ },
218
+ required: ['device'],
219
+ },
220
+ },
221
+ // =============================================================================
222
+ // Input Mode
223
+ // =============================================================================
224
+ {
225
+ name: 'xr_set_input_mode',
226
+ description: 'Switch between controller and hand tracking input modes',
227
+ inputSchema: {
228
+ type: 'object',
229
+ properties: {
230
+ mode: {
231
+ type: 'string',
232
+ enum: ['controller', 'hand'],
233
+ description: 'Input mode to switch to',
234
+ },
235
+ },
236
+ required: ['mode'],
237
+ },
238
+ },
239
+ {
240
+ name: 'xr_set_connected',
241
+ description: 'Connect or disconnect an input device',
242
+ inputSchema: {
243
+ type: 'object',
244
+ properties: {
245
+ device: {
246
+ type: 'string',
247
+ enum: [
248
+ 'controller-left',
249
+ 'controller-right',
250
+ 'hand-left',
251
+ 'hand-right',
252
+ ],
253
+ description: 'The input device',
254
+ },
255
+ connected: {
256
+ type: 'boolean',
257
+ description: 'Whether the device should be connected',
258
+ },
259
+ },
260
+ required: ['device', 'connected'],
261
+ },
262
+ },
263
+ // =============================================================================
264
+ // Select/Trigger Input
265
+ // =============================================================================
266
+ {
267
+ name: 'xr_get_select_value',
268
+ description: 'Get the current select (trigger/pinch) value for an input device',
269
+ inputSchema: {
270
+ type: 'object',
271
+ properties: {
272
+ device: {
273
+ type: 'string',
274
+ enum: [
275
+ 'controller-left',
276
+ 'controller-right',
277
+ 'hand-left',
278
+ 'hand-right',
279
+ ],
280
+ description: 'The input device',
281
+ },
282
+ },
283
+ required: ['device'],
284
+ },
285
+ },
286
+ {
287
+ name: 'xr_set_select_value',
288
+ description: 'Set the select (trigger/pinch) value for an input device. Use for grab-move-release patterns.',
289
+ inputSchema: {
290
+ type: 'object',
291
+ properties: {
292
+ device: {
293
+ type: 'string',
294
+ enum: [
295
+ 'controller-left',
296
+ 'controller-right',
297
+ 'hand-left',
298
+ 'hand-right',
299
+ ],
300
+ description: 'The input device',
301
+ },
302
+ value: {
303
+ type: 'number',
304
+ minimum: 0,
305
+ maximum: 1,
306
+ description: 'Select value (0=released, 1=fully pressed/pinched)',
307
+ },
308
+ },
309
+ required: ['device', 'value'],
310
+ },
311
+ },
312
+ {
313
+ name: 'xr_select',
314
+ description: 'Perform a complete select action (press and release). Dispatches selectstart, select, selectend events.',
315
+ inputSchema: {
316
+ type: 'object',
317
+ properties: {
318
+ device: {
319
+ type: 'string',
320
+ enum: [
321
+ 'controller-left',
322
+ 'controller-right',
323
+ 'hand-left',
324
+ 'hand-right',
325
+ ],
326
+ description: 'The input device',
327
+ },
328
+ duration: {
329
+ type: 'number',
330
+ description: 'How long to hold in seconds (default: 0.15)',
331
+ },
332
+ },
333
+ required: ['device'],
334
+ },
335
+ },
336
+ // =============================================================================
337
+ // Gamepad State (Controllers only)
338
+ // =============================================================================
339
+ {
340
+ name: 'xr_get_gamepad_state',
341
+ description: 'Get full gamepad state including all buttons and axes. Button indices in the result: 0=trigger, 1=squeeze, 2=thumbstick, 3=A/X, 4=B/Y, 5=thumbrest.',
342
+ inputSchema: {
343
+ type: 'object',
344
+ properties: {
345
+ device: {
346
+ type: 'string',
347
+ enum: ['controller-left', 'controller-right'],
348
+ description: 'The controller',
349
+ },
350
+ },
351
+ required: ['device'],
352
+ },
353
+ },
354
+ {
355
+ name: 'xr_set_gamepad_state',
356
+ description: 'Set gamepad button and axis values by index',
357
+ inputSchema: {
358
+ type: 'object',
359
+ properties: {
360
+ device: {
361
+ type: 'string',
362
+ enum: ['controller-left', 'controller-right'],
363
+ description: 'The controller',
364
+ },
365
+ buttons: {
366
+ type: 'array',
367
+ description: 'Button states to set',
368
+ items: {
369
+ type: 'object',
370
+ properties: {
371
+ index: {
372
+ type: 'number',
373
+ description: 'Button index (0=trigger, 1=squeeze, 2=thumbstick, 3=A/X, 4=B/Y, 5=thumbrest)',
374
+ },
375
+ value: { type: 'number', description: 'Button value 0-1' },
376
+ touched: {
377
+ type: 'boolean',
378
+ description: 'Whether button is touched',
379
+ },
380
+ },
381
+ required: ['index', 'value'],
382
+ },
383
+ },
384
+ axes: {
385
+ type: 'array',
386
+ description: 'Axis values to set',
387
+ items: {
388
+ type: 'object',
389
+ properties: {
390
+ index: {
391
+ type: 'number',
392
+ description: 'Axis index (0=thumbstick X, 1=thumbstick Y)',
393
+ },
394
+ value: { type: 'number', description: 'Axis value -1 to 1' },
395
+ },
396
+ required: ['index', 'value'],
397
+ },
398
+ },
399
+ },
400
+ required: ['device'],
401
+ },
402
+ },
403
+ // =============================================================================
404
+ // Screenshot
405
+ // =============================================================================
406
+ {
407
+ name: 'browser_screenshot',
408
+ description: 'Capture a screenshot of the browser. Returns the image directly.',
409
+ inputSchema: {
410
+ type: 'object',
411
+ properties: {},
412
+ },
413
+ },
414
+ // =============================================================================
415
+ // Device State
416
+ // =============================================================================
417
+ {
418
+ name: 'xr_get_device_state',
419
+ description: 'Get comprehensive state of the XR device including headset, controllers, and hands',
420
+ inputSchema: {
421
+ type: 'object',
422
+ properties: {},
423
+ required: [],
424
+ },
425
+ },
426
+ {
427
+ name: 'xr_set_device_state',
428
+ description: 'Set device state. When called with no state, resets everything to defaults.',
429
+ inputSchema: {
430
+ type: 'object',
431
+ properties: {
432
+ state: {
433
+ type: 'object',
434
+ description: 'Partial device state to apply. Omit to reset to defaults.',
435
+ properties: {
436
+ headset: {
437
+ type: 'object',
438
+ description: 'Headset transform',
439
+ properties: {
440
+ position: {
441
+ type: 'object',
442
+ properties: {
443
+ x: { type: 'number' },
444
+ y: { type: 'number' },
445
+ z: { type: 'number' },
446
+ },
447
+ },
448
+ orientation: {
449
+ type: 'object',
450
+ properties: {
451
+ x: { type: 'number' },
452
+ y: { type: 'number' },
453
+ z: { type: 'number' },
454
+ w: { type: 'number' },
455
+ },
456
+ },
457
+ },
458
+ },
459
+ inputMode: {
460
+ type: 'string',
461
+ enum: ['controller', 'hand'],
462
+ description: 'Input mode',
463
+ },
464
+ stereoEnabled: {
465
+ type: 'boolean',
466
+ description: 'Whether stereo rendering is enabled',
467
+ },
468
+ fov: {
469
+ type: 'number',
470
+ description: 'Field of view in degrees',
471
+ },
472
+ controllers: {
473
+ type: 'object',
474
+ description: 'Controller states',
475
+ properties: {
476
+ left: {
477
+ type: 'object',
478
+ properties: {
479
+ position: { type: 'object' },
480
+ orientation: { type: 'object' },
481
+ connected: { type: 'boolean' },
482
+ },
483
+ },
484
+ right: {
485
+ type: 'object',
486
+ properties: {
487
+ position: { type: 'object' },
488
+ orientation: { type: 'object' },
489
+ connected: { type: 'boolean' },
490
+ },
491
+ },
492
+ },
493
+ },
494
+ hands: {
495
+ type: 'object',
496
+ description: 'Hand states',
497
+ properties: {
498
+ left: {
499
+ type: 'object',
500
+ properties: {
501
+ position: { type: 'object' },
502
+ orientation: { type: 'object' },
503
+ connected: { type: 'boolean' },
504
+ },
505
+ },
506
+ right: {
507
+ type: 'object',
508
+ properties: {
509
+ position: { type: 'object' },
510
+ orientation: { type: 'object' },
511
+ connected: { type: 'boolean' },
512
+ },
513
+ },
514
+ },
515
+ },
516
+ },
517
+ },
518
+ },
519
+ },
520
+ },
521
+ // =============================================================================
522
+ // Console Logs (Plugin-specific, not in IWER)
523
+ // =============================================================================
524
+ {
525
+ name: 'browser_get_console_logs',
526
+ description: 'Get console logs from the browser with optional filtering. By default excludes debug level logs.',
527
+ inputSchema: {
528
+ type: 'object',
529
+ properties: {
530
+ count: {
531
+ type: 'number',
532
+ description: 'Maximum number of logs to return (most recent N)',
533
+ },
534
+ level: {
535
+ oneOf: [
536
+ {
537
+ type: 'string',
538
+ enum: ['log', 'info', 'warn', 'error', 'debug'],
539
+ },
540
+ {
541
+ type: 'array',
542
+ items: {
543
+ type: 'string',
544
+ enum: ['log', 'info', 'warn', 'error', 'debug'],
545
+ },
546
+ },
547
+ ],
548
+ description: 'Filter by log level(s). Default: ["log", "info", "warn", "error"] (excludes debug)',
549
+ },
550
+ pattern: {
551
+ type: 'string',
552
+ description: 'Regex pattern to filter log messages',
553
+ },
554
+ since: {
555
+ type: 'number',
556
+ description: 'Return logs since this timestamp (ms since epoch)',
557
+ },
558
+ },
559
+ },
560
+ },
561
+ {
562
+ name: 'browser_reload_page',
563
+ description: 'Reload the browser page to reset application state. Use when the app enters an unrecoverable state or to apply code changes.',
564
+ inputSchema: {
565
+ type: 'object',
566
+ properties: {},
567
+ },
568
+ },
569
+ // =============================================================================
570
+ // Framework-Specific Tools (IWSDK or any framework with FRAMEWORK_MCP_RUNTIME)
571
+ // =============================================================================
572
+ {
573
+ name: 'scene_get_hierarchy',
574
+ description: 'Get the Three.js scene hierarchy as a JSON tree. Returns object names, UUIDs, and entity indices where available. Requires IWSDK or a framework that provides FRAMEWORK_MCP_RUNTIME.',
575
+ inputSchema: {
576
+ type: 'object',
577
+ properties: {
578
+ parentId: {
579
+ type: 'string',
580
+ description: 'UUID of parent Object3D to start from. Defaults to scene root if omitted.',
581
+ },
582
+ maxDepth: {
583
+ type: 'number',
584
+ description: 'Maximum depth to traverse (default: 5). Use to limit context size.',
585
+ },
586
+ },
587
+ },
588
+ },
589
+ {
590
+ name: 'scene_get_object_transform',
591
+ description: 'Get local and global transforms of an Object3D. Includes positionRelativeToXROrigin which can be used directly with xr_look_at tool. Requires IWSDK or a framework that provides FRAMEWORK_MCP_RUNTIME.',
592
+ inputSchema: {
593
+ type: 'object',
594
+ properties: {
595
+ uuid: {
596
+ type: 'string',
597
+ description: 'UUID of the Object3D (get this from scene_get_hierarchy)',
598
+ },
599
+ },
600
+ required: ['uuid'],
601
+ },
602
+ },
603
+ // =============================================================================
604
+ // ECS Debugging (IWSDK — requires FRAMEWORK_MCP_RUNTIME)
605
+ // =============================================================================
606
+ {
607
+ name: 'ecs_pause',
608
+ description: 'Pause ECS system updates. The render loop continues (XR session stays alive, screenshots still work) but no systems tick. Use ecs_step to advance individual frames while paused. Requires FRAMEWORK_MCP_RUNTIME.',
609
+ inputSchema: {
610
+ type: 'object',
611
+ properties: {},
612
+ },
613
+ },
614
+ {
615
+ name: 'ecs_resume',
616
+ description: 'Resume ECS system updates after pausing. The first frame after resume uses a capped delta to avoid physics explosions. Requires FRAMEWORK_MCP_RUNTIME.',
617
+ inputSchema: {
618
+ type: 'object',
619
+ properties: {},
620
+ },
621
+ },
622
+ {
623
+ name: 'ecs_step',
624
+ description: 'Advance N ECS frames with a fixed timestep while paused. Must call ecs_pause first. Useful for frame-by-frame debugging. Requires FRAMEWORK_MCP_RUNTIME.',
625
+ inputSchema: {
626
+ type: 'object',
627
+ properties: {
628
+ count: {
629
+ type: 'number',
630
+ description: 'Number of frames to advance (1-120, default: 1)',
631
+ },
632
+ delta: {
633
+ type: 'number',
634
+ description: 'Fixed timestep in seconds for each frame (default: 1/72 ≈ 0.0139, matching Quest refresh rate)',
635
+ },
636
+ },
637
+ },
638
+ },
639
+ {
640
+ name: 'ecs_query_entity',
641
+ description: 'Get all component data for an entity. Use entityIndex from scene_get_hierarchy or ecs_find_entities. Returns serialized component values including vectors, entity refs, and Object3D references. Requires FRAMEWORK_MCP_RUNTIME.',
642
+ inputSchema: {
643
+ type: 'object',
644
+ properties: {
645
+ entityIndex: {
646
+ type: 'number',
647
+ description: 'Entity index (get this from scene_get_hierarchy or ecs_find_entities)',
648
+ },
649
+ components: {
650
+ type: 'array',
651
+ items: { type: 'string' },
652
+ description: 'Optional list of component IDs to include. If omitted, returns all components on the entity.',
653
+ },
654
+ },
655
+ required: ['entityIndex'],
656
+ },
657
+ },
658
+ {
659
+ name: 'ecs_find_entities',
660
+ description: 'Find entities by component composition and/or name. Returns entity indices and component lists. Use the returned entityIndex values with ecs_query_entity for detailed inspection. Requires FRAMEWORK_MCP_RUNTIME.',
661
+ inputSchema: {
662
+ type: 'object',
663
+ properties: {
664
+ withComponents: {
665
+ type: 'array',
666
+ items: { type: 'string' },
667
+ description: 'Component IDs that entities must have (AND logic)',
668
+ },
669
+ withoutComponents: {
670
+ type: 'array',
671
+ items: { type: 'string' },
672
+ description: 'Component IDs that entities must NOT have',
673
+ },
674
+ namePattern: {
675
+ type: 'string',
676
+ description: 'Regex pattern to match against entity Object3D name (case-insensitive)',
677
+ },
678
+ limit: {
679
+ type: 'number',
680
+ description: 'Maximum number of results (1-50, default: 50)',
681
+ },
682
+ },
683
+ },
684
+ },
685
+ {
686
+ name: 'ecs_list_systems',
687
+ description: 'List all registered ECS systems with name, priority, pause state, config keys, and query entity counts. Requires FRAMEWORK_MCP_RUNTIME.',
688
+ inputSchema: {
689
+ type: 'object',
690
+ properties: {},
691
+ },
692
+ },
693
+ {
694
+ name: 'ecs_list_components',
695
+ description: 'List all registered ECS components with their field schemas (type, default). Requires FRAMEWORK_MCP_RUNTIME.',
696
+ inputSchema: {
697
+ type: 'object',
698
+ properties: {},
699
+ },
700
+ },
701
+ {
702
+ name: 'ecs_toggle_system',
703
+ description: 'Pause or resume a specific ECS system by name. Use ecs_list_systems to discover system names. Requires FRAMEWORK_MCP_RUNTIME.',
704
+ inputSchema: {
705
+ type: 'object',
706
+ properties: {
707
+ name: {
708
+ type: 'string',
709
+ description: "System class name (e.g. 'OrbSystem', 'RobotSystem')",
710
+ },
711
+ paused: {
712
+ type: 'boolean',
713
+ description: 'Set to true to pause, false to resume. If omitted, toggles current state.',
714
+ },
715
+ },
716
+ required: ['name'],
717
+ },
718
+ },
719
+ {
720
+ name: 'ecs_set_component',
721
+ description: 'Set a component field value on an entity. Scalars use setValue (with validation), vectors accept arrays. Use ecs_query_entity to inspect current values first. Requires FRAMEWORK_MCP_RUNTIME.',
722
+ inputSchema: {
723
+ type: 'object',
724
+ properties: {
725
+ entityIndex: {
726
+ type: 'number',
727
+ description: 'Entity index (from ecs_find_entities or scene_get_hierarchy)',
728
+ },
729
+ componentId: {
730
+ type: 'string',
731
+ description: "Component ID (e.g. 'Orb', 'RobotMood', 'Transform')",
732
+ },
733
+ field: {
734
+ type: 'string',
735
+ description: "Field name within the component (e.g. 'orbitSpeed', 'mood')",
736
+ },
737
+ value: {
738
+ description: 'New value. Scalars: number/string/boolean. Vectors: array of numbers (e.g. [1,2,3] for Vec3).',
739
+ },
740
+ },
741
+ required: ['entityIndex', 'componentId', 'field', 'value'],
742
+ },
743
+ },
744
+ {
745
+ name: 'ecs_snapshot',
746
+ description: 'Capture a snapshot of all ECS entity/component state. Stores up to 2 snapshots. Use with ecs_diff to compare. Requires FRAMEWORK_MCP_RUNTIME.',
747
+ inputSchema: {
748
+ type: 'object',
749
+ properties: {
750
+ label: {
751
+ type: 'string',
752
+ description: 'Label for this snapshot (default: auto-generated). Use to reference in ecs_diff.',
753
+ },
754
+ },
755
+ },
756
+ },
757
+ {
758
+ name: 'ecs_diff',
759
+ description: 'Compare two ECS snapshots. Shows added/removed/changed entities and field-level diffs. Requires FRAMEWORK_MCP_RUNTIME.',
760
+ inputSchema: {
761
+ type: 'object',
762
+ properties: {
763
+ from: {
764
+ type: 'string',
765
+ description: "Label of the 'before' snapshot",
766
+ },
767
+ to: {
768
+ type: 'string',
769
+ description: "Label of the 'after' snapshot",
770
+ },
771
+ },
772
+ required: ['from', 'to'],
773
+ },
774
+ },
775
+ ];
776
+ const RUNTIME_TOOL_TO_METHOD = {
777
+ xr_get_session_status: 'get_session_status',
778
+ xr_accept_session: 'accept_session',
779
+ xr_end_session: 'end_session',
780
+ xr_get_transform: 'get_transform',
781
+ xr_set_transform: 'set_transform',
782
+ xr_look_at: 'look_at',
783
+ xr_animate_to: 'animate_to',
784
+ xr_set_input_mode: 'set_input_mode',
785
+ xr_set_connected: 'set_connected',
786
+ xr_get_select_value: 'get_select_value',
787
+ xr_set_select_value: 'set_select_value',
788
+ xr_select: 'select',
789
+ xr_get_gamepad_state: 'get_gamepad_state',
790
+ xr_set_gamepad_state: 'set_gamepad_state',
791
+ xr_get_device_state: 'get_device_state',
792
+ xr_set_device_state: 'set_device_state',
793
+ browser_screenshot: 'screenshot',
794
+ browser_get_console_logs: 'get_console_logs',
795
+ browser_reload_page: 'reload_page',
796
+ scene_get_hierarchy: 'get_scene_hierarchy',
797
+ scene_get_object_transform: 'get_object_transform',
798
+ };
799
+ const RUNTIME_CLI_PATHS = {
800
+ xr_get_session_status: ['xr', 'status'],
801
+ xr_accept_session: ['xr', 'enter'],
802
+ xr_end_session: ['xr', 'exit'],
803
+ xr_get_transform: ['xr', 'get-transform'],
804
+ xr_set_transform: ['xr', 'set-transform'],
805
+ xr_look_at: ['xr', 'look-at'],
806
+ xr_animate_to: ['xr', 'animate-to'],
807
+ xr_set_input_mode: ['xr', 'set-input-mode'],
808
+ xr_set_connected: ['xr', 'set-connected'],
809
+ xr_get_select_value: ['xr', 'get-select-value'],
810
+ xr_set_select_value: ['xr', 'set-select-value'],
811
+ xr_select: ['xr', 'select'],
812
+ xr_get_gamepad_state: ['xr', 'get-gamepad-state'],
813
+ xr_set_gamepad_state: ['xr', 'set-gamepad-state'],
814
+ browser_screenshot: ['browser', 'screenshot'],
815
+ xr_get_device_state: ['xr', 'get-device-state'],
816
+ xr_set_device_state: ['xr', 'set-device-state'],
817
+ browser_get_console_logs: ['browser', 'logs'],
818
+ browser_reload_page: ['browser', 'reload'],
819
+ scene_get_hierarchy: ['scene', 'hierarchy'],
820
+ scene_get_object_transform: ['scene', 'transform'],
821
+ ecs_pause: ['ecs', 'pause'],
822
+ ecs_resume: ['ecs', 'resume'],
823
+ ecs_step: ['ecs', 'step'],
824
+ ecs_query_entity: ['ecs', 'query'],
825
+ ecs_find_entities: ['ecs', 'find'],
826
+ ecs_list_systems: ['ecs', 'systems'],
827
+ ecs_list_components: ['ecs', 'components'],
828
+ ecs_toggle_system: ['ecs', 'toggle-system'],
829
+ ecs_set_component: ['ecs', 'set-component'],
830
+ ecs_snapshot: ['ecs', 'snapshot'],
831
+ ecs_diff: ['ecs', 'diff'],
832
+ };
833
+ RUNTIME_MCP_TOOLS.map((tool) => {
834
+ const cliPath = RUNTIME_CLI_PATHS[tool.name];
835
+ return {
836
+ id: cliPath ? cliPath.join('.') : tool.name,
837
+ domain: cliPath?.[0] ?? 'misc',
838
+ action: cliPath?.[1] ?? tool.name,
839
+ cliPath: cliPath ?? ['misc', tool.name],
840
+ mcpName: tool.name,
841
+ wsMethod: RUNTIME_TOOL_TO_METHOD[tool.name] ?? tool.name,
842
+ description: tool.description,
843
+ inputSchema: tool.inputSchema,
844
+ };
845
+ });
846
+
847
+ /**
848
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
849
+ *
850
+ * This source code is licensed under the MIT license found in the
851
+ * LICENSE file in the root directory of this source tree.
852
+ */
853
+ const RUNTIME_RPC_ERROR_CODE = -32e3;
854
+ function createUnavailableBrowserRpcError(browser) {
855
+ if (browser?.status === 'launch_failed') {
856
+ return {
857
+ code: RUNTIME_RPC_ERROR_CODE,
858
+ message: browser.lastError?.message ?? 'Managed browser launch failed.',
859
+ cause: browser.lastError?.cause ?? 'browser_launch_failed',
860
+ };
861
+ }
862
+ if (browser?.status === 'disconnected') {
863
+ return {
864
+ code: RUNTIME_RPC_ERROR_CODE,
865
+ message: browser.lastError?.message ??
866
+ 'Managed browser runtime disconnected from the MCP bridge.',
867
+ cause: browser.lastError?.cause ?? 'connection_lost',
868
+ };
869
+ }
870
+ if (browser?.connected && browser.commandReady === false) {
871
+ return {
872
+ code: RUNTIME_RPC_ERROR_CODE,
873
+ message: browser.lastError?.message ??
874
+ 'Managed browser command path is still warming up.',
875
+ cause: browser.lastError?.cause ?? 'browser_not_ready',
876
+ };
877
+ }
878
+ return {
879
+ code: RUNTIME_RPC_ERROR_CODE,
880
+ message: 'Browser not ready',
881
+ cause: browser?.lastError?.cause ?? 'browser_not_ready',
882
+ };
883
+ }
884
+
13
885
  /**
14
886
  * Copyright (c) Meta Platforms, Inc. and affiliates.
15
887
  *
@@ -17,6 +889,7 @@ import { fileURLToPath } from 'url';
17
889
  * LICENSE file in the root directory of this source tree.
18
890
  */
19
891
  const MAX_LOGS = 1000;
892
+ const TRACE_PREFIX = '[IWSDK-MCP-TRACE]';
20
893
  /** Map Playwright console message types to our LogLevel. */
21
894
  const PLAYWRIGHT_TYPE_MAP = {
22
895
  log: 'log',
@@ -87,10 +960,12 @@ let installPromise = null;
87
960
  * On install failure the flag stays unset so the next retry can try again.
88
961
  */
89
962
  async function ensureChromiumInstalled() {
90
- if (chromiumInstalled)
963
+ if (chromiumInstalled) {
91
964
  return;
92
- if (installPromise)
965
+ }
966
+ if (installPromise) {
93
967
  return installPromise;
968
+ }
94
969
  const execPath = chromium.executablePath();
95
970
  if (fs.existsSync(execPath)) {
96
971
  chromiumInstalled = true;
@@ -128,7 +1003,7 @@ async function doChromiumInstall() {
128
1003
  async function launchManagedBrowser(url, headless, verbose, viewport = null, screenshotSize = {
129
1004
  width: 800,
130
1005
  height: 800,
131
- }) {
1006
+ }, traceMcp = false) {
132
1007
  await ensureChromiumInstalled();
133
1008
  // Select GPU backend based on platform
134
1009
  const angleBackend = os.platform() === 'darwin'
@@ -165,7 +1040,7 @@ async function launchManagedBrowser(url, headless, verbose, viewport = null, scr
165
1040
  if (type === 'error') {
166
1041
  console.error('[browser]', text);
167
1042
  }
168
- else if (verbose) {
1043
+ else if (verbose || text.startsWith(TRACE_PREFIX)) {
169
1044
  console.log(`[browser:${type}]`, text);
170
1045
  }
171
1046
  });
@@ -191,9 +1066,10 @@ async function launchManagedBrowser(url, headless, verbose, viewport = null, scr
191
1066
  // Mark this tab as the Playwright-managed tab. The injection template
192
1067
  // checks this flag and only initializes the MCP WebSocket client when
193
1068
  // present, so manually-opened browser tabs are not remote-controlled.
194
- await page.addInitScript(() => {
1069
+ await page.addInitScript((traceEnabled) => {
195
1070
  window.__IWER_MCP_MANAGED = true;
196
- });
1071
+ window.__IWSDK_MCP_TRACE = traceEnabled;
1072
+ }, traceMcp);
197
1073
  await page.goto(url, { waitUntil: 'networkidle' });
198
1074
  // Wait for IWER to inject and XR device to be available
199
1075
  await page.waitForFunction(() => window.IWER_DEVICE !== undefined, {
@@ -228,6 +1104,21 @@ async function launchManagedBrowser(url, headless, verbose, viewport = null, scr
228
1104
  },
229
1105
  page,
230
1106
  queryLogs: (options) => consoleCapture.query(options),
1107
+ getTabMetadata: async () => page.evaluate(() => {
1108
+ const id = typeof sessionStorage !== 'undefined'
1109
+ ? sessionStorage.getItem('iwer-mcp-tab-id')
1110
+ : null;
1111
+ const rawGeneration = typeof sessionStorage !== 'undefined'
1112
+ ? sessionStorage.getItem('iwer-mcp-gen')
1113
+ : null;
1114
+ const generation = rawGeneration != null && rawGeneration !== ''
1115
+ ? Number(rawGeneration)
1116
+ : null;
1117
+ return {
1118
+ id,
1119
+ generation: Number.isFinite(generation) ? generation : null,
1120
+ };
1121
+ }),
231
1122
  screenshot: async () => {
232
1123
  const raw = await page.screenshot({ type: 'png' });
233
1124
  // In non-agent modes (viewport is null / freely resizable), downscale
@@ -271,11 +1162,11 @@ function hzdbTelemetry(args, clientVersion) {
271
1162
  if (clientVersion) {
272
1163
  globalArgs.push('--client-version', clientVersion);
273
1164
  }
274
- const child = execFile('npx', [...globalArgs, ...args], {
275
- timeout: 5000,
276
- shell: true,
1165
+ const child = spawn('npx', [...globalArgs, ...args], {
1166
+ stdio: 'ignore',
277
1167
  });
278
1168
  child.on('error', () => { });
1169
+ child.unref();
279
1170
  }
280
1171
  function reportSessionStart(sessionId, opts) {
281
1172
  const args = ['session-start', '--session-id', sessionId];
@@ -441,216 +1332,132 @@ function createRelayHandler(options) {
441
1332
  * This source code is licensed under the MIT license found in the
442
1333
  * LICENSE file in the root directory of this source tree.
443
1334
  */
444
- const MCP_CONFIG_TARGETS = {
445
- claude: { file: '.mcp.json', jsonKey: 'mcpServers', format: 'json' },
446
- cursor: { file: '.cursor/mcp.json', jsonKey: 'mcpServers', format: 'json' },
447
- copilot: { file: '.vscode/mcp.json', jsonKey: 'servers', format: 'json' },
448
- codex: { file: '.codex/config.toml', jsonKey: null, format: 'toml' },
449
- };
450
- const TOML_BLOCK_START = '# --- IWER managed (do not edit) ---';
451
- const TOML_BLOCK_END = '# --- end IWER managed ---';
452
- /**
453
- * Merge our server entries into an existing (or new) JSON config file.
454
- * When `managedKeys` is provided, any key in that list that is NOT in
455
- * `serverEntries` is removed — this prevents stale entries from surviving
456
- * across config changes (e.g. uninstalling an optional MCP server).
457
- * Returns true if the file was newly created.
458
- */
459
- async function mergeJsonConfig(filePath, serverEntries, jsonKey, managedKeys) {
460
- let existing = {};
461
- let created = false;
462
- try {
463
- const raw = await readFile(filePath, 'utf-8');
464
- existing = JSON.parse(raw);
465
- }
466
- catch {
467
- created = true;
468
- }
469
- const section = existing[jsonKey] ?? {};
470
- if (managedKeys) {
471
- for (const key of managedKeys) {
472
- if (!(key in serverEntries)) {
473
- delete section[key];
474
- }
475
- }
1335
+ function isTraceEnabled() {
1336
+ return process.env.IWSDK_RUNTIME_TRACE === '1';
1337
+ }
1338
+ function traceRuntimeSession(event, details = {}) {
1339
+ if (!isTraceEnabled()) {
1340
+ return;
476
1341
  }
477
- Object.assign(section, serverEntries);
478
- existing[jsonKey] = section;
479
- await mkdir(path.dirname(filePath), { recursive: true });
480
- await writeFile(filePath, JSON.stringify(existing, null, 2) + '\n');
481
- return created;
1342
+ console.error(`[IWSDK-RUNTIME-TRACE][session] ${event} ${JSON.stringify(details)}`);
482
1343
  }
483
- /**
484
- * Remove our managed server keys from a JSON config file.
485
- * If we originally created the file and the servers section is now empty
486
- * with no other top-level keys, delete the file entirely.
487
- *
488
- * @internal Not called by the plugin at runtime (MCP configs are left in
489
- * place on shutdown). Kept as a tested utility for potential external use.
490
- */
491
- async function unmergeJsonConfig(filePath, serverKeys, jsonKey, weCreatedFile) {
492
- let raw;
1344
+ function normalizeWorkspaceRoot(workspaceRoot) {
1345
+ const resolved = path__default.resolve(workspaceRoot);
493
1346
  try {
494
- raw = await readFile(filePath, 'utf-8');
1347
+ return existsSync(resolved) ? realpathSync.native(resolved) : resolved;
495
1348
  }
496
1349
  catch {
497
- return; // file doesn't exist — no-op
1350
+ return resolved;
498
1351
  }
499
- let existing;
1352
+ }
1353
+ function getRuntimeSessionFilePath(workspaceRoot) {
1354
+ return path__default.join(normalizeWorkspaceRoot(workspaceRoot), IWSDK_RUNTIME_SESSION_PATH);
1355
+ }
1356
+ const sessionMutationQueues = new Map();
1357
+ async function enqueueSessionMutation(workspaceRoot, mutate) {
1358
+ const normalizedWorkspaceRoot = normalizeWorkspaceRoot(workspaceRoot);
1359
+ const previous = sessionMutationQueues.get(normalizedWorkspaceRoot) ?? Promise.resolve();
1360
+ const next = previous
1361
+ .catch(() => { })
1362
+ .then(() => mutate(normalizedWorkspaceRoot));
1363
+ sessionMutationQueues.set(normalizedWorkspaceRoot, next);
500
1364
  try {
501
- existing = JSON.parse(raw);
502
- }
503
- catch {
504
- return; // invalid JSON — leave it alone
1365
+ return await next;
505
1366
  }
506
- const section = existing[jsonKey];
507
- if (section) {
508
- for (const key of serverKeys) {
509
- delete section[key];
510
- }
511
- if (Object.keys(section).length === 0) {
512
- delete existing[jsonKey];
1367
+ finally {
1368
+ if (sessionMutationQueues.get(normalizedWorkspaceRoot) === next) {
1369
+ sessionMutationQueues.delete(normalizedWorkspaceRoot);
513
1370
  }
514
1371
  }
515
- if (weCreatedFile && Object.keys(existing).length === 0) {
516
- try {
517
- await unlink(filePath);
518
- }
519
- catch { }
520
- }
521
- else {
522
- await writeFile(filePath, JSON.stringify(existing, null, 2) + '\n');
523
- }
524
1372
  }
525
- /**
526
- * Merge our managed TOML block into an existing (or new) config file.
527
- * Returns true if the file was newly created.
528
- */
529
- async function mergeTomlConfig(filePath, serverEntries) {
530
- let existing = '';
531
- let created = false;
1373
+ async function readRuntimeSession(filePath) {
532
1374
  try {
533
- existing = await readFile(filePath, 'utf-8');
1375
+ const raw = await readFile(filePath, 'utf8');
1376
+ return JSON.parse(raw);
534
1377
  }
535
1378
  catch {
536
- created = true;
537
- }
538
- // Remove any old managed block
539
- const startIdx = existing.indexOf(TOML_BLOCK_START);
540
- const endIdx = existing.indexOf(TOML_BLOCK_END);
541
- if (startIdx !== -1 && endIdx !== -1 && startIdx < endIdx) {
542
- existing =
543
- existing.slice(0, startIdx).trimEnd() +
544
- '\n' +
545
- existing.slice(endIdx + TOML_BLOCK_END.length).trimStart();
546
- existing = existing.trim();
547
- }
548
- // Build new managed block
549
- const tomlLines = [TOML_BLOCK_START];
550
- for (const [name, entry] of Object.entries(serverEntries)) {
551
- tomlLines.push(`[mcp_servers.${name}]`);
552
- tomlLines.push(`command = ${JSON.stringify(entry.command)}`);
553
- tomlLines.push(`args = [${entry.args.map((a) => JSON.stringify(a)).join(', ')}]`);
554
- tomlLines.push('');
1379
+ return null;
555
1380
  }
556
- tomlLines.push(TOML_BLOCK_END);
557
- const newContent = existing
558
- ? existing.trimEnd() + '\n\n' + tomlLines.join('\n') + '\n'
559
- : tomlLines.join('\n') + '\n';
560
- await mkdir(path.dirname(filePath), { recursive: true });
561
- await writeFile(filePath, newContent);
562
- return created;
563
1381
  }
564
- /**
565
- * Remove our managed TOML block from a config file.
566
- * If we originally created the file and it's now effectively empty, delete it.
567
- *
568
- * @internal Not called by the plugin at runtime (MCP configs are left in
569
- * place on shutdown). Kept as a tested utility for potential external use.
570
- */
571
- async function unmergeTomlConfig(filePath, weCreatedFile) {
572
- let existing;
1382
+ async function writeRuntimeSession(workspaceRoot, session) {
1383
+ const filePath = getRuntimeSessionFilePath(workspaceRoot);
1384
+ await mkdir(path__default.dirname(filePath), { recursive: true });
1385
+ const tempPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
573
1386
  try {
574
- existing = await readFile(filePath, 'utf-8');
575
- }
576
- catch {
577
- return; // file doesn't exist — no-op
578
- }
579
- const startIdx = existing.indexOf(TOML_BLOCK_START);
580
- const endIdx = existing.indexOf(TOML_BLOCK_END);
581
- if (startIdx === -1 || endIdx === -1 || startIdx >= endIdx) {
582
- // No managed block found — nothing to remove
583
- if (weCreatedFile && existing.trim() === '') {
584
- try {
585
- await unlink(filePath);
586
- }
587
- catch { }
588
- }
589
- return;
1387
+ await writeFile(tempPath, `${JSON.stringify(session, null, 2)}\n`, 'utf8');
1388
+ await rename(tempPath, filePath);
590
1389
  }
591
- const cleaned = existing.slice(0, startIdx).trimEnd() +
592
- '\n' +
593
- existing.slice(endIdx + TOML_BLOCK_END.length).trimStart();
594
- const result = cleaned.trim();
595
- if (weCreatedFile && result === '') {
596
- try {
597
- await unlink(filePath);
598
- }
599
- catch { }
600
- }
601
- else {
602
- await writeFile(filePath, result + '\n');
1390
+ finally {
1391
+ await rm(tempPath, { force: true }).catch(() => { });
603
1392
  }
1393
+ return session;
604
1394
  }
605
- /**
606
- * Warm up the RAG MCP server by spawning it and waiting for initialization.
607
- * This downloads the HuggingFace embedding model if not already cached.
608
- * The process is killed after initialization completes.
609
- */
610
- function warmupRagMcp(ragMcpServerPath, verbose) {
611
- if (!existsSync(ragMcpServerPath)) {
612
- if (verbose) {
613
- console.log('[RAG-MCP] Server not found, skipping warmup');
614
- }
615
- return;
616
- }
617
- console.log('📚 RAG-MCP: Warming up (downloading model if needed)...');
618
- const warmupProcess = spawn('node', [ragMcpServerPath], {
619
- stdio: ['pipe', 'pipe', 'pipe'],
620
- });
621
- let initialized = false;
622
- warmupProcess.stderr?.on('data', (data) => {
623
- const output = data.toString();
624
- if (verbose) {
625
- // Print warmup progress
626
- process.stderr.write(`[RAG-MCP Warmup] ${output}`);
627
- }
628
- // Check if initialization is complete
629
- if (output.includes('IWSDK RAG MCP Server is ready')) {
630
- initialized = true;
631
- clearTimeout(warmupTimeout);
632
- console.log('📚 RAG-MCP: Model cached successfully');
633
- warmupProcess.kill('SIGTERM');
634
- }
1395
+ async function registerRuntimeSession(input) {
1396
+ return enqueueSessionMutation(input.workspaceRoot, async (workspaceRoot) => {
1397
+ const existing = await readRuntimeSession(getRuntimeSessionFilePath(workspaceRoot));
1398
+ const now = new Date().toISOString();
1399
+ const session = {
1400
+ schemaVersion: IWSDK_RUNTIME_STATE_SCHEMA_VERSION,
1401
+ sessionId: input.sessionId,
1402
+ workspaceRoot,
1403
+ pid: input.pid,
1404
+ port: input.port,
1405
+ localUrl: input.localUrl,
1406
+ networkUrls: input.networkUrls ?? [],
1407
+ aiMode: input.aiMode,
1408
+ browser: input.browser ?? existing?.browser,
1409
+ registeredAt: existing?.registeredAt ?? now,
1410
+ updatedAt: now,
1411
+ };
1412
+ traceRuntimeSession('register', {
1413
+ workspaceRoot,
1414
+ port: input.port,
1415
+ browserStatus: session.browser?.status ?? null,
1416
+ bridgeConnected: session.browser?.connected ?? false,
1417
+ commandReady: session.browser?.commandReady ?? false,
1418
+ });
1419
+ return writeRuntimeSession(workspaceRoot, session);
635
1420
  });
636
- warmupProcess.on('error', (error) => {
637
- if (verbose) {
638
- console.error('[RAG-MCP] Warmup error:', error.message);
1421
+ }
1422
+ async function setRuntimeSessionBrowserState(workspaceRoot, browser) {
1423
+ return enqueueSessionMutation(workspaceRoot, async (normalizedWorkspaceRoot) => {
1424
+ const existing = await readRuntimeSession(getRuntimeSessionFilePath(normalizedWorkspaceRoot));
1425
+ if (!existing) {
1426
+ return null;
639
1427
  }
1428
+ const session = {
1429
+ ...existing,
1430
+ browser,
1431
+ updatedAt: new Date().toISOString(),
1432
+ };
1433
+ traceRuntimeSession('set_browser_state', {
1434
+ workspaceRoot: normalizedWorkspaceRoot,
1435
+ browserStatus: browser.status,
1436
+ bridgeConnected: browser.connected,
1437
+ commandReady: browser.commandReady,
1438
+ connectedClientCount: browser.connectedClientCount,
1439
+ lastError: browser.lastError ?? null,
1440
+ });
1441
+ return writeRuntimeSession(normalizedWorkspaceRoot, session);
640
1442
  });
641
- warmupProcess.on('exit', (code) => {
642
- if (!initialized && code !== 0 && verbose) {
643
- console.warn(`[RAG-MCP] Warmup process exited with code ${code}`);
644
- }
1443
+ }
1444
+ async function unregisterRuntimeSession(workspaceRoot) {
1445
+ await enqueueSessionMutation(workspaceRoot, async (normalizedWorkspaceRoot) => {
1446
+ traceRuntimeSession('unregister', {
1447
+ workspaceRoot: normalizedWorkspaceRoot,
1448
+ });
1449
+ await rm(getRuntimeSessionFilePath(normalizedWorkspaceRoot), {
1450
+ force: true,
1451
+ }).catch(() => { });
645
1452
  });
646
- // Safety timeout - kill after 5 minutes if still running
647
- const warmupTimeout = setTimeout(() => {
648
- if (!initialized && !warmupProcess.killed) {
649
- console.warn('[RAG-MCP] Warmup timeout, killing process');
650
- warmupProcess.kill('SIGTERM');
651
- }
652
- }, 5 * 60 * 1000);
653
1453
  }
1454
+
1455
+ /**
1456
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1457
+ *
1458
+ * This source code is licensed under the MIT license found in the
1459
+ * LICENSE file in the root directory of this source tree.
1460
+ */
654
1461
  /**
655
1462
  * Derive internal headless / devUI / viewport settings from the AI mode.
656
1463
  */
@@ -694,7 +1501,6 @@ function processOptions(options = {}) {
694
1501
  };
695
1502
  processed.ai = {
696
1503
  mode,
697
- tools: options.ai.tools ?? ['claude'],
698
1504
  headless: settings.headless,
699
1505
  devUI: settings.devUI,
700
1506
  viewport: settings.fixedViewport ? screenshotSize : null,
@@ -749,10 +1555,75 @@ function iwsdkDev(options = {}) {
749
1555
  }
750
1556
  // Closure-scoped state for browser auto-recovery
751
1557
  let browserLaunchPromise = null;
1558
+ let browserCommandReadyPromise = null;
1559
+ let browserRuntimeClients = null;
752
1560
  let serverShuttingDown = false;
753
1561
  let browserUrl = '';
754
1562
  let consecutiveFailures = 0;
1563
+ let currentBrowserState = null;
755
1564
  const MAX_LAUNCH_FAILURES = 3;
1565
+ const BRIDGE_READY_TIMEOUT_MS = 5000;
1566
+ const traceEnabled = process.env.IWSDK_RUNTIME_TRACE === '1';
1567
+ const wsConnectionIds = new WeakMap();
1568
+ const wsConnectionKinds = new WeakMap();
1569
+ const traceRuntime = (event, details = {}) => {
1570
+ if (!traceEnabled) {
1571
+ return;
1572
+ }
1573
+ console.error(`[IWSDK-RUNTIME-TRACE][vite] ${event} ${JSON.stringify(details)}`);
1574
+ };
1575
+ const getConnectionId = (ws) => wsConnectionIds.get(ws) ?? 'unknown';
1576
+ const getConnectionKind = (ws) => wsConnectionKinds.get(ws) ?? 'command';
1577
+ const markConnectionKind = (ws, kind) => {
1578
+ wsConnectionKinds.set(ws, kind);
1579
+ };
1580
+ const createBrowserIssue = (cause, message) => ({
1581
+ cause,
1582
+ message,
1583
+ at: new Date().toISOString(),
1584
+ });
1585
+ const classifyBrowserLaunchFailure = (message) => /permission|not permitted|denied|sandbox|eacces|eperm/i.test(message)
1586
+ ? 'permission_denied'
1587
+ : 'browser_launch_failed';
1588
+ const createBrowserState = (status, options = {}, previous = currentBrowserState) => {
1589
+ const connectedClientCount = options.connectedClientCount ?? browserRuntimeClients?.size ?? 0;
1590
+ const connected = options.connected ?? status === 'connected';
1591
+ const commandReady = options.commandReady ?? false;
1592
+ return {
1593
+ status,
1594
+ connected,
1595
+ commandReady,
1596
+ connectedClientCount,
1597
+ lastTransitionAt: new Date().toISOString(),
1598
+ ...(options.lastBridgeConnectedAt ?? previous?.lastBridgeConnectedAt
1599
+ ? {
1600
+ lastBridgeConnectedAt: options.lastBridgeConnectedAt ??
1601
+ previous?.lastBridgeConnectedAt,
1602
+ }
1603
+ : {}),
1604
+ ...(options.lastCommandReadyAt ?? previous?.lastCommandReadyAt
1605
+ ? {
1606
+ lastCommandReadyAt: options.lastCommandReadyAt ??
1607
+ previous?.lastCommandReadyAt,
1608
+ }
1609
+ : {}),
1610
+ ...(options.lastError ? { lastError: options.lastError } : {}),
1611
+ };
1612
+ };
1613
+ currentBrowserState = createBrowserState('launching', { connected: false }, null);
1614
+ const publishBrowserState = (browser) => {
1615
+ currentBrowserState = browser;
1616
+ traceRuntime('browser_state', {
1617
+ status: browser.status,
1618
+ bridgeConnected: browser.connected,
1619
+ commandReady: browser.commandReady,
1620
+ connectedClientCount: browser.connectedClientCount,
1621
+ lastError: browser.lastError ?? null,
1622
+ });
1623
+ void setRuntimeSessionBrowserState(config.root, browser).catch((error) => {
1624
+ console.error('[IWSDK Dev] Failed to update browser state:', error);
1625
+ });
1626
+ };
756
1627
  /**
757
1628
  * Launch (or re-launch) the Playwright-managed browser.
758
1629
  * Guards against concurrent launches via `browserLaunchPromise`.
@@ -763,14 +1634,40 @@ function iwsdkDev(options = {}) {
763
1634
  return browserLaunchPromise;
764
1635
  }
765
1636
  browserLaunchPromise = (async () => {
1637
+ publishBrowserState(createBrowserState('launching'));
1638
+ traceRuntime('browser_launch_start', {
1639
+ browserUrl,
1640
+ headless: pluginOptions.ai.headless,
1641
+ });
766
1642
  try {
767
- const browser = await launchManagedBrowser(browserUrl, pluginOptions.ai.headless, pluginOptions.verbose, pluginOptions.ai.viewport, pluginOptions.ai.screenshotSize);
1643
+ const browser = await launchManagedBrowser(browserUrl, pluginOptions.ai.headless, pluginOptions.verbose, pluginOptions.ai.viewport, pluginOptions.ai.screenshotSize, traceEnabled);
768
1644
  managedBrowser = browser;
769
1645
  consecutiveFailures = 0;
1646
+ traceRuntime('browser_launch_success', {
1647
+ browserRuntimeClients: browserRuntimeClients?.size ?? 0,
1648
+ });
1649
+ publishBrowserState(createBrowserState((browserRuntimeClients?.size ?? 0) > 0
1650
+ ? 'connected'
1651
+ : 'waiting_for_connection', {
1652
+ connected: (browserRuntimeClients?.size ?? 0) > 0,
1653
+ commandReady: false,
1654
+ lastBridgeConnectedAt: (browserRuntimeClients?.size ?? 0) > 0
1655
+ ? new Date().toISOString()
1656
+ : undefined,
1657
+ }));
770
1658
  // On unexpected close, mark as null. The browser will be
771
1659
  // relaunched lazily on the next MCP request via ensureBrowser().
772
1660
  browser.onClose(() => {
773
1661
  managedBrowser = null;
1662
+ browserCommandReadyPromise = null;
1663
+ traceRuntime('browser_closed', {
1664
+ serverShuttingDown,
1665
+ });
1666
+ publishBrowserState(createBrowserState('disconnected', {
1667
+ connected: false,
1668
+ commandReady: false,
1669
+ lastError: createBrowserIssue('connection_lost', 'Managed browser closed unexpectedly. It will relaunch on the next MCP request.'),
1670
+ }));
774
1671
  if (!serverShuttingDown) {
775
1672
  console.log('🔄 IWSDK: Browser closed. Will relaunch on next MCP request.');
776
1673
  }
@@ -778,6 +1675,16 @@ function iwsdkDev(options = {}) {
778
1675
  }
779
1676
  catch (error) {
780
1677
  consecutiveFailures++;
1678
+ const message = error instanceof Error ? error.message : String(error);
1679
+ traceRuntime('browser_launch_failed', {
1680
+ consecutiveFailures,
1681
+ message,
1682
+ });
1683
+ publishBrowserState(createBrowserState('launch_failed', {
1684
+ connected: false,
1685
+ commandReady: false,
1686
+ lastError: createBrowserIssue(classifyBrowserLaunchFailure(message), message),
1687
+ }));
781
1688
  console.error('❌ IWSDK: Failed to launch browser:', error);
782
1689
  if (consecutiveFailures >= MAX_LAUNCH_FAILURES) {
783
1690
  console.error(`❌ IWSDK: ${MAX_LAUNCH_FAILURES} consecutive launch failures, giving up. ` +
@@ -798,17 +1705,111 @@ function iwsdkDev(options = {}) {
798
1705
  const ensureBrowser = async () => {
799
1706
  const current = managedBrowser;
800
1707
  if (current && !current.isClosed()) {
1708
+ traceRuntime('ensure_browser_reuse', {
1709
+ browserRuntimeClients: browserRuntimeClients?.size ?? 0,
1710
+ });
801
1711
  return { browser: current, relaunched: false };
802
1712
  }
803
1713
  managedBrowser = null;
804
1714
  if (consecutiveFailures >= MAX_LAUNCH_FAILURES) {
1715
+ traceRuntime('ensure_browser_aborted', {
1716
+ consecutiveFailures,
1717
+ });
805
1718
  return { browser: null, relaunched: false };
806
1719
  }
807
1720
  await launchBrowser();
1721
+ traceRuntime('ensure_browser_relaunch_result', {
1722
+ relaunched: managedBrowser !== null,
1723
+ browserRuntimeClients: browserRuntimeClients?.size ?? 0,
1724
+ });
808
1725
  return { browser: managedBrowser, relaunched: managedBrowser !== null };
809
1726
  };
1727
+ const waitForBridgeConnection = async (timeoutMs, reason) => {
1728
+ const startedAt = Date.now();
1729
+ traceRuntime('bridge_wait_start', {
1730
+ reason,
1731
+ timeoutMs,
1732
+ browserRuntimeClients: browserRuntimeClients?.size ?? 0,
1733
+ });
1734
+ while (Date.now() - startedAt < timeoutMs) {
1735
+ if ((browserRuntimeClients?.size ?? 0) > 0) {
1736
+ const waitedForBridgeMs = Date.now() - startedAt;
1737
+ traceRuntime('bridge_wait_ready', {
1738
+ reason,
1739
+ waitedForBridgeMs,
1740
+ });
1741
+ return waitedForBridgeMs;
1742
+ }
1743
+ await new Promise((resolve) => setTimeout(resolve, 100));
1744
+ }
1745
+ const waitedForBridgeMs = Date.now() - startedAt;
1746
+ traceRuntime('bridge_wait_timeout', {
1747
+ reason,
1748
+ waitedForBridgeMs,
1749
+ });
1750
+ return waitedForBridgeMs;
1751
+ };
1752
+ const ensureBrowserCommandReady = async (reason) => {
1753
+ if (browserCommandReadyPromise) {
1754
+ return browserCommandReadyPromise;
1755
+ }
1756
+ browserCommandReadyPromise = (async () => {
1757
+ const { browser, relaunched } = await ensureBrowser();
1758
+ if (!browser) {
1759
+ return {
1760
+ browser: null,
1761
+ relaunched: false,
1762
+ bridgeConnected: false,
1763
+ waitedForBridgeMs: 0,
1764
+ };
1765
+ }
1766
+ const needsBridgeWait = relaunched ||
1767
+ !currentBrowserState?.connected ||
1768
+ currentBrowserState?.commandReady === false;
1769
+ const waitedForBridgeMs = needsBridgeWait
1770
+ ? await waitForBridgeConnection(BRIDGE_READY_TIMEOUT_MS, reason)
1771
+ : 0;
1772
+ const bridgeConnected = (browserRuntimeClients?.size ?? 0) > 0;
1773
+ if (bridgeConnected) {
1774
+ publishBrowserState(createBrowserState('connected', {
1775
+ connected: true,
1776
+ commandReady: true,
1777
+ connectedClientCount: browserRuntimeClients.size,
1778
+ lastBridgeConnectedAt: currentBrowserState?.lastBridgeConnectedAt ??
1779
+ new Date().toISOString(),
1780
+ lastCommandReadyAt: new Date().toISOString(),
1781
+ }));
1782
+ }
1783
+ else {
1784
+ publishBrowserState(createBrowserState('waiting_for_connection', {
1785
+ connected: false,
1786
+ commandReady: false,
1787
+ connectedClientCount: 0,
1788
+ lastError: createBrowserIssue(relaunched ? 'browser_relaunched' : 'browser_not_ready', relaunched
1789
+ ? 'Browser relaunched and is waiting for the runtime bridge to reconnect.'
1790
+ : 'Managed browser bridge has not connected yet.'),
1791
+ }));
1792
+ }
1793
+ traceRuntime('browser_command_ready_result', {
1794
+ reason,
1795
+ relaunched,
1796
+ bridgeConnected,
1797
+ waitedForBridgeMs,
1798
+ });
1799
+ return {
1800
+ browser,
1801
+ relaunched,
1802
+ bridgeConnected,
1803
+ waitedForBridgeMs,
1804
+ };
1805
+ })().finally(() => {
1806
+ browserCommandReadyPromise = null;
1807
+ });
1808
+ return browserCommandReadyPromise;
1809
+ };
810
1810
  // Initialize WebSocket server and client tracking
811
1811
  mcpClients = new Set();
1812
+ browserRuntimeClients = new Set();
812
1813
  mcpWss = new WebSocketServer({ noServer: true });
813
1814
  // First-response-wins relay handler (extracted for testability)
814
1815
  const relay = createRelayHandler({
@@ -819,96 +1820,241 @@ function iwsdkDev(options = {}) {
819
1820
  relay.cleanStale(60000);
820
1821
  }, 60000);
821
1822
  relayCleanupInterval.unref();
1823
+ const BROWSER_RELAUNCHED_RESULT = {
1824
+ status: 'browser_relaunched',
1825
+ message: 'Browser was closed and has been relaunched. ' +
1826
+ 'The page state has been reset — please retry your request.',
1827
+ };
1828
+ const sendWsJson = (ws, payload, context) => {
1829
+ if (ws.readyState !== WebSocket.OPEN) {
1830
+ traceRuntime('ws_send_skipped', {
1831
+ connectionId: getConnectionId(ws),
1832
+ kind: getConnectionKind(ws),
1833
+ context,
1834
+ readyState: ws.readyState,
1835
+ });
1836
+ return;
1837
+ }
1838
+ traceRuntime('ws_send', {
1839
+ connectionId: getConnectionId(ws),
1840
+ kind: getConnectionKind(ws),
1841
+ context,
1842
+ id: payload.id ?? null,
1843
+ });
1844
+ ws.send(JSON.stringify(payload));
1845
+ };
1846
+ const sendUnavailableBrowser = (ws, requestId, context) => {
1847
+ sendWsJson(ws, {
1848
+ id: requestId,
1849
+ error: createUnavailableBrowserRpcError(currentBrowserState),
1850
+ }, context);
1851
+ };
1852
+ const sendInternalError = (ws, requestId, error, context) => {
1853
+ sendWsJson(ws, {
1854
+ id: requestId,
1855
+ error: {
1856
+ code: -32e3,
1857
+ message: error instanceof Error ? error.message : String(error),
1858
+ },
1859
+ }, context);
1860
+ };
1861
+ const createBrowserProbeResult = (waitedForBridgeMs) => ({
1862
+ bridgeConnected: Boolean(currentBrowserState?.connected),
1863
+ commandReady: Boolean(currentBrowserState?.commandReady),
1864
+ waitedForBridgeMs,
1865
+ browser: currentBrowserState ??
1866
+ createBrowserState('launching', {
1867
+ connected: false,
1868
+ commandReady: false,
1869
+ }),
1870
+ });
822
1871
  mcpWss.on('connection', (ws) => {
1872
+ const connectionId = randomUUID();
1873
+ wsConnectionIds.set(ws, connectionId);
1874
+ markConnectionKind(ws, 'command');
823
1875
  mcpClients.add(ws);
1876
+ traceRuntime('ws_connected', {
1877
+ connectionId,
1878
+ kind: getConnectionKind(ws),
1879
+ });
824
1880
  if (pluginOptions.verbose) {
825
1881
  console.log('[IWSDK-MCP] Client connected');
826
1882
  }
827
1883
  ws.on('message', async (data) => {
828
1884
  const message = data.toString();
1885
+ traceRuntime('ws_message', {
1886
+ connectionId,
1887
+ kind: getConnectionKind(ws),
1888
+ bytes: data.length,
1889
+ });
829
1890
  if (pluginOptions.verbose) {
830
1891
  console.log('[IWSDK-MCP] Message received:', message.substring(0, 100));
831
1892
  }
832
- // Intercept server-side tools that use Playwright directly.
833
- // These respond from the Node process without a browser round-trip.
834
1893
  let intercepted = false;
835
1894
  try {
836
1895
  const parsed = JSON.parse(message);
837
- const BROWSER_RELAUNCHED_RESULT = {
838
- status: 'browser_relaunched',
839
- message: 'Browser was closed and has been relaunched. ' +
840
- 'The page state has been reset — please retry your request.',
841
- };
842
- // Console logs: Playwright captures via CDP
843
- if (parsed.method === 'get_console_logs' && parsed.id) {
1896
+ if (parsed?.type === 'iwsdk_browser_hello') {
844
1897
  intercepted = true;
845
- const { browser, relaunched } = await ensureBrowser();
846
- if (relaunched) {
847
- ws.send(JSON.stringify({
848
- id: parsed.id,
849
- result: BROWSER_RELAUNCHED_RESULT,
1898
+ markConnectionKind(ws, 'bridge');
1899
+ if (!browserRuntimeClients.has(ws)) {
1900
+ browserRuntimeClients.add(ws);
1901
+ publishBrowserState(createBrowserState('connected', {
1902
+ connected: true,
1903
+ commandReady: false,
1904
+ connectedClientCount: browserRuntimeClients.size,
1905
+ lastBridgeConnectedAt: new Date().toISOString(),
850
1906
  }));
851
1907
  }
852
- else {
853
- const params = parsed.params ?? {};
854
- if (!params.level) {
855
- params.level = ['log', 'info', 'warn', 'error'];
1908
+ traceRuntime('bridge_hello', {
1909
+ connectionId,
1910
+ tabId: parsed.tabId ?? null,
1911
+ tabGeneration: parsed.tabGeneration ?? null,
1912
+ connectedClientCount: browserRuntimeClients.size,
1913
+ });
1914
+ return;
1915
+ }
1916
+ if (parsed.method === INTERNAL_BROWSER_PROBE_METHOD &&
1917
+ typeof parsed.id === 'string') {
1918
+ intercepted = true;
1919
+ traceRuntime('probe_request', {
1920
+ connectionId,
1921
+ requestId: parsed.id,
1922
+ });
1923
+ try {
1924
+ const readiness = await ensureBrowserCommandReady('internal_browser_probe');
1925
+ if (!readiness.browser || !readiness.bridgeConnected) {
1926
+ sendUnavailableBrowser(ws, parsed.id, 'probe_unavailable');
1927
+ }
1928
+ else {
1929
+ sendWsJson(ws, {
1930
+ id: parsed.id,
1931
+ result: createBrowserProbeResult(readiness.waitedForBridgeMs),
1932
+ }, 'probe_ready');
856
1933
  }
857
- const result = browser ? browser.queryLogs(params) : [];
858
- ws.send(JSON.stringify({ id: parsed.id, result }));
859
1934
  }
1935
+ catch (error) {
1936
+ sendInternalError(ws, parsed.id, error, 'probe_error');
1937
+ }
1938
+ return;
860
1939
  }
861
- // Screenshot: Playwright captures via CDP compositor
862
- if (!intercepted && parsed.method === 'screenshot' && parsed.id) {
1940
+ if (parsed.method === 'get_console_logs' && typeof parsed.id === 'string') {
863
1941
  intercepted = true;
864
1942
  try {
865
- const { browser, relaunched } = await ensureBrowser();
866
- if (relaunched) {
867
- ws.send(JSON.stringify({
1943
+ const readiness = await ensureBrowserCommandReady('get_console_logs');
1944
+ if (!readiness.browser || !readiness.bridgeConnected) {
1945
+ sendUnavailableBrowser(ws, parsed.id, 'console_logs_unavailable');
1946
+ return;
1947
+ }
1948
+ if (readiness.relaunched) {
1949
+ const tab = await readiness.browser.getTabMetadata();
1950
+ sendWsJson(ws, {
868
1951
  id: parsed.id,
869
1952
  result: BROWSER_RELAUNCHED_RESULT,
870
- }));
1953
+ ...(tab.id
1954
+ ? {
1955
+ _tabId: tab.id,
1956
+ _tabGeneration: tab.generation ?? undefined,
1957
+ }
1958
+ : {}),
1959
+ }, 'console_logs_relaunched');
1960
+ return;
871
1961
  }
872
- else if (browser) {
873
- const buffer = await browser.screenshot();
874
- const base64 = buffer.toString('base64');
875
- ws.send(JSON.stringify({
876
- id: parsed.id,
877
- result: { imageData: base64, mimeType: 'image/png' },
878
- }));
1962
+ const params = parsed.params ?? {};
1963
+ if (!params.level) {
1964
+ params.level = ['log', 'info', 'warn', 'error'];
879
1965
  }
880
- else {
881
- ws.send(JSON.stringify({
1966
+ const tab = await readiness.browser.getTabMetadata();
1967
+ sendWsJson(ws, {
1968
+ id: parsed.id,
1969
+ result: readiness.browser.queryLogs(params),
1970
+ ...(tab.id
1971
+ ? {
1972
+ _tabId: tab.id,
1973
+ _tabGeneration: tab.generation ?? undefined,
1974
+ }
1975
+ : {}),
1976
+ }, 'console_logs_result');
1977
+ }
1978
+ catch (error) {
1979
+ sendInternalError(ws, parsed.id, error, 'console_logs_error');
1980
+ }
1981
+ return;
1982
+ }
1983
+ if (parsed.method === 'screenshot' && typeof parsed.id === 'string') {
1984
+ intercepted = true;
1985
+ try {
1986
+ const readiness = await ensureBrowserCommandReady('screenshot');
1987
+ if (!readiness.browser || !readiness.bridgeConnected) {
1988
+ sendUnavailableBrowser(ws, parsed.id, 'screenshot_unavailable');
1989
+ return;
1990
+ }
1991
+ if (readiness.relaunched) {
1992
+ sendWsJson(ws, {
882
1993
  id: parsed.id,
883
- error: { code: -32000, message: 'Browser not ready' },
884
- }));
1994
+ result: BROWSER_RELAUNCHED_RESULT,
1995
+ }, 'screenshot_relaunched');
1996
+ return;
885
1997
  }
886
- }
887
- catch (err) {
888
- ws.send(JSON.stringify({
1998
+ const buffer = await readiness.browser.screenshot();
1999
+ const base64 = buffer.toString('base64');
2000
+ sendWsJson(ws, {
889
2001
  id: parsed.id,
890
- error: {
891
- code: -32000,
892
- message: err instanceof Error ? err.message : String(err),
893
- },
894
- }));
2002
+ result: { imageData: base64, mimeType: 'image/png' },
2003
+ }, 'screenshot_result');
2004
+ }
2005
+ catch (error) {
2006
+ sendInternalError(ws, parsed.id, error, 'screenshot_error');
895
2007
  }
2008
+ return;
896
2009
  }
897
2010
  }
898
- catch {
899
- // Not JSON — fall through to relay
2011
+ catch (error) {
2012
+ traceRuntime('ws_message_parse_fallthrough', {
2013
+ connectionId,
2014
+ kind: getConnectionKind(ws),
2015
+ message: error instanceof Error ? error.message : 'non_json_message',
2016
+ });
900
2017
  }
901
2018
  if (!intercepted) {
902
2019
  relay.onMessage(ws, message, mcpClients);
903
2020
  }
904
2021
  });
905
- ws.on('close', () => {
2022
+ ws.on('close', (code, reasonBuffer) => {
2023
+ const kind = getConnectionKind(ws);
2024
+ const reason = typeof reasonBuffer === 'string'
2025
+ ? reasonBuffer
2026
+ : reasonBuffer.toString('utf8');
906
2027
  mcpClients.delete(ws);
2028
+ const removedBridge = browserRuntimeClients.delete(ws);
2029
+ if (removedBridge) {
2030
+ browserCommandReadyPromise = null;
2031
+ publishBrowserState(createBrowserState(browserRuntimeClients.size > 0 ? 'connected' : 'disconnected', {
2032
+ connected: browserRuntimeClients.size > 0,
2033
+ commandReady: false,
2034
+ connectedClientCount: browserRuntimeClients.size,
2035
+ lastError: browserRuntimeClients.size > 0
2036
+ ? undefined
2037
+ : createBrowserIssue('connection_lost', 'Managed browser runtime disconnected from the MCP bridge.'),
2038
+ }));
2039
+ }
2040
+ traceRuntime('ws_closed', {
2041
+ connectionId,
2042
+ kind,
2043
+ code,
2044
+ reason,
2045
+ removedBridge,
2046
+ browserRuntimeClients: browserRuntimeClients.size,
2047
+ });
907
2048
  if (pluginOptions.verbose) {
908
2049
  console.log('[IWSDK-MCP] Client disconnected');
909
2050
  }
910
2051
  });
911
2052
  ws.on('error', (error) => {
2053
+ traceRuntime('ws_error', {
2054
+ connectionId,
2055
+ kind: getConnectionKind(ws),
2056
+ message: error instanceof Error ? error.message : String(error),
2057
+ });
912
2058
  if (pluginOptions.verbose) {
913
2059
  console.error('[IWSDK-MCP] WebSocket error:', error);
914
2060
  }
@@ -919,6 +2065,10 @@ function iwsdkDev(options = {}) {
919
2065
  if (request.url !== '/__iwer_mcp') {
920
2066
  return;
921
2067
  }
2068
+ traceRuntime('ws_upgrade', {
2069
+ url: request.url,
2070
+ remoteAddress: request.socket.remoteAddress ?? null,
2071
+ });
922
2072
  if (pluginOptions.verbose) {
923
2073
  console.log('[IWSDK-MCP] WebSocket upgrade request received');
924
2074
  }
@@ -929,15 +2079,8 @@ function iwsdkDev(options = {}) {
929
2079
  if (pluginOptions.verbose) {
930
2080
  console.log('🔌 IWSDK-MCP: WebSocket endpoint registered at /__iwer_mcp');
931
2081
  }
932
- // Generate MCP config files for selected AI tools after server starts
933
- // We wait for the 'listening' event to get the actual port (in case configured port was busy)
934
- // Find the path to the MCP server script
935
- // It's installed in node_modules/@iwsdk/vite-plugin-dev/dist/mcp-server.js
936
- const mcpServerPath = path.join(config.root, 'node_modules', '@iwsdk', 'vite-plugin-dev', 'dist', 'mcp-server.js');
937
- // Find the path to the RAG MCP server
938
- const ragMcpServerPath = path.join(config.root, 'node_modules', '@felixtz', 'iwsdk-rag-mcp', 'dist', 'index.js');
939
- // Check if hzdb is installed (for MCP config — telemetry uses npx and fails silently)
940
- const hzdbInstalled = existsSync(path.join(config.root, 'node_modules', '@meta-quest', 'hzdb'));
2082
+ // Register the project-local runtime session after server start.
2083
+ // Waiting for 'listening' lets us record Vite's actual chosen port.
941
2084
  // Resolve IWSDK version for telemetry attribution
942
2085
  let iwsdkVersion;
943
2086
  try {
@@ -951,85 +2094,42 @@ function iwsdkDev(options = {}) {
951
2094
  // Session tracking for telemetry
952
2095
  const sessionId = randomUUID();
953
2096
  const sessionStartTime = Date.now();
954
- const writeMcpConfigs = async (actualPort) => {
955
- const mcpServerArgs = [mcpServerPath, '--port', String(actualPort)];
956
- if (iwsdkVersion) {
957
- mcpServerArgs.push('--client-version', iwsdkVersion);
958
- }
959
- // Build the full set of all possible managed entries, then remove
960
- // those whose packages aren't installed. The full key list is passed
961
- // as managedKeys so mergeJsonConfig can clean up stale entries from
962
- // previous runs where a package was present but has since been removed.
963
- const serverEntries = {
964
- 'iwsdk-dev-mcp': {
965
- command: 'node',
966
- args: mcpServerArgs,
967
- },
968
- 'iwsdk-rag-local': existsSync(ragMcpServerPath)
969
- ? { command: 'node', args: [ragMcpServerPath] }
970
- : undefined,
971
- hzdb: hzdbInstalled
972
- ? { command: 'npx', args: ['@meta-quest/hzdb', 'mcp', 'server'] }
973
- : undefined,
974
- };
975
- const managedKeys = Object.keys(serverEntries);
976
- const activeEntries = {};
977
- for (const [key, value] of Object.entries(serverEntries)) {
978
- if (value) {
979
- activeEntries[key] = value;
980
- }
981
- }
982
- const tools = pluginOptions.ai.tools;
983
- const writes = [];
984
- for (const tool of tools) {
985
- const target = MCP_CONFIG_TARGETS[tool];
986
- const filePath = path.join(config.root, target.file);
987
- if (target.format === 'json') {
988
- writes.push(mergeJsonConfig(filePath, activeEntries, target.jsonKey, managedKeys));
989
- }
990
- else {
991
- writes.push(mergeTomlConfig(filePath, activeEntries));
992
- }
993
- }
994
- const results = await Promise.allSettled(writes);
995
- const failures = results.filter((r) => r.status === 'rejected');
996
- if (failures.length > 0) {
997
- for (const f of failures) {
998
- console.error('[MCP] Config write failed:', f.reason);
999
- }
1000
- }
1001
- else if (pluginOptions.verbose) {
1002
- const toolNames = tools.join(', ');
1003
- console.log(`📝 MCP: Generated config files for [${toolNames}] (port: ${actualPort})`);
1004
- }
1005
- };
1006
2097
  // Wait for server to start listening to get the actual port
1007
- server.httpServer?.on('listening', () => {
2098
+ server.httpServer?.on('listening', async () => {
1008
2099
  const address = server.httpServer?.address();
1009
2100
  const actualPort = typeof address === 'object' && address
1010
2101
  ? address.port
1011
2102
  : server.config.server.port || 5173;
1012
- writeMcpConfigs(actualPort);
2103
+ const protocol = server.config.server.https ? 'https' : 'http';
2104
+ browserUrl = `${protocol}://localhost:${actualPort}`;
2105
+ try {
2106
+ await registerRuntimeSession({
2107
+ sessionId,
2108
+ workspaceRoot: config.root,
2109
+ pid: process.pid,
2110
+ port: actualPort,
2111
+ localUrl: server.resolvedUrls?.local?.[0] ?? browserUrl,
2112
+ networkUrls: server.resolvedUrls?.network ?? [],
2113
+ aiMode: pluginOptions.ai?.mode,
2114
+ browser: currentBrowserState ?? undefined,
2115
+ });
2116
+ }
2117
+ catch (error) {
2118
+ console.error('[IWSDK Dev] Failed to register runtime session:', error);
2119
+ }
1013
2120
  // Report session start to hzdb telemetry (fire-and-forget via npx)
1014
2121
  reportSessionStart(sessionId, {
1015
2122
  iwsdkVersion,
1016
2123
  clientVersion: iwsdkVersion,
1017
2124
  port: actualPort,
1018
2125
  });
1019
- // Warm up RAG MCP server (downloads embedding model if needed)
1020
- // This ensures the model is cached before Claude Code tries to use it
1021
- warmupRagMcp(ragMcpServerPath, pluginOptions.verbose);
1022
2126
  // Launch Playwright-managed browser
1023
- const protocol = server.config.server.https ? 'https' : 'http';
1024
- browserUrl = `${protocol}://localhost:${actualPort}`;
1025
2127
  launchBrowser();
1026
2128
  });
1027
2129
  // Clean up WebSocket server and browser when Vite server closes.
1028
- // MCP config files (.mcp.json, .cursor/mcp.json, etc.) are intentionally
1029
- // left in place — they are harmless when the dev server isn't running and
1030
- // will be overwritten with fresh values on the next `npm run dev`.
1031
2130
  server.httpServer?.on('close', () => {
1032
2131
  serverShuttingDown = true;
2132
+ void unregisterRuntimeSession(config.root);
1033
2133
  reportSessionEnd(sessionId, {
1034
2134
  durationMs: Date.now() - sessionStartTime,
1035
2135
  reason: 'user_closed',
@@ -1141,5 +2241,5 @@ function iwsdkDev(options = {}) {
1141
2241
  /** @deprecated Use `iwsdkDev` instead */
1142
2242
  const injectIWER = iwsdkDev;
1143
2243
 
1144
- export { injectIWER, iwsdkDev, mergeJsonConfig, mergeTomlConfig, unmergeJsonConfig, unmergeTomlConfig };
2244
+ export { injectIWER, iwsdkDev };
1145
2245
  //# sourceMappingURL=index.js.map