@iwsdk/cli 0.5.3 → 1.0.0-rc.0

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 (39) hide show
  1. package/README.md +62 -1
  2. package/bin/iwsdk.js +1 -1
  3. package/dist/browser-lease.d.ts +14 -0
  4. package/dist/browser-lease.d.ts.map +1 -0
  5. package/dist/cli-types.d.ts +1 -1
  6. package/dist/cli-types.d.ts.map +1 -1
  7. package/dist/cli.js +2811 -485
  8. package/dist/cli.js.map +1 -1
  9. package/dist/commands/browser.d.ts +14 -0
  10. package/dist/commands/browser.d.ts.map +1 -0
  11. package/dist/commands/dev.d.ts +6 -2
  12. package/dist/commands/dev.d.ts.map +1 -1
  13. package/dist/commands/runtime.d.ts.map +1 -1
  14. package/dist/commands/status.d.ts.map +1 -1
  15. package/dist/contract.js +481 -30
  16. package/dist/contract.js.map +1 -1
  17. package/dist/help.d.ts +1 -0
  18. package/dist/help.d.ts.map +1 -1
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +2813 -487
  21. package/dist/index.js.map +1 -1
  22. package/dist/mcp-stdio.d.ts.map +1 -1
  23. package/dist/runtime-contract.d.ts +70 -1
  24. package/dist/runtime-contract.d.ts.map +1 -1
  25. package/dist/runtime-files.d.ts +19 -0
  26. package/dist/runtime-files.d.ts.map +1 -0
  27. package/dist/runtime-files.js +318 -0
  28. package/dist/runtime-files.js.map +1 -0
  29. package/dist/runtime-owner.d.ts +50 -0
  30. package/dist/runtime-owner.d.ts.map +1 -0
  31. package/dist/runtime-owner.js +539 -0
  32. package/dist/runtime-owner.js.map +1 -0
  33. package/dist/runtime-state.d.ts +20 -18
  34. package/dist/runtime-state.d.ts.map +1 -1
  35. package/dist/runtime-transport.d.ts.map +1 -1
  36. package/dist/screenshot-output.d.ts +13 -0
  37. package/dist/screenshot-output.d.ts.map +1 -0
  38. package/guidance/AGENTS.md +96 -37
  39. package/package.json +16 -2
package/dist/cli.js CHANGED
@@ -1,21 +1,22 @@
1
1
  #!/usr/bin/env node
2
2
  import { existsSync, realpathSync, readFileSync, openSync, closeSync } from 'fs';
3
- import { readFile, mkdir, writeFile, rm, unlink, copyFile } from 'fs/promises';
3
+ import { mkdir, mkdtemp, writeFile, readdir, rename, unlink, rmdir, rm, readFile, copyFile } from 'fs/promises';
4
4
  import path from 'path';
5
- import require$$7, { fileURLToPath } from 'url';
6
- import { spawn } from 'child_process';
5
+ import require$$7, { fileURLToPath, pathToFileURL } from 'url';
6
+ import { execFileSync, spawn } from 'child_process';
7
+ import require$$1, { randomUUID, createHash as createHash$2 } from 'crypto';
8
+ import require$$3$1, { createConnection } from 'net';
9
+ import { createRequire } from 'module';
7
10
  import require$$0$3 from 'events';
8
11
  import require$$1$1 from 'https';
9
12
  import require$$2$1 from 'http';
10
- import require$$3$1 from 'net';
11
13
  import require$$4 from 'tls';
12
- import require$$1 from 'crypto';
13
14
  import require$$0$2 from 'stream';
14
15
  import require$$0 from 'zlib';
15
16
  import require$$0$1 from 'buffer';
16
17
  import require$$2 from 'util';
17
18
  import process$2 from 'node:process';
18
- import { createRequire } from 'module';
19
+ import { randomUUID as randomUUID$1 } from 'node:crypto';
19
20
  import os from 'os';
20
21
 
21
22
  function getDefaultExportFromCjs (x) {
@@ -2517,9 +2518,25 @@ var mcpSurfaceMarkers = {
2517
2518
  */
2518
2519
  const DEFAULT_RUNTIME_COMMAND_TIMEOUT_MS = 30_000;
2519
2520
  const UI_RENDER_PREVIEW_TIMEOUT_MS = 60_000;
2521
+ const ASSET_RENDER_PREVIEW_TIMEOUT_MS = 120_000;
2522
+ const BROWSER_RUNTIME_COMMAND_TIMEOUT_MS = 60_000;
2523
+ const BROWSER_RUNTIME_METHODS = new Set([
2524
+ 'browser_interact',
2525
+ 'browser_profile',
2526
+ 'browser_snapshot',
2527
+ 'get_console_logs',
2528
+ 'reload_page',
2529
+ 'screenshot',
2530
+ ]);
2520
2531
  function getDefaultRuntimeCommandTimeoutMs(method) {
2521
- return method === 'ui_render_preview'
2522
- ? UI_RENDER_PREVIEW_TIMEOUT_MS
2532
+ if (method === 'asset_render_preview') {
2533
+ return ASSET_RENDER_PREVIEW_TIMEOUT_MS;
2534
+ }
2535
+ if (method === 'ui_render_preview') {
2536
+ return UI_RENDER_PREVIEW_TIMEOUT_MS;
2537
+ }
2538
+ return BROWSER_RUNTIME_METHODS.has(method)
2539
+ ? BROWSER_RUNTIME_COMMAND_TIMEOUT_MS
2523
2540
  : DEFAULT_RUNTIME_COMMAND_TIMEOUT_MS;
2524
2541
  }
2525
2542
  function describeValue(value) {
@@ -2599,10 +2616,13 @@ function assertSchemaValue(value, schema, path) {
2599
2616
  throw new Error(`${path} must be at most ${schema.maximum}`);
2600
2617
  }
2601
2618
  }
2602
- if (typeof value === 'string' &&
2603
- schema.pattern &&
2604
- !new RegExp(schema.pattern).test(value)) {
2605
- throw new Error(`${path} must match ${schema.pattern}`);
2619
+ if (typeof value === 'string') {
2620
+ if (schema.maxLength != null && value.length > schema.maxLength) {
2621
+ throw new Error(`${path} allows at most ${schema.maxLength} characters`);
2622
+ }
2623
+ if (schema.pattern && !new RegExp(schema.pattern).test(value)) {
2624
+ throw new Error(`${path} must match ${schema.pattern}`);
2625
+ }
2606
2626
  }
2607
2627
  if (Array.isArray(value)) {
2608
2628
  if (schema.minItems != null && value.length < schema.minItems) {
@@ -2646,6 +2666,8 @@ const IWSDK_RUNTIME_LAUNCH_PATH = '.iwsdk/runtime/launch.json';
2646
2666
  const IWSDK_RUNTIME_STATE_SCHEMA_VERSION = 2;
2647
2667
  const IWSDK_RUNTIME_BROWSER_READY_SCHEMA_VERSION = 2;
2648
2668
  const INTERNAL_BROWSER_PROBE_METHOD = '__iwsdk_browser_probe';
2669
+ const INTERNAL_RUNTIME_SHUTDOWN_METHOD = '__iwsdk_runtime_shutdown';
2670
+ const INTERNAL_RUNTIME_LAUNCH_CLAIM_ENV = 'IWSDK_DEV_LAUNCH_CLAIM_ID';
2649
2671
  function hasRuntimeBrowserCommandReadyContract(session) {
2650
2672
  if (!session?.browser) {
2651
2673
  return false;
@@ -3368,14 +3390,234 @@ const ALL_RUNTIME_MCP_TOOLS = [
3368
3390
  // =============================================================================
3369
3391
  {
3370
3392
  name: 'browser_screenshot',
3371
- description: 'Capture the managed application runtime. If the workspace editor is visible, switches to the runtime before capturing.',
3393
+ description: 'Capture the current application in the managed browser, persist the image locally, and return screenshotPath with capture metadata. The application surface is resolved automatically.',
3372
3394
  inputSchema: {
3373
3395
  type: 'object',
3374
- properties: {},
3396
+ properties: {
3397
+ format: {
3398
+ type: 'string',
3399
+ enum: ['png', 'jpeg'],
3400
+ description: 'Image format. Defaults to png.',
3401
+ },
3402
+ quality: {
3403
+ type: 'number',
3404
+ minimum: 20,
3405
+ maximum: 100,
3406
+ description: 'JPEG quality. Ignored for PNG.',
3407
+ },
3408
+ fullPage: {
3409
+ type: 'boolean',
3410
+ description: 'Capture the full application document when it fits the bounded 32-megapixel and 64-tile limits.',
3411
+ },
3412
+ ref: {
3413
+ type: 'string',
3414
+ description: 'Capture one fully visible element ref returned by browser_snapshot. Targets larger than the application viewport are rejected as non-retryable.',
3415
+ },
3416
+ },
3375
3417
  required: [],
3376
3418
  additionalProperties: false,
3377
3419
  },
3378
3420
  },
3421
+ {
3422
+ name: 'browser_snapshot',
3423
+ description: 'Inspect the current application as a compact accessibility-first list of interactive elements and canvas regions. Use returned refs with browser_interact.',
3424
+ inputSchema: {
3425
+ type: 'object',
3426
+ additionalProperties: false,
3427
+ properties: {
3428
+ maxNodes: {
3429
+ type: 'integer',
3430
+ minimum: 1,
3431
+ maximum: 1000,
3432
+ description: 'Maximum returned elements. Defaults to 200.',
3433
+ },
3434
+ maxTextLength: {
3435
+ type: 'integer',
3436
+ minimum: 16,
3437
+ maximum: 1000,
3438
+ description: 'Maximum text/name length per element. Defaults to 200.',
3439
+ },
3440
+ rootRef: {
3441
+ type: 'string',
3442
+ description: 'Optional existing ref used as the snapshot root.',
3443
+ },
3444
+ },
3445
+ },
3446
+ },
3447
+ {
3448
+ name: 'browser_interact',
3449
+ description: 'Perform up to 10 trusted Playwright actions against the current application. Prefer refs from browser_snapshot; use coordinates for canvas input. Hold keys within one batch with keyDown, wait, and keyUp; keyDown and keyUp focus an optional ref or locator, and any held keys are released when the batch ends. This tool does not navigate to arbitrary URLs.',
3450
+ inputSchema: {
3451
+ type: 'object',
3452
+ additionalProperties: false,
3453
+ properties: {
3454
+ timeoutMs: {
3455
+ type: 'integer',
3456
+ minimum: 100,
3457
+ maximum: 12000,
3458
+ description: 'Total timeout budget for the complete batch. Defaults to 10000 and is capped at 12000 so workspace restoration completes before the host command deadline.',
3459
+ },
3460
+ steps: {
3461
+ type: 'array',
3462
+ minItems: 1,
3463
+ maxItems: 10,
3464
+ items: {
3465
+ type: 'object',
3466
+ additionalProperties: false,
3467
+ properties: {
3468
+ action: {
3469
+ type: 'string',
3470
+ enum: [
3471
+ 'click',
3472
+ 'doubleClick',
3473
+ 'hover',
3474
+ 'pointerMove',
3475
+ 'pointerDown',
3476
+ 'pointerUp',
3477
+ 'wheel',
3478
+ 'fill',
3479
+ 'type',
3480
+ 'clear',
3481
+ 'press',
3482
+ 'keyDown',
3483
+ 'keyUp',
3484
+ 'check',
3485
+ 'uncheck',
3486
+ 'select',
3487
+ 'scroll',
3488
+ 'drag',
3489
+ 'wait',
3490
+ ],
3491
+ },
3492
+ ref: { type: 'string' },
3493
+ targetRef: { type: 'string' },
3494
+ locator: {
3495
+ type: 'object',
3496
+ additionalProperties: false,
3497
+ properties: {
3498
+ role: { type: 'string' },
3499
+ name: { type: 'string' },
3500
+ testId: { type: 'string' },
3501
+ text: { type: 'string' },
3502
+ },
3503
+ },
3504
+ targetLocator: {
3505
+ type: 'object',
3506
+ additionalProperties: false,
3507
+ properties: {
3508
+ role: { type: 'string' },
3509
+ name: { type: 'string' },
3510
+ testId: { type: 'string' },
3511
+ text: { type: 'string' },
3512
+ },
3513
+ },
3514
+ point: {
3515
+ type: 'object',
3516
+ additionalProperties: false,
3517
+ properties: {
3518
+ x: { type: 'number' },
3519
+ y: { type: 'number' },
3520
+ canvasRef: { type: 'string' },
3521
+ },
3522
+ required: ['x', 'y'],
3523
+ },
3524
+ targetPoint: {
3525
+ type: 'object',
3526
+ additionalProperties: false,
3527
+ properties: {
3528
+ x: { type: 'number' },
3529
+ y: { type: 'number' },
3530
+ canvasRef: { type: 'string' },
3531
+ },
3532
+ required: ['x', 'y'],
3533
+ },
3534
+ button: {
3535
+ type: 'string',
3536
+ enum: ['left', 'middle', 'right'],
3537
+ },
3538
+ key: {
3539
+ type: 'string',
3540
+ maxLength: 100,
3541
+ description: 'Keyboard key for press, keyDown, or keyUp. Keys held by keyDown are scoped to this batch and released automatically at the end.',
3542
+ },
3543
+ durationMs: {
3544
+ type: 'integer',
3545
+ minimum: 0,
3546
+ maximum: 12000,
3547
+ description: 'For wait, pause for this duration within the batch timeout.',
3548
+ },
3549
+ value: { type: 'string' },
3550
+ values: { type: 'array', items: { type: 'string' } },
3551
+ text: { type: 'string' },
3552
+ path: {
3553
+ type: 'string',
3554
+ description: 'For wait, the expected application pathname, search, and hash.',
3555
+ },
3556
+ loadState: {
3557
+ type: 'string',
3558
+ enum: ['domcontentloaded', 'load', 'networkidle'],
3559
+ description: 'For wait, the application load state to await.',
3560
+ },
3561
+ state: {
3562
+ type: 'string',
3563
+ enum: [
3564
+ 'attached',
3565
+ 'checked',
3566
+ 'detached',
3567
+ 'disabled',
3568
+ 'editable',
3569
+ 'enabled',
3570
+ 'focused',
3571
+ 'hidden',
3572
+ 'unchecked',
3573
+ 'visible',
3574
+ ],
3575
+ },
3576
+ deltaX: { type: 'number' },
3577
+ deltaY: { type: 'number' },
3578
+ timeoutMs: {
3579
+ type: 'integer',
3580
+ minimum: 100,
3581
+ maximum: 12000,
3582
+ },
3583
+ },
3584
+ required: ['action'],
3585
+ },
3586
+ },
3587
+ },
3588
+ required: ['steps'],
3589
+ },
3590
+ },
3591
+ {
3592
+ name: 'browser_profile',
3593
+ description: 'Start, stop, or inspect a bounded uncalibrated desktop-browser performance profile for the current application.',
3594
+ inputSchema: {
3595
+ type: 'object',
3596
+ additionalProperties: false,
3597
+ properties: {
3598
+ action: {
3599
+ type: 'string',
3600
+ enum: ['start', 'status', 'stop'],
3601
+ },
3602
+ mode: {
3603
+ type: 'string',
3604
+ enum: ['interaction', 'rendering', 'trace'],
3605
+ description: 'Profile mode used when action is start.',
3606
+ },
3607
+ maxDurationMs: {
3608
+ type: 'integer',
3609
+ minimum: 1000,
3610
+ maximum: 60000,
3611
+ description: 'Safety auto-stop duration. Defaults to 30000.',
3612
+ },
3613
+ profileId: {
3614
+ type: 'string',
3615
+ description: 'Optional profile ID precondition for stop.',
3616
+ },
3617
+ },
3618
+ required: ['action'],
3619
+ },
3620
+ },
3379
3621
  // =============================================================================
3380
3622
  // Device State
3381
3623
  // =============================================================================
@@ -3494,19 +3736,21 @@ const ALL_RUNTIME_MCP_TOOLS = [
3494
3736
  properties: {
3495
3737
  count: {
3496
3738
  type: 'number',
3497
- description: 'Maximum number of logs to return (most recent N)',
3739
+ minimum: 1,
3740
+ maximum: 200,
3741
+ description: 'Maximum number of logs to return (most recent N). Defaults to 100 and is capped at 200.',
3498
3742
  },
3499
3743
  level: {
3500
3744
  oneOf: [
3501
3745
  {
3502
3746
  type: 'string',
3503
- enum: ['log', 'info', 'warn', 'error', 'debug'],
3747
+ enum: ['log', 'info', 'warn', 'error', 'debug', 'trace'],
3504
3748
  },
3505
3749
  {
3506
3750
  type: 'array',
3507
3751
  items: {
3508
3752
  type: 'string',
3509
- enum: ['log', 'info', 'warn', 'error', 'debug'],
3753
+ enum: ['log', 'info', 'warn', 'error', 'debug', 'trace'],
3510
3754
  },
3511
3755
  },
3512
3756
  ],
@@ -3603,7 +3847,7 @@ const ALL_RUNTIME_MCP_TOOLS = [
3603
3847
  },
3604
3848
  {
3605
3849
  name: 'scene_render_file',
3606
- description: 'Validate, compose, and render an IWSDK scene JSON file without opening it in the live editor. Invalid files return structured diagnostics and no PNG; valid files return hashes, render metadata, and PNG image data.',
3850
+ description: 'Validate, compose, and render an IWSDK scene JSON file without opening it in the live editor. Invalid files return structured diagnostics and no PNG; valid files persist the PNG locally and return screenshotPath with hashes and render metadata.',
3607
3851
  inputSchema: {
3608
3852
  type: 'object',
3609
3853
  additionalProperties: false,
@@ -3619,8 +3863,16 @@ const ALL_RUNTIME_MCP_TOOLS = [
3619
3863
  type: 'string',
3620
3864
  description: 'Stable id of an exact camera declared in document.authoring.views. Use this, not view, for names such as "hero".',
3621
3865
  },
3622
- width: { type: 'number', minimum: 1 },
3623
- height: { type: 'number', minimum: 1 },
3866
+ width: {
3867
+ type: 'number',
3868
+ minimum: 1,
3869
+ description: 'Render width in pixels. For agent-loop review use 512 or smaller; use 384 or smaller when verifying a correction.',
3870
+ },
3871
+ height: {
3872
+ type: 'number',
3873
+ minimum: 1,
3874
+ description: 'Render height in pixels. For agent-loop review use 512 or smaller; use 384 or smaller when verifying a correction.',
3875
+ },
3624
3876
  },
3625
3877
  required: ['path'],
3626
3878
  },
@@ -4102,7 +4354,7 @@ const ALL_RUNTIME_MCP_TOOLS = [
4102
4354
  },
4103
4355
  {
4104
4356
  name: 'scene_screenshot',
4105
- description: 'Capture a native scene editor screenshot. Supports exact saved authoring viewId cameras, current/top/front/back/left/right/quarter/orbit views, and explicit perspective/orthographic poses.',
4357
+ description: 'Capture a native scene editor screenshot, persist the PNG locally, and return screenshotPath. Supports exact saved authoring viewId cameras, current/top/front/back/left/right/quarter/orbit views, and explicit perspective/orthographic poses.',
4106
4358
  inputSchema: {
4107
4359
  type: 'object',
4108
4360
  properties: {
@@ -4127,6 +4379,57 @@ const ALL_RUNTIME_MCP_TOOLS = [
4127
4379
  },
4128
4380
  },
4129
4381
  },
4382
+ {
4383
+ name: 'asset_render_preview',
4384
+ description: 'Render an isolated manifest model as one labelled multi-view contact sheet without changing the open scene. Supports authored materials or a neutral clay pass, optional framing around one named subtree, persists the PNG locally, and returns screenshotPath with deterministic geometry diagnostics. UIKitML assets must use ui_render_preview.',
4385
+ inputSchema: {
4386
+ type: 'object',
4387
+ additionalProperties: false,
4388
+ properties: {
4389
+ assetId: {
4390
+ type: 'string',
4391
+ description: 'Renderable glTF or Object3D manifest asset id. UIKitML assets are rejected with guidance to use ui_render_preview.',
4392
+ },
4393
+ views: {
4394
+ type: 'array',
4395
+ minItems: 1,
4396
+ maxItems: 6,
4397
+ items: {
4398
+ type: 'string',
4399
+ enum: ['front', 'back', 'left', 'right', 'top', 'quarter'],
4400
+ },
4401
+ description: 'Ordered contact-sheet views. Defaults to front, back, right, top, and quarter.',
4402
+ },
4403
+ mode: {
4404
+ type: 'string',
4405
+ enum: ['material', 'clay'],
4406
+ description: 'Use authored materials or a fixed neutral clay material. Defaults to material.',
4407
+ },
4408
+ focus: {
4409
+ type: 'string',
4410
+ maxLength: 512,
4411
+ description: 'Optional exact object name or slash-separated named hierarchy path to frame. The full asset remains visible for attachment context.',
4412
+ },
4413
+ width: {
4414
+ type: 'number',
4415
+ minimum: 320,
4416
+ maximum: 2048,
4417
+ description: 'Composite contact-sheet width in pixels. Defaults to 640. Keep agent-loop previews at 640 or smaller; use focus rather than more pixels for detail review.',
4418
+ },
4419
+ height: {
4420
+ type: 'number',
4421
+ minimum: 240,
4422
+ maximum: 2048,
4423
+ description: 'Composite contact-sheet height in pixels. Defaults to 480. Keep agent-loop previews at 480 or smaller; use focus rather than more pixels for detail review.',
4424
+ },
4425
+ background: {
4426
+ type: 'string',
4427
+ description: 'Three.js-compatible background color. Defaults to #202226.',
4428
+ },
4429
+ },
4430
+ required: ['assetId'],
4431
+ },
4432
+ },
4130
4433
  {
4131
4434
  name: 'ui_list_assets',
4132
4435
  description: 'List UIKitML assets available in the project asset manifest. Use a returned asset id with ui_render_preview or a PanelUI component config.',
@@ -4143,7 +4446,7 @@ const ALL_RUNTIME_MCP_TOOLS = [
4143
4446
  },
4144
4447
  {
4145
4448
  name: 'ui_render_preview',
4146
- description: 'Render one UIKitML asset from the project asset manifest in isolation against a plain background. Use this to inspect panel layout without the surrounding scene.',
4449
+ description: 'Render one UIKitML asset from the project asset manifest in isolation against a plain background, persist the PNG locally, and return screenshotPath. Use this to inspect panel layout without the surrounding scene.',
4147
4450
  inputSchema: {
4148
4451
  type: 'object',
4149
4452
  additionalProperties: false,
@@ -4172,6 +4475,45 @@ const ALL_RUNTIME_MCP_TOOLS = [
4172
4475
  required: ['assetId'],
4173
4476
  },
4174
4477
  },
4478
+ {
4479
+ name: 'ui_inspect',
4480
+ description: 'Inspect live UIKitML elements owned by one ECS panel entity. Omit selector to list stable-ID elements, or use #id, .class, and descendant selectors for focused inspection. Returns bounded current text, state, layout, and selected computed properties without interacting with the UI; documents over 10,000 objects fail explicitly. Requires FRAMEWORK_MCP_RUNTIME.',
4481
+ inputSchema: {
4482
+ type: 'object',
4483
+ additionalProperties: false,
4484
+ properties: {
4485
+ entityIndex: {
4486
+ type: 'integer',
4487
+ minimum: 0,
4488
+ description: 'Panel entity index from ecs_find_entities or scene_get_runtime_hierarchy.',
4489
+ },
4490
+ selector: {
4491
+ type: 'string',
4492
+ maxLength: 512,
4493
+ description: 'Optional #id, .class, or descendant selector with at most 16 parts. Omit to list every stable-ID element in document order.',
4494
+ },
4495
+ properties: {
4496
+ type: 'array',
4497
+ minItems: 1,
4498
+ maxItems: 20,
4499
+ items: {
4500
+ type: 'string',
4501
+ maxLength: 64,
4502
+ pattern: '^[A-Za-z][A-Za-z0-9]*$',
4503
+ description: 'Camel-case UIKit property name.',
4504
+ },
4505
+ description: 'Optional computed UIKit property names to return. Defaults to common text, value, state, display, and pointer-event properties.',
4506
+ },
4507
+ limit: {
4508
+ type: 'integer',
4509
+ minimum: 1,
4510
+ maximum: 50,
4511
+ description: 'Maximum returned elements. Defaults to 50.',
4512
+ },
4513
+ },
4514
+ required: ['entityIndex'],
4515
+ },
4516
+ },
4175
4517
  {
4176
4518
  name: 'scene_compare_screenshots',
4177
4519
  description: 'Capture two native scene editor screenshots and report byte identity. This is not a perceptual image comparison.',
@@ -4840,7 +5182,7 @@ const ALL_RUNTIME_MCP_TOOLS = [
4840
5182
  },
4841
5183
  {
4842
5184
  name: 'ecs_snapshot',
4843
- 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.',
5185
+ description: 'Capture a snapshot of all ECS entity/component state. Retains 2 snapshots by default; set capacity (2-20) to keep a larger rolling window. Use with ecs_diff to compare. Requires FRAMEWORK_MCP_RUNTIME.',
4844
5186
  inputSchema: {
4845
5187
  type: 'object',
4846
5188
  properties: {
@@ -4848,6 +5190,10 @@ const ALL_RUNTIME_MCP_TOOLS = [
4848
5190
  type: 'string',
4849
5191
  description: 'Label for this snapshot (default: auto-generated). Use to reference in ecs_diff.',
4850
5192
  },
5193
+ capacity: {
5194
+ type: 'number',
5195
+ description: 'Rolling snapshot capacity for this runtime (integer 2-20). Omit to keep the current capacity; defaults to 2.',
5196
+ },
4851
5197
  },
4852
5198
  },
4853
5199
  },
@@ -4910,20 +5256,79 @@ const EXPECTED_TAB_SCHEMA = {
4910
5256
  },
4911
5257
  required: ['id', 'generation'],
4912
5258
  };
5259
+ const RUNTIME_TARGET_SCHEMA = {
5260
+ type: 'object',
5261
+ additionalProperties: false,
5262
+ description: 'Execution destination. Omit for the managed browser. Physical devices require headsetId, pageId and tabGeneration from runtime_list_targets.',
5263
+ properties: {
5264
+ deviceClass: { type: 'string', enum: ['managed', 'physical'] },
5265
+ headsetId: { type: 'string' },
5266
+ pageId: { type: 'string' },
5267
+ tabGeneration: { type: 'integer', minimum: 1 },
5268
+ browserEpoch: { type: 'integer', minimum: 1 },
5269
+ sessionId: { type: 'string' },
5270
+ },
5271
+ required: ['deviceClass'],
5272
+ };
5273
+ const CONTROL_TOOLS = [
5274
+ {
5275
+ name: 'runtime_pair_headset',
5276
+ description: 'Associate an exact headset identifier (adb serial) with this dev session. Open the returned bootstrap URL on that device, then discover its page using runtime_list_targets.',
5277
+ inputSchema: {
5278
+ type: 'object',
5279
+ properties: { headsetId: { type: 'string' } },
5280
+ required: ['headsetId'],
5281
+ },
5282
+ },
5283
+ {
5284
+ name: 'runtime_get_status',
5285
+ description: 'Read live runtime ownership and managed browser lifecycle. Does not launch or recover a browser.',
5286
+ inputSchema: { type: 'object', properties: {} },
5287
+ },
5288
+ {
5289
+ name: 'runtime_list_targets',
5290
+ description: 'Discover connected targets, exact identities, readiness and supported methods. Physical targets must be explicitly selected.',
5291
+ inputSchema: { type: 'object', properties: {} },
5292
+ },
5293
+ {
5294
+ name: 'runtime_wait',
5295
+ description: 'Wait for a lifecycle revision change, without causing recovery. Returns a current snapshot on timeout.',
5296
+ inputSchema: {
5297
+ type: 'object',
5298
+ properties: {
5299
+ afterRevision: { type: 'integer', minimum: 0 },
5300
+ timeoutMs: { type: 'integer', minimum: 0, maximum: 25000 },
5301
+ },
5302
+ },
5303
+ },
5304
+ {
5305
+ name: 'runtime_recover',
5306
+ description: 'Explicitly retry launching the managed browser after failures. Does not replay previous commands or reset live page state.',
5307
+ inputSchema: { type: 'object', properties: {} },
5308
+ },
5309
+ ];
4913
5310
  function withExpectedTabPrecondition(schema) {
4914
5311
  return {
4915
5312
  ...schema,
4916
5313
  properties: {
4917
5314
  ...(schema.properties ?? {}),
4918
5315
  expectedTab: EXPECTED_TAB_SCHEMA,
5316
+ runtimeTarget: RUNTIME_TARGET_SCHEMA,
4919
5317
  },
4920
5318
  };
4921
5319
  }
4922
- const RUNTIME_MCP_TOOLS = ALL_RUNTIME_MCP_TOOLS.filter((tool) => (!tool.name.startsWith('scene_') ||
5320
+ const RUNTIME_MCP_TOOLS = [
5321
+ ...ALL_RUNTIME_MCP_TOOLS,
5322
+ ...CONTROL_TOOLS,
5323
+ ]
5324
+ .filter((tool) => (!tool.name.startsWith('scene_') ||
4923
5325
  PUBLIC_SCENE_MCP_TOOL_NAME_SET.has(tool.name)) &&
4924
- !REMOVED_WORKSPACE_MCP_TOOL_NAME_SET.has(tool.name)).map((tool) => ({
5326
+ !REMOVED_WORKSPACE_MCP_TOOL_NAME_SET.has(tool.name))
5327
+ .map((tool) => ({
4925
5328
  ...tool,
4926
- inputSchema: withExpectedTabPrecondition(tool.inputSchema),
5329
+ inputSchema: CONTROL_TOOLS.some((control) => control.name === tool.name)
5330
+ ? tool.inputSchema
5331
+ : withExpectedTabPrecondition(tool.inputSchema),
4927
5332
  }));
4928
5333
  const RUNTIME_TOOL_TO_METHOD = {
4929
5334
  xr_get_session_status: 'get_session_status',
@@ -4943,6 +5348,9 @@ const RUNTIME_TOOL_TO_METHOD = {
4943
5348
  xr_get_device_state: 'get_device_state',
4944
5349
  xr_set_device_state: 'set_device_state',
4945
5350
  browser_screenshot: 'screenshot',
5351
+ browser_snapshot: 'browser_snapshot',
5352
+ browser_interact: 'browser_interact',
5353
+ browser_profile: 'browser_profile',
4946
5354
  browser_get_console_logs: 'get_console_logs',
4947
5355
  browser_reload_page: 'reload_page',
4948
5356
  scene_get_render_stats: 'get_render_stats',
@@ -4965,6 +5373,9 @@ const ALL_RUNTIME_CLI_PATHS = {
4965
5373
  xr_get_gamepad_state: ['xr', 'get-gamepad-state'],
4966
5374
  xr_set_gamepad_state: ['xr', 'set-gamepad-state'],
4967
5375
  browser_screenshot: ['browser', 'screenshot'],
5376
+ browser_snapshot: ['browser', 'snapshot'],
5377
+ browser_interact: ['browser', 'interact'],
5378
+ browser_profile: ['browser', 'profile'],
4968
5379
  xr_get_device_state: ['xr', 'get-device-state'],
4969
5380
  xr_set_device_state: ['xr', 'set-device-state'],
4970
5381
  browser_get_console_logs: ['browser', 'logs'],
@@ -5004,8 +5415,10 @@ const ALL_RUNTIME_CLI_PATHS = {
5004
5415
  scene_get_logs: ['scene', 'logs'],
5005
5416
  scene_set_camera: ['scene', 'set-camera'],
5006
5417
  scene_screenshot: ['scene', 'screenshot'],
5418
+ asset_render_preview: ['asset', 'render-preview'],
5007
5419
  ui_list_assets: ['ui', 'assets'],
5008
5420
  ui_render_preview: ['ui', 'render-preview'],
5421
+ ui_inspect: ['ui', 'inspect'],
5009
5422
  scene_compare_screenshots: ['scene', 'compare-screenshots'],
5010
5423
  scene_begin_review: ['scene', 'begin-review'],
5011
5424
  scene_set_review_lens: ['scene', 'set-review-lens'],
@@ -5045,6 +5458,7 @@ const SCENE_EDITOR_MCP_TOOL_NAMES = [
5045
5458
  'scene_screenshot',
5046
5459
  'scene_set_preview_visibility',
5047
5460
  'scene_measure_image_regions',
5461
+ 'asset_render_preview',
5048
5462
  'ui_list_assets',
5049
5463
  'ui_render_preview',
5050
5464
  ];
@@ -5063,9 +5477,27 @@ const EDITOR_TARGET_MCP_TOOL_NAME_SET = new Set([
5063
5477
  ...REVIEW_EVIDENCE_MCP_TOOL_NAMES,
5064
5478
  ...WORKSPACE_MCP_TOOL_NAMES,
5065
5479
  ]);
5066
- const APP_TARGET_MCP_TOOL_NAME_SET = new Set(['browser_screenshot']);
5480
+ const HOST_BROWSER_MCP_TOOL_NAME_SET = new Set([
5481
+ 'browser_screenshot',
5482
+ 'browser_snapshot',
5483
+ 'browser_interact',
5484
+ 'browser_profile',
5485
+ 'browser_get_console_logs',
5486
+ 'browser_reload_page',
5487
+ ]);
5488
+ const APP_TARGET_MCP_TOOL_NAME_SET = new Set([
5489
+ ...HOST_BROWSER_MCP_TOOL_NAME_SET,
5490
+ 'ui_inspect',
5491
+ ]);
5067
5492
  const RUNTIME_OPERATIONS = RUNTIME_MCP_TOOLS.map((tool) => {
5068
- const cliPath = RUNTIME_CLI_PATHS[tool.name];
5493
+ const cliPath = RUNTIME_CLI_PATHS[tool.name] ??
5494
+ {
5495
+ runtime_get_status: ['runtime', 'status'],
5496
+ runtime_list_targets: ['runtime', 'targets'],
5497
+ runtime_wait: ['runtime', 'wait'],
5498
+ runtime_recover: ['runtime', 'recover'],
5499
+ runtime_pair_headset: ['runtime', 'pair-headset'],
5500
+ }[tool.name];
5069
5501
  const target = EDITOR_TARGET_MCP_TOOL_NAME_SET.has(tool.name)
5070
5502
  ? { role: 'editor' }
5071
5503
  : APP_TARGET_MCP_TOOL_NAME_SET.has(tool.name)
@@ -5079,6 +5511,14 @@ const RUNTIME_OPERATIONS = RUNTIME_MCP_TOOLS.map((tool) => {
5079
5511
  mcpName: tool.name,
5080
5512
  wsMethod: RUNTIME_TOOL_TO_METHOD[tool.name] ?? tool.name,
5081
5513
  ...(target ? { target } : {}),
5514
+ execution: tool.name.startsWith('runtime_')
5515
+ ? 'server'
5516
+ : HOST_BROWSER_MCP_TOOL_NAME_SET.has(tool.name)
5517
+ ? 'host'
5518
+ : 'runtime',
5519
+ physical: !EDITOR_TARGET_MCP_TOOL_NAME_SET.has(tool.name) &&
5520
+ (!HOST_BROWSER_MCP_TOOL_NAME_SET.has(tool.name) ||
5521
+ tool.name === 'browser_reload_page'),
5082
5522
  description: tool.description,
5083
5523
  inputSchema: tool.inputSchema,
5084
5524
  };
@@ -5106,30 +5546,467 @@ function resolveRuntimeOperationRequest(operation, params) {
5106
5546
  expectedTab.generation < 1)) {
5107
5547
  throw new Error(`${operation.mcpName}.expectedTab requires the { id, generation } object returned as result._tab`);
5108
5548
  }
5109
- if (operation.mcpName === 'browser_screenshot' &&
5110
- paramsRecord != null &&
5111
- Object.keys(paramsRecord).some((key) => key !== 'expectedTab')) {
5112
- throw new Error('browser_screenshot does not accept parameters; it always captures the application runtime');
5113
- }
5114
5549
  assertSchemaValue(params, operation.inputSchema, operation.mcpName);
5115
5550
  const commandParams = paramsRecord == null
5116
5551
  ? params
5117
- : Object.fromEntries(Object.entries(paramsRecord).filter(([key]) => key !== 'expectedTab'));
5552
+ : Object.fromEntries(Object.entries(paramsRecord).filter(([key]) => key !== 'expectedTab' && key !== 'runtimeTarget'));
5553
+ const selection = paramsRecord?.runtimeTarget;
5554
+ if (selection?.deviceClass === 'physical' &&
5555
+ (!selection.headsetId ||
5556
+ !selection.pageId ||
5557
+ !Number.isInteger(selection.tabGeneration))) {
5558
+ throw new Error('Physical runtimeTarget requires headsetId, pageId and tabGeneration from runtime_list_targets.');
5559
+ }
5560
+ if (selection &&
5561
+ isRecord$6(expectedTab) &&
5562
+ ((selection.pageId != null && selection.pageId !== expectedTab.id) ||
5563
+ (selection.tabGeneration != null &&
5564
+ selection.tabGeneration !== expectedTab.generation))) {
5565
+ throw new Error('runtimeTarget and expectedTab must identify the same page generation.');
5566
+ }
5118
5567
  const target = isRecord$6(expectedTab) &&
5119
5568
  typeof expectedTab.id === 'string' &&
5120
5569
  typeof expectedTab.generation === 'number'
5121
5570
  ? {
5122
5571
  ...(operation.target ?? {}),
5572
+ ...selection,
5123
5573
  pageId: expectedTab.id,
5124
5574
  tabGeneration: expectedTab.generation,
5125
5575
  }
5126
- : operation.target;
5576
+ : selection
5577
+ ? { ...operation.target, ...selection }
5578
+ : operation.target;
5127
5579
  return { params: commandParams, target };
5128
5580
  }
5129
5581
  function isRecord$6(value) {
5130
5582
  return typeof value === 'object' && value !== null && !Array.isArray(value);
5131
5583
  }
5132
5584
 
5585
+ /**
5586
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
5587
+ *
5588
+ * This source code is licensed under the MIT license found in the
5589
+ * LICENSE file in the root directory of this source tree.
5590
+ */
5591
+ const LOCK_TIMEOUT_MS = 5_000;
5592
+ const mutationQueues = new Map();
5593
+ async function renameRuntimeFile(tempPath, filePath) {
5594
+ for (let attempt = 0;; attempt += 1) {
5595
+ try {
5596
+ await rename(tempPath, filePath);
5597
+ return;
5598
+ }
5599
+ catch (error) {
5600
+ const code = error.code;
5601
+ if (process.platform !== 'win32' ||
5602
+ attempt >= 4 ||
5603
+ !['EACCES', 'EBUSY', 'EPERM'].includes(code ?? '')) {
5604
+ throw error;
5605
+ }
5606
+ await new Promise((resolve) => setTimeout(resolve, 25 * 2 ** attempt));
5607
+ }
5608
+ }
5609
+ }
5610
+ function normalizeWorkspaceRoot(workspaceRoot) {
5611
+ const resolved = path.resolve(workspaceRoot);
5612
+ try {
5613
+ return existsSync(resolved) ? realpathSync.native(resolved) : resolved;
5614
+ }
5615
+ catch {
5616
+ return resolved;
5617
+ }
5618
+ }
5619
+ function getRuntimeFilePath(workspaceRoot, relativePath) {
5620
+ return path.join(normalizeWorkspaceRoot(workspaceRoot), relativePath);
5621
+ }
5622
+ async function readRuntimeJson(filePath) {
5623
+ try {
5624
+ return JSON.parse(await readFile(filePath, 'utf8'));
5625
+ }
5626
+ catch {
5627
+ return null;
5628
+ }
5629
+ }
5630
+ async function writeRuntimeJson(filePath, value) {
5631
+ await mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
5632
+ const tempPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
5633
+ try {
5634
+ await writeFile(tempPath, `${JSON.stringify(value, null, 2)}\n`, {
5635
+ encoding: 'utf8',
5636
+ flag: 'wx',
5637
+ mode: 0o600,
5638
+ });
5639
+ await renameRuntimeFile(tempPath, filePath);
5640
+ }
5641
+ finally {
5642
+ await rm(tempPath, { force: true }).catch(() => { });
5643
+ }
5644
+ }
5645
+ async function removeRuntimeFile(filePath) {
5646
+ await rm(filePath, { force: true }).catch(() => { });
5647
+ }
5648
+ function isRuntimeProcessAlive(pid) {
5649
+ if (!Number.isInteger(pid) || pid <= 0) {
5650
+ return false;
5651
+ }
5652
+ try {
5653
+ process.kill(pid, 0);
5654
+ return true;
5655
+ }
5656
+ catch (error) {
5657
+ return error.code === 'EPERM';
5658
+ }
5659
+ }
5660
+ function getRuntimeFileLockPath(filePath) {
5661
+ return `${filePath}.lock`;
5662
+ }
5663
+ async function removeOrphanedTempFiles(filePath) {
5664
+ const directory = path.dirname(filePath);
5665
+ const prefix = `${path.basename(filePath)}.`;
5666
+ let entries;
5667
+ try {
5668
+ entries = await readdir(directory);
5669
+ }
5670
+ catch {
5671
+ return;
5672
+ }
5673
+ await Promise.all(entries
5674
+ .filter((entry) => entry.startsWith(prefix) && entry.endsWith('.tmp'))
5675
+ .map((entry) => rm(path.join(directory, entry), { force: true }).catch(() => { })));
5676
+ }
5677
+ const processStarts = new Map();
5678
+ /** OS process birth identity distinguishes a live owner from a reused PID. */
5679
+ function getRuntimeProcessStart(pid) {
5680
+ if (!Number.isInteger(pid) || pid <= 0) {
5681
+ return null;
5682
+ }
5683
+ const cached = processStarts.get(pid);
5684
+ if (pid === process.pid && cached) {
5685
+ return cached;
5686
+ }
5687
+ let value = null;
5688
+ try {
5689
+ if (process.platform === 'linux') {
5690
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
5691
+ const boot = readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
5692
+ value = `${boot}:${stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19]}`;
5693
+ }
5694
+ else if (process.platform === 'win32') {
5695
+ value =
5696
+ execFileSync('powershell.exe', [
5697
+ '-NoProfile',
5698
+ '-NonInteractive',
5699
+ '-Command',
5700
+ `(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks`,
5701
+ ], {
5702
+ encoding: 'utf8',
5703
+ timeout: 1500,
5704
+ stdio: ['ignore', 'pipe', 'ignore'],
5705
+ }).trim() || null;
5706
+ }
5707
+ else {
5708
+ value =
5709
+ execFileSync('ps', ['-p', String(pid), '-o', 'lstart='], {
5710
+ encoding: 'utf8',
5711
+ timeout: 1500,
5712
+ env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' },
5713
+ stdio: ['ignore', 'pipe', 'ignore'],
5714
+ }).trim() || null;
5715
+ }
5716
+ }
5717
+ catch { }
5718
+ // A transient Windows/ps failure must remain retryable. Only a positive
5719
+ // identity is stable enough to cache for the lifetime of this process.
5720
+ if (pid === process.pid && value != null) {
5721
+ processStarts.set(pid, value);
5722
+ }
5723
+ return value;
5724
+ }
5725
+ const liveLockOwners = new Map();
5726
+ function ownerIsDead(owner) {
5727
+ if (!isRuntimeProcessAlive(owner.pid)) {
5728
+ return true;
5729
+ }
5730
+ if (owner.processStart) {
5731
+ const key = `${owner.pid}:${owner.processStart}:${owner.lockId ?? 'legacy'}`;
5732
+ if ((liveLockOwners.get(key) ?? 0) > Date.now()) {
5733
+ return false;
5734
+ }
5735
+ const current = getRuntimeProcessStart(owner.pid);
5736
+ if (current != null && current !== owner.processStart) {
5737
+ return true;
5738
+ }
5739
+ // Especially on Windows, avoid a synchronous OS query on every 25ms
5740
+ // contention poll. PID death is still checked immediately above; cached
5741
+ // liveness only delays reclamation and can never steal a live lock.
5742
+ if (liveLockOwners.size >= 128) {
5743
+ liveLockOwners.clear();
5744
+ }
5745
+ liveLockOwners.set(key, Date.now() + 1000);
5746
+ }
5747
+ return false;
5748
+ }
5749
+ async function reclaimFileLock(lockPath) {
5750
+ let entries;
5751
+ try {
5752
+ entries = await readdir(lockPath);
5753
+ }
5754
+ catch {
5755
+ return;
5756
+ }
5757
+ if (entries.length === 1 &&
5758
+ (entries[0] === 'owner.json' ||
5759
+ /^owner-[a-f0-9-]+\.json$/u.test(entries[0]))) {
5760
+ const ownerPath = path.join(lockPath, entries[0]);
5761
+ const owner = await readRuntimeJson(ownerPath);
5762
+ if (!owner ||
5763
+ !Number.isInteger(owner.pid) ||
5764
+ owner.pid <= 0 ||
5765
+ !ownerIsDead(owner)) {
5766
+ return;
5767
+ }
5768
+ // A successor has a different filename. A delayed reclaimer cannot remove
5769
+ // its owner file, and rmdir cannot remove a populated successor directory.
5770
+ await unlink(ownerPath).catch(() => { });
5771
+ }
5772
+ else if (entries.length !== 0) {
5773
+ return;
5774
+ }
5775
+ await rmdir(lockPath).catch(() => { });
5776
+ }
5777
+ function newLockOwner() {
5778
+ return {
5779
+ acquiredAt: Date.now(),
5780
+ pid: process.pid,
5781
+ lockId: randomUUID(),
5782
+ processStart: getRuntimeProcessStart(process.pid),
5783
+ };
5784
+ }
5785
+ async function acquireRuntimeFileLock(filePath) {
5786
+ const lockPath = getRuntimeFileLockPath(filePath);
5787
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
5788
+ await mkdir(path.dirname(lockPath), { recursive: true });
5789
+ const owner = newLockOwner();
5790
+ const filename = `owner-${owner.lockId}.json`;
5791
+ const prepared = await mkdtemp(`${lockPath}.prepared-`);
5792
+ try {
5793
+ await writeFile(path.join(prepared, filename), JSON.stringify(owner), {
5794
+ mode: 0o600,
5795
+ });
5796
+ while (true) {
5797
+ // Respect a live recovery guard left by an older CLI. New writers do not
5798
+ // need a recovery guard, so its own crash cannot create another lock layer.
5799
+ await reclaimFileLock(`${lockPath}.recovery`);
5800
+ let recoveryExists = false;
5801
+ try {
5802
+ await readdir(`${lockPath}.recovery`);
5803
+ recoveryExists = true;
5804
+ }
5805
+ catch { }
5806
+ try {
5807
+ if (recoveryExists) {
5808
+ throw Object.assign(new Error('Legacy recovery in progress'), {
5809
+ code: 'EEXIST',
5810
+ });
5811
+ }
5812
+ await rename(prepared, lockPath);
5813
+ await removeOrphanedTempFiles(filePath);
5814
+ return async () => {
5815
+ await unlink(path.join(lockPath, filename)).catch(() => { });
5816
+ await rmdir(lockPath).catch(() => { });
5817
+ };
5818
+ }
5819
+ catch (error) {
5820
+ if (!['EEXIST', 'ENOTEMPTY', 'EPERM', 'EACCES'].includes(error.code ?? '')) {
5821
+ throw error;
5822
+ }
5823
+ }
5824
+ if (!recoveryExists) {
5825
+ await reclaimFileLock(lockPath);
5826
+ }
5827
+ if (Date.now() >= deadline) {
5828
+ throw new Error(`Timed out acquiring runtime state lock ${lockPath}. Inspect its owner and stop the owning process before removing an unreadable legacy lock or recovery guard.`);
5829
+ }
5830
+ await new Promise((resolve) => setTimeout(resolve, 25));
5831
+ }
5832
+ }
5833
+ finally {
5834
+ await rm(prepared, { recursive: true, force: true });
5835
+ }
5836
+ }
5837
+ async function withRuntimeFileLock(filePath, operation) {
5838
+ const previous = mutationQueues.get(filePath) ?? Promise.resolve();
5839
+ const next = previous
5840
+ .catch(() => { })
5841
+ .then(async () => {
5842
+ const release = await acquireRuntimeFileLock(filePath);
5843
+ try {
5844
+ return await operation();
5845
+ }
5846
+ finally {
5847
+ await release().catch(() => { });
5848
+ }
5849
+ });
5850
+ mutationQueues.set(filePath, next);
5851
+ try {
5852
+ return await next;
5853
+ }
5854
+ finally {
5855
+ if (mutationQueues.get(filePath) === next) {
5856
+ mutationQueues.delete(filePath);
5857
+ }
5858
+ }
5859
+ }
5860
+
5861
+ /**
5862
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
5863
+ *
5864
+ * This source code is licensed under the MIT license found in the
5865
+ * LICENSE file in the root directory of this source tree.
5866
+ */
5867
+ class RuntimeOwnerError extends Error {
5868
+ constructor(message, owner, code = 'runtime_owner_conflict') {
5869
+ super(message);
5870
+ this.owner = owner;
5871
+ this.code = code;
5872
+ this.name = 'RuntimeOwnerError';
5873
+ }
5874
+ }
5875
+ function runtimeOwnerRecordPath(workspaceRoot) {
5876
+ return path.join(normalizeWorkspaceRoot(workspaceRoot), '.iwsdk/runtime/owner.json');
5877
+ }
5878
+ function sameRuntimeOwner(expected, actual) {
5879
+ return (expected.sessionId === actual.sessionId &&
5880
+ expected.pid === actual.pid &&
5881
+ expected.workspaceRoot === actual.workspaceRoot &&
5882
+ expected.endpoint === actual.endpoint &&
5883
+ expected.processStart != null &&
5884
+ expected.processStart === actual.processStart);
5885
+ }
5886
+ function runtimeOwnerEndpoint(workspaceRoot) {
5887
+ const key = createHash$2('sha256')
5888
+ .update(normalizeWorkspaceRoot(workspaceRoot))
5889
+ .digest('hex')
5890
+ .slice(0, 32);
5891
+ // Short enough for macOS sockaddr_un even with a long project path.
5892
+ return process.platform === 'win32'
5893
+ ? `\\\\.\\pipe\\iwsdk-${key}`
5894
+ : path.join('/tmp', `iwsdk-${process.getuid?.() ?? 'user'}`, `${key}.sock`);
5895
+ }
5896
+ /** A timeout is uncertainty; only ENOENT/ECONNREFUSED proves absence. */
5897
+ function inspectRuntimeOwner(endpoint) {
5898
+ return new Promise((resolve) => {
5899
+ const socket = createConnection(endpoint);
5900
+ let data = '';
5901
+ const finish = (result) => {
5902
+ socket.destroy();
5903
+ resolve(result);
5904
+ };
5905
+ socket.setTimeout(750, () => finish({ state: 'unknown', reason: 'Owner probe timed out' }));
5906
+ socket.on('error', (error) => finish(['ENOENT', 'ECONNREFUSED'].includes(error.code ?? '')
5907
+ ? { state: 'absent' }
5908
+ : { state: 'unknown', reason: error.message }));
5909
+ socket.on('data', (chunk) => {
5910
+ data += chunk.toString();
5911
+ if (data.length > 4096) {
5912
+ return finish({ state: 'unknown', reason: 'Invalid owner response' });
5913
+ }
5914
+ if (!data.includes('\n')) {
5915
+ return;
5916
+ }
5917
+ try {
5918
+ const owner = JSON.parse(data);
5919
+ if (typeof owner.sessionId !== 'string' ||
5920
+ typeof owner.workspaceRoot !== 'string' ||
5921
+ owner.endpoint !== endpoint ||
5922
+ !Number.isInteger(owner.pid) ||
5923
+ owner.pid <= 0) {
5924
+ throw new Error('Invalid identity');
5925
+ }
5926
+ finish({ state: 'live', owner });
5927
+ }
5928
+ catch {
5929
+ finish({ state: 'unknown', reason: 'Invalid owner identity' });
5930
+ }
5931
+ });
5932
+ socket.on('end', () => finish({ state: 'unknown', reason: 'Owner closed without an identity' }));
5933
+ });
5934
+ }
5935
+ /** Stop only the runtime whose live endpoint was positively verified. */
5936
+ async function stopRuntimeOwner(owner, requestShutdown, timing = {}) {
5937
+ const recordPath = runtimeOwnerRecordPath(owner.workspaceRoot);
5938
+ const sameOwner = (value) => sameRuntimeOwner(owner, value);
5939
+ const initial = await inspectRuntimeOwner(owner.endpoint);
5940
+ const recorded = await readRuntimeJson(recordPath);
5941
+ if (initial.state !== 'live' ||
5942
+ !sameOwner(initial.owner) ||
5943
+ recorded == null ||
5944
+ !sameOwner(recorded)) {
5945
+ throw new RuntimeOwnerError(`Runtime ownership could not be verified at ${owner.endpoint}; refusing PID-only termination.`, owner, 'runtime_owner_unverified');
5946
+ }
5947
+ const stopped = async (duration) => {
5948
+ const deadline = Date.now() + duration;
5949
+ do {
5950
+ const observation = await inspectRuntimeOwner(owner.endpoint);
5951
+ if (observation.state === 'live' && !sameOwner(observation.owner)) {
5952
+ return true;
5953
+ }
5954
+ if (observation.state === 'absent') {
5955
+ if (!isRuntimeProcessAlive(owner.pid)) {
5956
+ return true;
5957
+ }
5958
+ const processStart = getRuntimeProcessStart(owner.pid);
5959
+ if (processStart != null && processStart !== owner.processStart) {
5960
+ return true;
5961
+ }
5962
+ }
5963
+ await new Promise((resolve) => setTimeout(resolve, 50));
5964
+ } while (Date.now() < deadline);
5965
+ return false;
5966
+ };
5967
+ const accepted = await requestShutdown();
5968
+ // An acknowledgement can be lost after the runtime accepted shutdown. Give
5969
+ // even an unacknowledged owner time to finish cleanup before using signals.
5970
+ if (await stopped(timing.graceMs ?? (accepted ? 35000 : 5000))) {
5971
+ return;
5972
+ }
5973
+ for (const signal of ['SIGTERM', 'SIGKILL']) {
5974
+ const observation = await inspectRuntimeOwner(owner.endpoint);
5975
+ if (observation.state === 'absent') {
5976
+ return;
5977
+ }
5978
+ if (observation.state === 'live' && !sameOwner(observation.owner)) {
5979
+ return;
5980
+ }
5981
+ const currentRecord = await readRuntimeJson(recordPath);
5982
+ if (currentRecord == null || !sameOwner(currentRecord)) {
5983
+ throw new RuntimeOwnerError(`Runtime ownership record changed at ${recordPath}; refusing PID-only termination.`, owner, 'runtime_owner_unverified');
5984
+ }
5985
+ // The endpoint proves workspace ownership, but it is not sufficient
5986
+ // authority to signal an arbitrary PID (notably for Windows named pipes).
5987
+ // Require the independently recorded process-birth identity immediately
5988
+ // before every destructive signal so PID reuse or endpoint squatting can
5989
+ // only cause a fail-closed refusal.
5990
+ const identityMatches = owner.processStart != null &&
5991
+ getRuntimeProcessStart(owner.pid) === owner.processStart;
5992
+ if (!identityMatches || owner.pid === process.pid) {
5993
+ throw new RuntimeOwnerError(`Runtime ${owner.sessionId} did not stop, and its process identity cannot be safely signalled. Inspect ${owner.endpoint}.`, owner, 'runtime_owner_unverified');
5994
+ }
5995
+ try {
5996
+ process.kill(owner.pid, signal);
5997
+ }
5998
+ catch (error) {
5999
+ if (error.code !== 'ESRCH') {
6000
+ throw error;
6001
+ }
6002
+ }
6003
+ if (await stopped(timing.signalMs ?? 5000)) {
6004
+ return;
6005
+ }
6006
+ }
6007
+ throw new RuntimeOwnerError(`Runtime ${owner.sessionId} is still present or unresponsive at ${owner.endpoint}; shutdown is not confirmed.`, owner, 'runtime_owner_shutdown_failed');
6008
+ }
6009
+
5133
6010
  /**
5134
6011
  * Copyright (c) Meta Platforms, Inc. and affiliates.
5135
6012
  *
@@ -5158,48 +6035,23 @@ function readPackageManifest$1(dirPath) {
5158
6035
  catch {
5159
6036
  return null;
5160
6037
  }
5161
- }
5162
- function hasIwsdkDependency(manifest) {
5163
- if (!manifest) {
5164
- return false;
5165
- }
5166
- const dependencyBuckets = [
5167
- manifest.dependencies,
5168
- manifest.devDependencies,
5169
- manifest.peerDependencies,
5170
- ];
5171
- return dependencyBuckets.some((dependencies) => IWSDK_APP_PACKAGE_NAMES.some((packageName) => typeof dependencies?.[packageName] === 'string'));
5172
- }
5173
- async function readJsonFile(filePath) {
5174
- try {
5175
- const raw = await readFile(filePath, 'utf8');
5176
- return JSON.parse(raw);
5177
- }
5178
- catch {
5179
- return null;
5180
- }
5181
- }
5182
- async function writeJsonFile(filePath, value) {
5183
- await mkdir(path.dirname(filePath), { recursive: true });
5184
- await writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
5185
- }
5186
- async function removeIfExists(filePath) {
5187
- await rm(filePath, { force: true }).catch(() => { });
5188
- }
5189
- function normalizeWorkspaceRoot(workspaceRoot) {
5190
- const resolved = path.resolve(workspaceRoot);
5191
- try {
5192
- return existsSync(resolved) ? realpathSync.native(resolved) : resolved;
5193
- }
5194
- catch {
5195
- return resolved;
6038
+ }
6039
+ function hasIwsdkDependency(manifest) {
6040
+ if (!manifest) {
6041
+ return false;
5196
6042
  }
6043
+ const dependencyBuckets = [
6044
+ manifest.dependencies,
6045
+ manifest.devDependencies,
6046
+ manifest.peerDependencies,
6047
+ ];
6048
+ return dependencyBuckets.some((dependencies) => IWSDK_APP_PACKAGE_NAMES.some((packageName) => typeof dependencies?.[packageName] === 'string'));
5197
6049
  }
5198
6050
  function getRuntimeSessionFilePath(workspaceRoot) {
5199
- return path.join(normalizeWorkspaceRoot(workspaceRoot), IWSDK_RUNTIME_SESSION_PATH);
6051
+ return getRuntimeFilePath(workspaceRoot, IWSDK_RUNTIME_SESSION_PATH);
5200
6052
  }
5201
6053
  function getRuntimeLaunchFilePath(workspaceRoot) {
5202
- return path.join(normalizeWorkspaceRoot(workspaceRoot), IWSDK_RUNTIME_LAUNCH_PATH);
6054
+ return getRuntimeFilePath(workspaceRoot, IWSDK_RUNTIME_LAUNCH_PATH);
5203
6055
  }
5204
6056
  function getRuntimeLogsDir(workspaceRoot) {
5205
6057
  return path.join(normalizeWorkspaceRoot(workspaceRoot), IWSDK_RUNTIME_LOGS_DIR);
@@ -5209,18 +6061,7 @@ async function ensureRuntimeLogsDir(workspaceRoot) {
5209
6061
  await mkdir(logsDir, { recursive: true });
5210
6062
  return logsDir;
5211
6063
  }
5212
- function isProcessAlive(pid) {
5213
- if (!Number.isInteger(pid) || pid <= 0) {
5214
- return false;
5215
- }
5216
- try {
5217
- process.kill(pid, 0);
5218
- return true;
5219
- }
5220
- catch {
5221
- return false;
5222
- }
5223
- }
6064
+ const isProcessAlive = isRuntimeProcessAlive;
5224
6065
  function isIwsdkAppRoot(dirPath) {
5225
6066
  const normalizedDir = normalizeWorkspaceRoot(dirPath);
5226
6067
  if (!existsSync(path.join(normalizedDir, 'package.json'))) {
@@ -5246,52 +6087,135 @@ function findNearestIwsdkAppRoot(startDir = process.cwd()) {
5246
6087
  current = parent;
5247
6088
  }
5248
6089
  }
5249
- async function unregisterRuntimeSession(workspaceRoot) {
5250
- await removeIfExists(getRuntimeSessionFilePath(workspaceRoot));
5251
- }
5252
6090
  async function getRuntimeSession(workspaceRoot) {
5253
6091
  const normalizedWorkspaceRoot = normalizeWorkspaceRoot(workspaceRoot);
5254
- const session = await readJsonFile(getRuntimeSessionFilePath(normalizedWorkspaceRoot));
6092
+ const filePath = getRuntimeSessionFilePath(normalizedWorkspaceRoot);
6093
+ const session = await withRuntimeFileLock(filePath, () => readRuntimeJson(filePath));
5255
6094
  if (!session) {
5256
6095
  return null;
5257
6096
  }
5258
- if (!isProcessAlive(session.pid)) {
5259
- await unregisterRuntimeSession(normalizedWorkspaceRoot);
5260
- return null;
6097
+ if (isProcessAlive(session.pid) && session.browser?.lifecycle) {
6098
+ const endpoint = runtimeOwnerEndpoint(normalizedWorkspaceRoot);
6099
+ const observation = await inspectRuntimeOwner(endpoint);
6100
+ if (observation.state === 'unknown') {
6101
+ throw new Error(`Runtime ownership is unknown at ${endpoint}: ${observation.reason}. Inspect the runtime process before retrying; no PID-only action was taken.`);
6102
+ }
6103
+ if (observation.state === 'live') {
6104
+ if (observation.owner.sessionId === session.sessionId &&
6105
+ observation.owner.pid === session.pid &&
6106
+ observation.owner.workspaceRoot === normalizedWorkspaceRoot) {
6107
+ return session;
6108
+ }
6109
+ }
6110
+ else if (session.processStart != null) {
6111
+ const birth = getRuntimeProcessStart(session.pid);
6112
+ if (birth == null || birth === session.processStart) {
6113
+ throw new Error(`Runtime ${session.sessionId} (pid ${session.pid}) has lost its owner endpoint at ${endpoint}, but its process may still be alive. Stop that dev process before retrying.`);
6114
+ }
6115
+ }
6116
+ }
6117
+ else if (isProcessAlive(session.pid)) {
6118
+ return session;
5261
6119
  }
5262
- return session;
6120
+ // Never hold the file lock across IPC: a runtime publishing state may need
6121
+ // that lock before it can respond, especially with slower Windows probes.
6122
+ return withRuntimeFileLock(filePath, async () => {
6123
+ const current = await readRuntimeJson(filePath);
6124
+ if (current?.sessionId === session.sessionId &&
6125
+ current.pid === session.pid &&
6126
+ current.processStart === session.processStart) {
6127
+ await removeRuntimeFile(filePath);
6128
+ }
6129
+ return null;
6130
+ });
5263
6131
  }
5264
- async function setLaunchMetadata(input) {
6132
+ function createLaunchMetadata(input, createdAt = new Date().toISOString()) {
5265
6133
  const workspaceRoot = normalizeWorkspaceRoot(input.workspaceRoot);
5266
- const metadata = {
6134
+ return {
5267
6135
  schemaVersion: IWSDK_RUNTIME_STATE_SCHEMA_VERSION,
6136
+ ...(input.claimId == null ? {} : { claimId: input.claimId }),
6137
+ ...(input.phase == null ? {} : { phase: input.phase }),
5268
6138
  workspaceRoot,
5269
6139
  pid: input.pid,
6140
+ processStart: getRuntimeProcessStart(input.pid),
6141
+ ...(input.launcherPid == null ? {} : { launcherPid: input.launcherPid }),
6142
+ ...(input.processGroupId == null
6143
+ ? {}
6144
+ : { processGroupId: input.processGroupId }),
5270
6145
  command: input.command,
5271
6146
  args: input.args ?? [],
5272
6147
  logPath: input.logPath ?? null,
5273
6148
  scriptName: input.scriptName ?? 'dev:runtime',
5274
6149
  port: input.port ?? null,
5275
6150
  openBrowser: input.openBrowser ?? false,
5276
- createdAt: new Date().toISOString(),
6151
+ createdAt,
5277
6152
  };
5278
- await writeJsonFile(getRuntimeLaunchFilePath(workspaceRoot), metadata);
5279
- return metadata;
5280
6153
  }
5281
- async function clearLaunchMetadata(workspaceRoot) {
5282
- await removeIfExists(getRuntimeLaunchFilePath(workspaceRoot));
6154
+ async function claimLaunchMetadata(input) {
6155
+ const workspaceRoot = normalizeWorkspaceRoot(input.workspaceRoot);
6156
+ const filePath = getRuntimeLaunchFilePath(workspaceRoot);
6157
+ const metadata = createLaunchMetadata({
6158
+ ...input,
6159
+ phase: 'starting',
6160
+ workspaceRoot,
6161
+ });
6162
+ return withRuntimeFileLock(filePath, async () => {
6163
+ const existing = await readRuntimeJson(filePath);
6164
+ if (existing != null && isLaunchProcessAlive(existing)) {
6165
+ return { acquired: false, metadata: existing };
6166
+ }
6167
+ await writeRuntimeJson(filePath, metadata);
6168
+ return { acquired: true, metadata };
6169
+ });
6170
+ }
6171
+ async function setLaunchMetadata(input, expectedClaimId) {
6172
+ const workspaceRoot = normalizeWorkspaceRoot(input.workspaceRoot);
6173
+ const filePath = getRuntimeLaunchFilePath(workspaceRoot);
6174
+ return withRuntimeFileLock(filePath, async () => {
6175
+ const existing = await readRuntimeJson(filePath);
6176
+ if (expectedClaimId != null && existing?.claimId !== expectedClaimId) {
6177
+ return null;
6178
+ }
6179
+ const metadata = createLaunchMetadata({ ...input, workspaceRoot }, existing != null && existing.claimId === input.claimId
6180
+ ? existing.createdAt
6181
+ : new Date().toISOString());
6182
+ await writeRuntimeJson(filePath, metadata);
6183
+ return metadata;
6184
+ });
6185
+ }
6186
+ async function clearLaunchMetadata(workspaceRoot, expectedClaimId, expectedPhase) {
6187
+ const filePath = getRuntimeLaunchFilePath(workspaceRoot);
6188
+ return withRuntimeFileLock(filePath, async () => {
6189
+ const existing = await readRuntimeJson(filePath);
6190
+ if ((expectedClaimId == null || existing?.claimId === expectedClaimId) &&
6191
+ (expectedPhase == null || existing?.phase === expectedPhase)) {
6192
+ await removeRuntimeFile(filePath);
6193
+ return true;
6194
+ }
6195
+ return false;
6196
+ });
5283
6197
  }
5284
6198
  async function getLaunchMetadata(workspaceRoot) {
5285
6199
  const normalizedWorkspaceRoot = normalizeWorkspaceRoot(workspaceRoot);
5286
- const metadata = await readJsonFile(getRuntimeLaunchFilePath(normalizedWorkspaceRoot));
5287
- if (!metadata) {
5288
- return null;
5289
- }
6200
+ const filePath = getRuntimeLaunchFilePath(normalizedWorkspaceRoot);
6201
+ return withRuntimeFileLock(filePath, async () => {
6202
+ const metadata = await readRuntimeJson(filePath);
6203
+ if (!metadata) {
6204
+ return null;
6205
+ }
6206
+ if (!isLaunchProcessAlive(metadata)) {
6207
+ await removeRuntimeFile(filePath);
6208
+ return null;
6209
+ }
6210
+ return metadata;
6211
+ });
6212
+ }
6213
+ function isLaunchProcessAlive(metadata) {
5290
6214
  if (!isProcessAlive(metadata.pid)) {
5291
- await clearLaunchMetadata(normalizedWorkspaceRoot);
5292
- return null;
6215
+ return false;
5293
6216
  }
5294
- return metadata;
6217
+ const birth = metadata.processStart == null ? null : getRuntimeProcessStart(metadata.pid);
6218
+ return birth == null || birth === metadata.processStart;
5295
6219
  }
5296
6220
  async function getWorkspaceRuntimeState(workspaceRoot) {
5297
6221
  const normalizedWorkspaceRoot = normalizeWorkspaceRoot(workspaceRoot);
@@ -5312,6 +6236,12 @@ async function getWorkspaceRuntimeState(workspaceRoot) {
5312
6236
  launch,
5313
6237
  };
5314
6238
  }
6239
+ function getRuntimeUrls(session) {
6240
+ return {
6241
+ local: session?.localUrl ?? null,
6242
+ network: session?.networkUrls ?? [],
6243
+ };
6244
+ }
5315
6245
  function formatMissingRuntimeMessage(workspaceRoot) {
5316
6246
  return `No running IWSDK runtime found for ${workspaceRoot}. Start the dev server with "iwsdk dev up".`;
5317
6247
  }
@@ -10469,6 +11399,102 @@ const { Duplex } = require$$0$2;
10469
11399
  const { createHash } = require$$1;
10470
11400
  const { CLOSE_TIMEOUT, GUID, kWebSocket } = constants;
10471
11401
 
11402
+ /**
11403
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
11404
+ *
11405
+ * This source code is licensed under the MIT license found in the
11406
+ * LICENSE file in the root directory of this source tree.
11407
+ */
11408
+ /** Keep a command connection open for the complete secondary-CDP operation. */
11409
+ async function acquireBrowserLease(session, timeoutMs) {
11410
+ const id = randomUUID();
11411
+ const protocol = session.localUrl.startsWith('https:') ? 'wss' : 'ws';
11412
+ const ws = new WebSocket$1(`${protocol}://127.0.0.1:${session.port}/__iwer_mcp`, { rejectUnauthorized: false });
11413
+ let granted = false;
11414
+ let released = false;
11415
+ let closed = false;
11416
+ let rejectLost;
11417
+ const lost = new Promise((_resolve, reject) => {
11418
+ rejectLost = reject;
11419
+ });
11420
+ // A connection can die between granting and the caller's Promise.race.
11421
+ void lost.catch(() => { });
11422
+ const release = () => {
11423
+ if (closed) {
11424
+ return;
11425
+ }
11426
+ closed = true;
11427
+ released = true;
11428
+ if (granted && ws.readyState === WebSocket$1.OPEN) {
11429
+ ws.send(JSON.stringify({ id, method: '__iwsdk_browser_lease_release' }));
11430
+ }
11431
+ ws.close();
11432
+ };
11433
+ // Closing without a release is deliberate: the runtime treats the lost
11434
+ // lease as an uncertain command outcome and retires the owned browser before
11435
+ // admitting another command. This prevents a rejected or timed-out runner
11436
+ // from continuing CDP work concurrently with a later command.
11437
+ const abandon = () => {
11438
+ if (closed) {
11439
+ return;
11440
+ }
11441
+ closed = true;
11442
+ ws.close();
11443
+ };
11444
+ try {
11445
+ await new Promise((resolve, reject) => {
11446
+ const timer = setTimeout(() => {
11447
+ reject(new Error('Timed out acquiring the managed browser lease.'));
11448
+ ws.close();
11449
+ }, 20000);
11450
+ const failed = (error) => {
11451
+ clearTimeout(timer);
11452
+ if (granted && !released) {
11453
+ rejectLost(error);
11454
+ }
11455
+ else if (!granted) {
11456
+ reject(error);
11457
+ }
11458
+ };
11459
+ ws.on('error', failed);
11460
+ ws.on('close', () => failed(new Error('Managed browser lease was lost. The script outcome is unknown.')));
11461
+ ws.on('open', () => ws.send(JSON.stringify({
11462
+ id,
11463
+ method: '__iwsdk_browser_lease',
11464
+ expectedSessionId: session.sessionId,
11465
+ params: {
11466
+ browserEpoch: session.browser?.lifecycle?.browserEpoch,
11467
+ targetId: session.browserAutomation?.targetId,
11468
+ timeoutMs,
11469
+ },
11470
+ })));
11471
+ ws.on('message', (raw) => {
11472
+ try {
11473
+ const response = JSON.parse(raw.toString());
11474
+ if (response.id !== id) {
11475
+ return;
11476
+ }
11477
+ clearTimeout(timer);
11478
+ if (response.error) {
11479
+ failed(new Error(response.error.message));
11480
+ return;
11481
+ }
11482
+ granted = true;
11483
+ resolve();
11484
+ }
11485
+ catch (error) {
11486
+ failed(error);
11487
+ }
11488
+ });
11489
+ });
11490
+ return { abandon, release, lost };
11491
+ }
11492
+ catch (error) {
11493
+ release();
11494
+ throw error;
11495
+ }
11496
+ }
11497
+
10472
11498
  /**
10473
11499
  * Copyright (c) Meta Platforms, Inc. and affiliates.
10474
11500
  *
@@ -10525,6 +11551,26 @@ function getProtocolOrder(runtimeSession) {
10525
11551
  function isRecord$2(value) {
10526
11552
  return value != null && typeof value === 'object' && !Array.isArray(value);
10527
11553
  }
11554
+ const PERMISSION_FAILURE = /permission|not permitted|denied|sandbox|eacces|eperm/i;
11555
+ function isTransportFailure(normalized) {
11556
+ return (normalized.includes('socket hang up') ||
11557
+ normalized.includes('closed before response') ||
11558
+ normalized.includes('request timeout') ||
11559
+ normalized.includes('econnreset') ||
11560
+ normalized.includes('econnrefused'));
11561
+ }
11562
+ /** A headset's failures are its own; managed browser state never explains them. */
11563
+ function inferPhysicalIssueCause(message, explicitCause) {
11564
+ if (explicitCause) {
11565
+ return explicitCause;
11566
+ }
11567
+ if (PERMISSION_FAILURE.test(message)) {
11568
+ return 'permission_denied';
11569
+ }
11570
+ return isTransportFailure(message.toLowerCase())
11571
+ ? 'connection_lost'
11572
+ : undefined;
11573
+ }
10528
11574
  function inferRuntimeIssueCause(message, browser, explicitCause) {
10529
11575
  if (explicitCause) {
10530
11576
  return explicitCause;
@@ -10550,14 +11596,10 @@ function inferRuntimeIssueCause(message, browser, explicitCause) {
10550
11596
  normalized.includes('relaunch')) {
10551
11597
  return 'browser_relaunched';
10552
11598
  }
10553
- if (/permission|not permitted|denied|sandbox|eacces|eperm/i.test(normalized)) {
11599
+ if (PERMISSION_FAILURE.test(normalized)) {
10554
11600
  return 'permission_denied';
10555
11601
  }
10556
- if (normalized.includes('socket hang up') ||
10557
- normalized.includes('closed before response') ||
10558
- normalized.includes('request timeout') ||
10559
- normalized.includes('econnreset') ||
10560
- normalized.includes('econnrefused')) {
11602
+ if (isTransportFailure(normalized)) {
10561
11603
  if (browser &&
10562
11604
  !isRuntimeBrowserCommandReady({
10563
11605
  schemaVersion: 1,
@@ -10569,14 +11611,19 @@ function inferRuntimeIssueCause(message, browser, explicitCause) {
10569
11611
  }
10570
11612
  return undefined;
10571
11613
  }
10572
- async function trySendRuntimeCommand(protocol, port, method, params, target, timeoutMs, browser) {
11614
+ async function trySendRuntimeCommand(protocol, port, method, params, target, deadline, connectDeadline, browser, expectedSessionId) {
11615
+ const inferCause = (message, explicitCause) => target?.deviceClass === 'physical'
11616
+ ? inferPhysicalIssueCause(message, explicitCause)
11617
+ : inferRuntimeIssueCause(message, browser, explicitCause);
10573
11618
  return new Promise((resolve, reject) => {
11619
+ const timeoutMs = Math.max(Math.min(deadline, connectDeadline) - Date.now(), 1);
10574
11620
  const requestId = `${Date.now()}-${Math.random().toString(16).slice(2)}`;
10575
11621
  const wsUrl = `${protocol}://127.0.0.1:${port}/__iwer_mcp`;
10576
11622
  const ws = new WebSocket$1(wsUrl, {
10577
11623
  rejectUnauthorized: false,
10578
11624
  });
10579
11625
  let settled = false;
11626
+ let dispatched = false;
10580
11627
  const finish = (callback) => {
10581
11628
  if (settled) {
10582
11629
  return;
@@ -10606,7 +11653,7 @@ async function trySendRuntimeCommand(protocol, port, method, params, target, tim
10606
11653
  })
10607
11654
  : false,
10608
11655
  });
10609
- const timeout = setTimeout(() => {
11656
+ const onTimeout = () => {
10610
11657
  const message = `Request timeout for ${method}`;
10611
11658
  traceTransport('timeout', {
10612
11659
  method,
@@ -10616,12 +11663,30 @@ async function trySendRuntimeCommand(protocol, port, method, params, target, tim
10616
11663
  });
10617
11664
  closeSocket();
10618
11665
  finish(() => reject(new RuntimeCommandTransportError(message, {
10619
- issueCause: inferRuntimeIssueCause(message, browser),
11666
+ issueCause: inferCause(message),
10620
11667
  browser,
11668
+ details: {
11669
+ outcome: dispatched ? 'outcome_unknown' : 'not_executed',
11670
+ },
10621
11671
  })));
10622
- }, timeoutMs);
11672
+ };
11673
+ // Until the socket opens, only the connection budget applies; a probe that
11674
+ // times out has dispatched nothing and may fall back to another protocol.
11675
+ let timeout = setTimeout(onTimeout, timeoutMs);
10623
11676
  ws.on('open', () => {
11677
+ // Once open, the command gets its whole original deadline, and the relay
11678
+ // settles against that same absolute deadline, so admission time and a
11679
+ // WSS probe never extend or shorten the caller's budget. An open that
11680
+ // lands after the deadline dispatches nothing.
11681
+ clearTimeout(timeout);
11682
+ if (deadline <= Date.now()) {
11683
+ onTimeout();
11684
+ return;
11685
+ }
11686
+ timeout = setTimeout(onTimeout, deadline - Date.now());
10624
11687
  const payload = JSON.stringify({
11688
+ deadline,
11689
+ expectedSessionId,
10625
11690
  id: requestId,
10626
11691
  method,
10627
11692
  params: params ?? {},
@@ -10633,6 +11698,7 @@ async function trySendRuntimeCommand(protocol, port, method, params, target, tim
10633
11698
  protocol,
10634
11699
  port,
10635
11700
  });
11701
+ dispatched = true;
10636
11702
  ws.send(payload, (error) => {
10637
11703
  if (!error) {
10638
11704
  traceTransport('send', {
@@ -10651,8 +11717,11 @@ async function trySendRuntimeCommand(protocol, port, method, params, target, tim
10651
11717
  });
10652
11718
  closeSocket();
10653
11719
  finish(() => reject(new RuntimeCommandTransportError(error.message, {
10654
- issueCause: inferRuntimeIssueCause(error.message, browser),
11720
+ issueCause: inferCause(error.message),
10655
11721
  browser,
11722
+ details: {
11723
+ outcome: dispatched ? 'outcome_unknown' : 'not_executed',
11724
+ },
10656
11725
  })));
10657
11726
  });
10658
11727
  });
@@ -10687,7 +11756,7 @@ async function trySendRuntimeCommand(protocol, port, method, params, target, tim
10687
11756
  cause: explicitCause ?? null,
10688
11757
  });
10689
11758
  finish(() => reject(new RuntimeCommandExecutionError(message, {
10690
- issueCause: inferRuntimeIssueCause(message, browser, explicitCause),
11759
+ issueCause: inferCause(message, explicitCause),
10691
11760
  browser,
10692
11761
  details,
10693
11762
  })));
@@ -10710,8 +11779,11 @@ async function trySendRuntimeCommand(protocol, port, method, params, target, tim
10710
11779
  });
10711
11780
  closeSocket();
10712
11781
  finish(() => reject(new RuntimeCommandTransportError(message, {
10713
- issueCause: inferRuntimeIssueCause(message, browser),
11782
+ issueCause: inferCause(message),
10714
11783
  browser,
11784
+ details: {
11785
+ outcome: dispatched ? 'outcome_unknown' : 'not_executed',
11786
+ },
10715
11787
  })));
10716
11788
  }
10717
11789
  });
@@ -10724,8 +11796,11 @@ async function trySendRuntimeCommand(protocol, port, method, params, target, tim
10724
11796
  });
10725
11797
  closeSocket();
10726
11798
  finish(() => reject(new RuntimeCommandTransportError(error.message, {
10727
- issueCause: inferRuntimeIssueCause(error.message, browser),
11799
+ issueCause: inferCause(error.message),
10728
11800
  browser,
11801
+ details: {
11802
+ outcome: dispatched ? 'outcome_unknown' : 'not_executed',
11803
+ },
10729
11804
  })));
10730
11805
  });
10731
11806
  ws.on('close', (code, reasonBuffer) => {
@@ -10747,30 +11822,37 @@ async function trySendRuntimeCommand(protocol, port, method, params, target, tim
10747
11822
  ? `Connection closed before response for ${method}: ${reason}`
10748
11823
  : `Connection closed before response for ${method} (code ${code})`;
10749
11824
  finish(() => reject(new RuntimeCommandTransportError(message, {
10750
- issueCause: inferRuntimeIssueCause(message, browser),
11825
+ issueCause: inferCause(message),
10751
11826
  browser,
11827
+ details: {
11828
+ outcome: dispatched ? 'outcome_unknown' : 'not_executed',
11829
+ },
10752
11830
  })));
10753
11831
  });
10754
11832
  });
10755
11833
  }
10756
11834
  async function sendRuntimeCommandBeforeDeadline(options, deadline) {
10757
11835
  const { method, params, port, runtimeSession, target } = options;
10758
- const browser = runtimeSession?.browser;
11836
+ // Managed browser state describes the host browser only, never a headset.
11837
+ const browser = target?.deviceClass === 'physical' ? undefined : runtimeSession?.browser;
10759
11838
  const protocolOrder = getProtocolOrder(runtimeSession);
10760
11839
  const firstProtocol = protocolOrder[0];
10761
11840
  const fallbackProtocol = protocolOrder[1];
10762
11841
  const remainingAtStart = Math.max(deadline - Date.now(), 1);
10763
- const firstAttemptTimeout = fallbackProtocol && firstProtocol === 'wss'
10764
- ? Math.min(remainingAtStart, FAST_WSS_FALLBACK_TIMEOUT_MS)
10765
- : remainingAtStart;
11842
+ // An unknown scheme probes WSS briefly; the budget covers connecting only.
11843
+ const connectDeadline = fallbackProtocol && firstProtocol === 'wss'
11844
+ ? Date.now() + FAST_WSS_FALLBACK_TIMEOUT_MS
11845
+ : deadline;
10766
11846
  try {
10767
- return await trySendRuntimeCommand(firstProtocol, port, method, params, target, firstAttemptTimeout, browser);
11847
+ return await trySendRuntimeCommand(firstProtocol, port, method, params, target, deadline, connectDeadline, browser, runtimeSession?.sessionId);
10768
11848
  }
10769
11849
  catch (error) {
10770
11850
  if (!(error instanceof RuntimeCommandTransportError)) {
10771
11851
  throw error;
10772
11852
  }
10773
- if (!fallbackProtocol || fallbackProtocol === firstProtocol) {
11853
+ if (error.details?.outcome === 'outcome_unknown' ||
11854
+ !fallbackProtocol ||
11855
+ fallbackProtocol === firstProtocol) {
10774
11856
  throw error;
10775
11857
  }
10776
11858
  const remainingMs = Math.max(deadline - Date.now(), 1);
@@ -10789,7 +11871,7 @@ async function sendRuntimeCommandBeforeDeadline(options, deadline) {
10789
11871
  })
10790
11872
  : false,
10791
11873
  });
10792
- return trySendRuntimeCommand(fallbackProtocol, port, method, params, target, remainingMs, browser);
11874
+ return trySendRuntimeCommand(fallbackProtocol, port, method, params, target, deadline, deadline, browser, runtimeSession?.sessionId);
10793
11875
  }
10794
11876
  }
10795
11877
  function sceneOpenReadinessRequest(method, params, response, previousSceneSessionId) {
@@ -10939,13 +12021,6 @@ async function confirmOpenedSceneReady(options, response, deadline, previousScen
10939
12021
  });
10940
12022
  }
10941
12023
  async function sendRuntimeCommand({ port, method, params, target, timeoutMs = getDefaultRuntimeCommandTimeoutMs(method), runtimeSession, }) {
10942
- if (runtimeSession?.browser?.status === 'not_launched') {
10943
- throw new RuntimeCommandExecutionError(runtimeSession.browser.lastError?.message ??
10944
- 'No managed browser was launched. Run "iwsdk dev restart --open" to enable browser, scene, and runtime tools.', {
10945
- issueCause: 'browser_not_launched',
10946
- browser: runtimeSession.browser,
10947
- });
10948
- }
10949
12024
  const deadline = Date.now() + Math.max(timeoutMs, 1);
10950
12025
  const options = { method, params, port, runtimeSession, target };
10951
12026
  const previousSceneSessionId = await captureSceneOpenSessionBaseline(options, deadline);
@@ -10953,6 +12028,355 @@ async function sendRuntimeCommand({ port, method, params, target, timeoutMs = ge
10953
12028
  return confirmOpenedSceneReady(options, response, deadline, previousSceneSessionId);
10954
12029
  }
10955
12030
 
12031
+ /**
12032
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
12033
+ *
12034
+ * This source code is licensed under the MIT license found in the
12035
+ * LICENSE file in the root directory of this source tree.
12036
+ */
12037
+ const MAX_RUNNER_RESULT_BYTES = 1024 * 1024;
12038
+ async function getPageTargetId(context, page) {
12039
+ const cdp = await context.newCDPSession(page);
12040
+ try {
12041
+ const response = await cdp.send('Target.getTargetInfo');
12042
+ const targetId = response?.targetInfo?.targetId;
12043
+ return typeof targetId === 'string' ? targetId : '';
12044
+ }
12045
+ finally {
12046
+ await cdp.detach().catch(() => { });
12047
+ }
12048
+ }
12049
+ async function selectManagedBrowserPage(browser, managedOrigin, expectedTargetId) {
12050
+ const originCandidates = browser
12051
+ .contexts()
12052
+ .flatMap((candidateContext) => candidateContext.pages().map((candidatePage) => ({
12053
+ context: candidateContext,
12054
+ page: candidatePage,
12055
+ })))
12056
+ .filter(({ page: candidatePage }) => {
12057
+ try {
12058
+ return new URL(candidatePage.url()).origin === managedOrigin;
12059
+ }
12060
+ catch {
12061
+ return false;
12062
+ }
12063
+ });
12064
+ const managedCandidates = [];
12065
+ for (const candidate of originCandidates) {
12066
+ const opener = typeof candidate.page.opener === 'function'
12067
+ ? await candidate.page.opener().catch(() => null)
12068
+ : null;
12069
+ if (opener != null) {
12070
+ continue;
12071
+ }
12072
+ const [targetId, marked] = await Promise.all([
12073
+ getPageTargetId(candidate.context, candidate.page).catch(() => ''),
12074
+ candidate.page
12075
+ .evaluate(() => globalThis.__IWSDK_MANAGED_BROWSER_TARGET === true)
12076
+ .catch(() => false),
12077
+ ]);
12078
+ if (targetId === expectedTargetId && marked) {
12079
+ managedCandidates.push(candidate);
12080
+ }
12081
+ }
12082
+ if (managedCandidates.length !== 1) {
12083
+ throw new Error(`Expected exactly one verified managed application page; found ${managedCandidates.length}`);
12084
+ }
12085
+ return managedCandidates[0];
12086
+ }
12087
+ function validateAutomationEndpoint(endpoint) {
12088
+ let parsed;
12089
+ try {
12090
+ parsed = new URL(endpoint);
12091
+ }
12092
+ catch {
12093
+ throw new Error('Managed browser automation endpoint is invalid');
12094
+ }
12095
+ const loopbackHosts = new Set(['127.0.0.1', 'localhost', '[::1]']);
12096
+ if (parsed.protocol !== 'http:' ||
12097
+ !loopbackHosts.has(parsed.hostname) ||
12098
+ parsed.username !== '' ||
12099
+ parsed.password !== '' ||
12100
+ parsed.search !== '' ||
12101
+ parsed.hash !== '') {
12102
+ throw new Error('Managed browser automation endpoint must use loopback HTTP');
12103
+ }
12104
+ return parsed.href;
12105
+ }
12106
+ async function withTimeout(operation, timeoutMs, onTimeout) {
12107
+ let timer = null;
12108
+ return Promise.race([
12109
+ operation,
12110
+ new Promise((_, reject) => {
12111
+ timer = setTimeout(() => {
12112
+ onTimeout();
12113
+ reject(new Error(`browser run timed out after ${timeoutMs}ms`));
12114
+ }, timeoutMs);
12115
+ }),
12116
+ ]).finally(() => {
12117
+ if (timer != null) {
12118
+ clearTimeout(timer);
12119
+ }
12120
+ });
12121
+ }
12122
+ const DESTRUCTIVE_CDP_METHODS = new Set([
12123
+ 'Browser.close',
12124
+ 'Page.close',
12125
+ 'Target.closeTarget',
12126
+ 'Target.disposeBrowserContext',
12127
+ ]);
12128
+ function protectCdpOwnership(cdp) {
12129
+ const send = cdp.send.bind(cdp);
12130
+ cdp.send = async (method, params) => {
12131
+ if (DESTRUCTIVE_CDP_METHODS.has(method)) {
12132
+ throw new Error(`Direct CDP method ${method} is blocked for IWSDK-owned browser resources`);
12133
+ }
12134
+ return send(method, params);
12135
+ };
12136
+ }
12137
+ function protectManagedOwnership(browser, context, page, cdp) {
12138
+ const deny = () => {
12139
+ throw new Error('The managed browser, context, and application page are owned by IWSDK; direct close operations are blocked in browser run scripts.');
12140
+ };
12141
+ browser.close = deny;
12142
+ context.close = deny;
12143
+ page.close = deny;
12144
+ protectCdpOwnership(cdp);
12145
+ const newContextCdp = context.newCDPSession?.bind(context);
12146
+ if (newContextCdp) {
12147
+ context.newCDPSession = async (...args) => {
12148
+ const session = await newContextCdp(...args);
12149
+ protectCdpOwnership(session);
12150
+ return session;
12151
+ };
12152
+ }
12153
+ const newBrowserCdp = browser.newBrowserCDPSession?.bind(browser);
12154
+ if (newBrowserCdp) {
12155
+ browser.newBrowserCDPSession = async (...args) => {
12156
+ const session = await newBrowserCdp(...args);
12157
+ protectCdpOwnership(session);
12158
+ return session;
12159
+ };
12160
+ }
12161
+ }
12162
+ function serializeRunnerResult(value) {
12163
+ if (value === undefined) {
12164
+ return null;
12165
+ }
12166
+ let serialized;
12167
+ try {
12168
+ serialized = JSON.stringify(value);
12169
+ }
12170
+ catch {
12171
+ throw new Error('browser run result must be JSON-serializable');
12172
+ }
12173
+ if (serialized == null) {
12174
+ throw new Error('browser run result must be JSON-serializable');
12175
+ }
12176
+ if (Buffer.byteLength(serialized, 'utf8') > MAX_RUNNER_RESULT_BYTES) {
12177
+ throw new Error(`browser run result exceeds ${MAX_RUNNER_RESULT_BYTES} bytes`);
12178
+ }
12179
+ return JSON.parse(serialized);
12180
+ }
12181
+ async function handleBrowserRun(scriptArgument, options, io) {
12182
+ if (!scriptArgument) {
12183
+ throw new Error('Usage: iwsdk browser run <workspace-script.mjs>');
12184
+ }
12185
+ const workspaceRoot = await resolveWorkspaceRoot({
12186
+ cwd: io.cwd,
12187
+ workspace: typeof options.workspace === 'string' ? options.workspace : undefined,
12188
+ requireRunning: true,
12189
+ });
12190
+ const requestedScriptPath = path.resolve(io.cwd, scriptArgument);
12191
+ const requestedDirectory = path.dirname(requestedScriptPath);
12192
+ // Workspace discovery canonicalizes directory aliases (for example macOS
12193
+ // /var -> /private/var). Compare paths in the same namespace, while leaving
12194
+ // a symlink on the script itself for the separate containment check below.
12195
+ const scriptPath = path.join(existsSync(requestedDirectory)
12196
+ ? realpathSync.native(requestedDirectory)
12197
+ : requestedDirectory, path.basename(requestedScriptPath));
12198
+ const relativeScriptPath = path.relative(workspaceRoot, scriptPath);
12199
+ if (relativeScriptPath === '..' ||
12200
+ relativeScriptPath.startsWith(`..${path.sep}`) ||
12201
+ path.isAbsolute(relativeScriptPath)) {
12202
+ throw new Error('browser run script must stay inside the IWSDK workspace');
12203
+ }
12204
+ if (!existsSync(scriptPath)) {
12205
+ throw new Error(`browser run script does not exist: ${relativeScriptPath}`);
12206
+ }
12207
+ const realWorkspaceRoot = realpathSync(workspaceRoot);
12208
+ const realScriptPath = realpathSync(scriptPath);
12209
+ const realRelativeScriptPath = path.relative(realWorkspaceRoot, realScriptPath);
12210
+ if (realRelativeScriptPath === '..' ||
12211
+ realRelativeScriptPath.startsWith(`..${path.sep}`) ||
12212
+ path.isAbsolute(realRelativeScriptPath)) {
12213
+ throw new Error('browser run script symlinks must stay inside the IWSDK workspace');
12214
+ }
12215
+ const session = await getRuntimeSession(workspaceRoot);
12216
+ if (!session) {
12217
+ throw new Error('Managed browser runtime session is unavailable');
12218
+ }
12219
+ const automation = session.browserAutomation;
12220
+ const automationConfigured = automation?.configured ?? automation?.enabled ?? false;
12221
+ if (!automationConfigured) {
12222
+ throw new Error('Managed browser automation is disabled. Start with "iwsdk dev up --allow-browser-automation" or restart with "iwsdk dev restart --allow-browser-automation".');
12223
+ }
12224
+ const endpoint = automation?.endpoint;
12225
+ const expectedTargetId = automation?.targetId;
12226
+ if (!automation?.enabled || !endpoint || !expectedTargetId) {
12227
+ throw new Error('Managed browser automation is configured, but the managed browser is not running. Retry after the browser relaunches or restart the dev session.');
12228
+ }
12229
+ if (automation.protocol !== 'cdp') {
12230
+ throw new Error('Managed browser automation protocol is unsupported');
12231
+ }
12232
+ const automationEndpoint = validateAutomationEndpoint(endpoint);
12233
+ const timeoutMs = parseIntegerOption(options.timeout, '--timeout', 60_000);
12234
+ const requireFromWorkspace = createRequire(path.join(workspaceRoot, 'package.json'));
12235
+ let playwright;
12236
+ try {
12237
+ playwright = requireFromWorkspace('playwright');
12238
+ }
12239
+ catch {
12240
+ try {
12241
+ let requireFromPlugin;
12242
+ try {
12243
+ const pluginEntry = requireFromWorkspace.resolve('@iwsdk/vite-plugin-dev');
12244
+ requireFromPlugin = createRequire(pluginEntry);
12245
+ }
12246
+ catch {
12247
+ // The package exports only an ESM entry, so CommonJS resolution can
12248
+ // reject the package root even though the dependency is installed.
12249
+ requireFromPlugin = createRequire(path.join(workspaceRoot, 'node_modules', '@iwsdk', 'vite-plugin-dev', 'package.json'));
12250
+ }
12251
+ playwright = requireFromPlugin('playwright');
12252
+ }
12253
+ catch {
12254
+ throw new Error('The workspace does not expose Playwright through @iwsdk/vite-plugin-dev. Reinstall the IWSDK development dependencies.');
12255
+ }
12256
+ }
12257
+ if (session.browser?.lifecycle && timeoutMs > 110000) {
12258
+ throw new Error('Managed browser scripts are limited to 110000ms per lease.');
12259
+ }
12260
+ const browser = await playwright.chromium.connectOverCDP(automationEndpoint, {
12261
+ timeout: Math.min(timeoutMs, 30_000),
12262
+ });
12263
+ // For a connectOverCDP browser, Playwright's close implementation disconnects
12264
+ // the secondary CDP transport. Capture it before scripts receive protected
12265
+ // wrappers; closing the shared client connection can tear down the owner.
12266
+ const disconnectBrowser = browser.close.bind(browser);
12267
+ let lease = null;
12268
+ try {
12269
+ // Connecting is read-only. Acquire exclusive ownership immediately after
12270
+ // connection so the complete lease budget remains available to the script.
12271
+ lease = session.browser?.lifecycle
12272
+ ? await acquireBrowserLease(session, timeoutMs + 5000)
12273
+ : null;
12274
+ }
12275
+ catch (error) {
12276
+ await disconnectBrowser().catch(() => { });
12277
+ throw error;
12278
+ }
12279
+ let cdp = null;
12280
+ const cleanup = {
12281
+ detachCdp: null,
12282
+ };
12283
+ const abortController = new AbortController();
12284
+ let runnerSettled = false;
12285
+ try {
12286
+ const runnerOperation = (async () => {
12287
+ try {
12288
+ const managedOrigin = new URL(session.localUrl).origin;
12289
+ const selected = await selectManagedBrowserPage(browser, managedOrigin, expectedTargetId);
12290
+ const { context, page } = selected;
12291
+ const pageUrl = new URL(page.url());
12292
+ // Keep this small DOM-boundary resolver local to the CLI runner. The
12293
+ // plugin's resolver owns a live Playwright Page and is intentionally
12294
+ // private; exporting it would couple the CLI to plugin internals while
12295
+ // still requiring separate serialization across the CDP connection.
12296
+ const workspacePath = pageUrl.pathname === '/__iwsdk/workspace' ||
12297
+ pageUrl.pathname.startsWith('/__iwsdk/workspace/');
12298
+ const workspaceDataset = workspacePath
12299
+ ? false
12300
+ : await page.evaluate(() => globalThis.document.documentElement.dataset
12301
+ .iwsdkWorkspaceView != null);
12302
+ const hasWorkspaceMarker = workspacePath || workspaceDataset;
12303
+ const frameElement = hasWorkspaceMarker
12304
+ ? await page.$('#workspace-runtime-frame')
12305
+ : null;
12306
+ const frame = await frameElement?.contentFrame();
12307
+ if (hasWorkspaceMarker && !frame) {
12308
+ throw new Error('IWSDK workspace application frame is unavailable');
12309
+ }
12310
+ cdp = await context.newCDPSession(page);
12311
+ cleanup.detachCdp = cdp.detach.bind(cdp);
12312
+ protectManagedOwnership(browser, context, page, cdp);
12313
+ const moduleUrl = `${pathToFileURL(realScriptPath).href}?iwsdk_run=${randomUUID()}`;
12314
+ const scriptModule = (await import(moduleUrl));
12315
+ const run = scriptModule.default ?? scriptModule.run;
12316
+ if (typeof run !== 'function') {
12317
+ throw new Error('browser run script must export a default async function or named run function');
12318
+ }
12319
+ const result = await run({
12320
+ browser,
12321
+ cdp,
12322
+ context,
12323
+ frame: frame ?? page.mainFrame(),
12324
+ page,
12325
+ signal: abortController.signal,
12326
+ workspaceRoot,
12327
+ });
12328
+ return createSuccess({
12329
+ operation: 'browser.run',
12330
+ result: serializeRunnerResult(result),
12331
+ script: realRelativeScriptPath.split(path.sep).join('/'),
12332
+ workspaceRoot,
12333
+ });
12334
+ }
12335
+ finally {
12336
+ // A settled script (success or rejection) no longer owns awaited CDP
12337
+ // work and may release normally. A timeout or lost lease leaves this
12338
+ // false until the abandoned operation actually settles, so the server
12339
+ // retires the browser instead of admitting overlapping commands.
12340
+ runnerSettled = true;
12341
+ }
12342
+ })();
12343
+ const execution = withTimeout(runnerOperation, timeoutMs, () => abortController.abort());
12344
+ try {
12345
+ return await (lease ? Promise.race([execution, lease.lost]) : execution);
12346
+ }
12347
+ catch (error) {
12348
+ abortController.abort();
12349
+ if (error instanceof RuntimeCommandExecutionError) {
12350
+ throw error;
12351
+ }
12352
+ throw new RuntimeCommandExecutionError(error instanceof Error ? error.message : String(error), {
12353
+ details: {
12354
+ code: 'browser_run_failed',
12355
+ outcome: 'outcome_unknown',
12356
+ },
12357
+ });
12358
+ }
12359
+ }
12360
+ finally {
12361
+ if (cleanup.detachCdp != null) {
12362
+ try {
12363
+ await cleanup.detachCdp();
12364
+ }
12365
+ catch { }
12366
+ }
12367
+ try {
12368
+ await disconnectBrowser();
12369
+ }
12370
+ catch { }
12371
+ if (runnerSettled) {
12372
+ lease?.release();
12373
+ }
12374
+ else {
12375
+ lease?.abandon();
12376
+ }
12377
+ }
12378
+ }
12379
+
10956
12380
  /**
10957
12381
  * Copyright (c) Meta Platforms, Inc. and affiliates.
10958
12382
  *
@@ -10987,6 +12411,7 @@ async function handleStatus(options, io) {
10987
12411
  ]);
10988
12412
  return createSuccess({
10989
12413
  workspaceRoot,
12414
+ runtimeUrls: getRuntimeUrls(state.session),
10990
12415
  state,
10991
12416
  adapters,
10992
12417
  });
@@ -10999,9 +12424,11 @@ async function handleStatus(options, io) {
10999
12424
  * LICENSE file in the root directory of this source tree.
11000
12425
  */
11001
12426
  const DEV_SESSION_ENV_NAMES = {
12427
+ allowBrowserAutomation: 'IWSDK_DEV_ALLOW_BROWSER_AUTOMATION',
11002
12428
  aiMode: 'IWSDK_DEV_AI_MODE',
11003
12429
  headless: 'IWSDK_DEV_HEADLESS',
11004
12430
  open: 'IWSDK_DEV_OPEN',
12431
+ nativeXRControl: 'IWSDK_DEV_NATIVE_XR_CONTROL',
11005
12432
  screenshotHeight: 'IWSDK_DEV_SCREENSHOT_HEIGHT',
11006
12433
  screenshotWidth: 'IWSDK_DEV_SCREENSHOT_WIDTH',
11007
12434
  };
@@ -11024,6 +12451,14 @@ function describeChildExit(exit) {
11024
12451
  }
11025
12452
  return 'Dev server exited abnormally';
11026
12453
  }
12454
+ /** Names the port a fail-closed startup could not bind, from its launch log. */
12455
+ async function describeStartupExit(logPath) {
12456
+ const log = logPath ? await readFile(logPath, 'utf8').catch(() => '') : '';
12457
+ const port = /Port (\d+) is already in use/.exec(log.slice(-16384))?.[1];
12458
+ return port
12459
+ ? `Port ${port} is already in use. The runtime keeps its configured port instead of moving; stop the process using it or change server.port.`
12460
+ : 'Dev server exited before registering a runtime session';
12461
+ }
11027
12462
  function sleep(ms) {
11028
12463
  return new Promise((resolve) => setTimeout(resolve, ms));
11029
12464
  }
@@ -11165,6 +12600,8 @@ function resolveDevSessionOptions(options) {
11165
12600
  const headedRequested = readBooleanFlag(options.headed, '--headed');
11166
12601
  const openRequested = readBooleanFlag(options.open, '--open');
11167
12602
  const noOpenRequested = readBooleanFlag(options.noOpen, '--no-open');
12603
+ const allowBrowserAutomation = readBooleanFlag(options.allowBrowserAutomation, '--allow-browser-automation');
12604
+ const nativeXRControl = readBooleanFlag(options.nativeXrControl, '--native-xr-control');
11168
12605
  if (headlessRequested && headedRequested) {
11169
12606
  throw new Error('--headless and --headed cannot be used together');
11170
12607
  }
@@ -11180,9 +12617,11 @@ function resolveDevSessionOptions(options) {
11180
12617
  const screenshotWidth = parseOptionalPositiveIntegerOption(options.screenshotWidth, '--screenshot-width');
11181
12618
  const screenshotHeight = parseOptionalPositiveIntegerOption(options.screenshotHeight, '--screenshot-height');
11182
12619
  return {
12620
+ allowBrowserAutomation,
11183
12621
  ...(aiMode == null ? {} : { aiMode }),
11184
12622
  headless: headlessRequested || aiMode === 'agent',
11185
12623
  open: !noOpenRequested,
12624
+ nativeXRControl,
11186
12625
  ...(screenshotWidth == null ? {} : { screenshotWidth }),
11187
12626
  ...(screenshotHeight == null ? {} : { screenshotHeight }),
11188
12627
  };
@@ -11196,6 +12635,8 @@ function buildDevRuntimeEnvironment(options, baseEnvironment = process.env) {
11196
12635
  }
11197
12636
  environment[DEV_SESSION_ENV_NAMES.headless] = String(session.headless);
11198
12637
  environment[DEV_SESSION_ENV_NAMES.open] = String(session.open);
12638
+ environment[DEV_SESSION_ENV_NAMES.allowBrowserAutomation] = String(session.allowBrowserAutomation);
12639
+ environment[DEV_SESSION_ENV_NAMES.nativeXRControl] = String(session.nativeXRControl);
11199
12640
  if (session.aiMode != null) {
11200
12641
  environment[DEV_SESSION_ENV_NAMES.aiMode] = session.aiMode;
11201
12642
  }
@@ -11229,14 +12670,28 @@ async function ensureLogPath(workspaceRoot) {
11229
12670
  const logsDir = await ensureRuntimeLogsDir(workspaceRoot);
11230
12671
  return path.join(logsDir, `dev-${Date.now()}.log`);
11231
12672
  }
11232
- async function waitForRuntimeSession(workspaceRoot, timeoutMs, getChildExit) {
12673
+ async function waitForRuntimeSession(workspaceRoot, timeoutMs, getChildExit, attachingToOwner) {
11233
12674
  const deadline = Date.now() + timeoutMs;
11234
12675
  let lastSession = null;
11235
12676
  let lastBrowserIssue;
11236
12677
  while (Date.now() < deadline) {
11237
12678
  const session = await getRuntimeSession(workspaceRoot);
12679
+ if (!session &&
12680
+ attachingToOwner != null &&
12681
+ (await inspectRuntimeOwner(runtimeOwnerEndpoint(workspaceRoot))).state ===
12682
+ 'absent') {
12683
+ throw new Error('The runtime stopped while this command was attaching. Retry iwsdk dev up to start a new runtime.');
12684
+ }
11238
12685
  if (session) {
11239
12686
  lastSession = session;
12687
+ if (session.browser?.lifecycle) {
12688
+ return {
12689
+ session,
12690
+ exit: null,
12691
+ browserReady: isRuntimeBrowserCommandReady(session),
12692
+ browserIssue: session.browser.lastError,
12693
+ };
12694
+ }
11240
12695
  if (!session.browser || isRuntimeBrowserCommandReady(session)) {
11241
12696
  return { session, exit: null, browserReady: true };
11242
12697
  }
@@ -11316,6 +12771,45 @@ async function waitForRuntimeSession(workspaceRoot, timeoutMs, getChildExit) {
11316
12771
  : undefined),
11317
12772
  };
11318
12773
  }
12774
+ async function attachToRuntime(workspaceRoot, timeoutMs, foreground, openBrowser, io, attachingToOwner) {
12775
+ const waitResult = await waitForRuntimeSession(workspaceRoot, timeoutMs, undefined, attachingToOwner);
12776
+ const launch = await getLaunchMetadata(workspaceRoot);
12777
+ if (!waitResult.session) {
12778
+ const owner = await inspectRuntimeOwner(runtimeOwnerEndpoint(workspaceRoot));
12779
+ if (owner.state === 'live') {
12780
+ return createFailure(`Runtime ${owner.owner.sessionId} owns the workspace but has not registered a session; it may be starting or finishing cleanup. Retry shortly, or stop it with iwsdk dev down. No second runtime was started.`, 'runtime_owner_unregistered', { workspaceRoot, owner: owner.owner });
12781
+ }
12782
+ return createFailure(launch == null
12783
+ ? formatMissingRuntimeMessage(workspaceRoot)
12784
+ : `Dev server did not register a runtime session within ${timeoutMs}ms`, launch == null ? 'dev_up_missing_runtime' : 'dev_up_timeout', { workspaceRoot, launch });
12785
+ }
12786
+ if (shouldOpenExternalBrowser(openBrowser, waitResult.session)) {
12787
+ await openUrl(waitResult.session.localUrl);
12788
+ }
12789
+ const adapters = await readAdapterStatus(workspaceRoot);
12790
+ if (foreground) {
12791
+ io.stdout.write(`[IWSDK] Runtime already running at ${waitResult.session.localUrl}\n`);
12792
+ io.stdout.write(waitResult.browserReady
12793
+ ? '[IWSDK] Managed browser command path is ready.\n'
12794
+ : `[IWSDK] Managed browser command path is not ready${waitResult.browserIssue?.cause ? ` (${waitResult.browserIssue.cause})` : ''}. ${waitResult.session.browser?.lifecycle?.nextAction ?? 'Run "iwsdk dev status" and wait for browserCommandReady before issuing browser-backed commands.'}\n`);
12795
+ return null;
12796
+ }
12797
+ return createSuccess({
12798
+ action: 'attached',
12799
+ workspaceRoot,
12800
+ session: waitResult.session,
12801
+ launch,
12802
+ adapters,
12803
+ browserCommandReady: waitResult.browserReady,
12804
+ ...(waitResult.browserReady
12805
+ ? {}
12806
+ : {
12807
+ browserIssue: waitResult.browserIssue ?? null,
12808
+ browserNextAction: waitResult.session.browser?.lifecycle?.nextAction ??
12809
+ 'Run "iwsdk dev status" and wait for browserCommandReady before issuing browser-backed commands.',
12810
+ }),
12811
+ });
12812
+ }
11319
12813
  function waitForChildExit(child) {
11320
12814
  return new Promise((resolve) => {
11321
12815
  child.once('error', () => {
@@ -11351,46 +12845,154 @@ async function openUrl(url) {
11351
12845
  child.unref();
11352
12846
  });
11353
12847
  }
11354
- async function terminateRuntimeWorkspace(workspaceRoot) {
11355
- const state = await getWorkspaceRuntimeState(workspaceRoot);
11356
- const pids = Array.from(new Set([state.session?.pid, state.launch?.pid].filter((value) => typeof value === 'number')));
11357
- if (pids.length === 0) {
11358
- return {
11359
- stopped: false,
11360
- workspaceRoot,
11361
- session: state.session,
11362
- launch: state.launch,
12848
+ async function terminateWindowsProcessTree(pid, force) {
12849
+ await new Promise((resolve) => {
12850
+ const child = spawn('taskkill', ['/pid', String(pid), '/T', ...(force ? ['/F'] : [])], { stdio: 'ignore', windowsHide: true });
12851
+ let settled = false;
12852
+ const finish = () => {
12853
+ if (settled) {
12854
+ return;
12855
+ }
12856
+ settled = true;
12857
+ clearTimeout(timeout);
12858
+ resolve();
11363
12859
  };
12860
+ const timeout = setTimeout(() => {
12861
+ child.kill();
12862
+ finish();
12863
+ }, 5_000);
12864
+ child.once('error', finish);
12865
+ child.once('close', finish);
12866
+ });
12867
+ }
12868
+ function isPosixProcessGroupAlive(processGroupId) {
12869
+ try {
12870
+ process.kill(-processGroupId, 0);
12871
+ return true;
12872
+ }
12873
+ catch (error) {
12874
+ return error.code !== 'ESRCH';
12875
+ }
12876
+ }
12877
+ async function waitForSpawnedDevProcessExit(child, childExitPromise, processGroupId, timeoutMs) {
12878
+ const deadline = Date.now() + timeoutMs;
12879
+ do {
12880
+ if (process.platform === 'win32'
12881
+ ? child.exitCode != null || child.signalCode != null
12882
+ : processGroupId != null
12883
+ ? !isPosixProcessGroupAlive(processGroupId)
12884
+ : child.exitCode != null || child.signalCode != null) {
12885
+ return true;
12886
+ }
12887
+ await Promise.race([childExitPromise, sleep(50)]);
12888
+ } while (Date.now() < deadline);
12889
+ return process.platform === 'win32'
12890
+ ? child.exitCode != null || child.signalCode != null
12891
+ : processGroupId != null
12892
+ ? !isPosixProcessGroupAlive(processGroupId)
12893
+ : child.exitCode != null || child.signalCode != null;
12894
+ }
12895
+ async function terminateSpawnedDevProcess(child, childExitPromise, processGroupId) {
12896
+ if (typeof child.pid !== 'number') {
12897
+ return true;
12898
+ }
12899
+ if (process.platform === 'win32') {
12900
+ await terminateWindowsProcessTree(child.pid, false);
11364
12901
  }
11365
- for (const pid of pids) {
12902
+ else if (processGroupId != null) {
11366
12903
  try {
11367
- process.kill(pid, 'SIGTERM');
12904
+ process.kill(-processGroupId, 'SIGTERM');
12905
+ }
12906
+ catch (error) {
12907
+ if (error.code === 'ESRCH') {
12908
+ return true;
12909
+ }
11368
12910
  }
11369
- catch { }
11370
12911
  }
11371
- const deadline = Date.now() + 5000;
11372
- while (Date.now() < deadline) {
11373
- const freshState = await getWorkspaceRuntimeState(workspaceRoot);
11374
- if (!freshState.session && !freshState.launch) {
11375
- await clearLaunchMetadata(workspaceRoot);
12912
+ else {
12913
+ child.kill('SIGTERM');
12914
+ }
12915
+ if (await waitForSpawnedDevProcessExit(child, childExitPromise, processGroupId, 2_000)) {
12916
+ return true;
12917
+ }
12918
+ if (process.platform === 'win32') {
12919
+ await terminateWindowsProcessTree(child.pid, true);
12920
+ }
12921
+ else if (processGroupId != null) {
12922
+ try {
12923
+ process.kill(-processGroupId, 'SIGKILL');
12924
+ }
12925
+ catch (error) {
12926
+ if (error.code === 'ESRCH') {
12927
+ return true;
12928
+ }
12929
+ }
12930
+ }
12931
+ else {
12932
+ child.kill('SIGKILL');
12933
+ }
12934
+ return waitForSpawnedDevProcessExit(child, childExitPromise, processGroupId, 2_000);
12935
+ }
12936
+ async function requestRuntimeShutdown(session, claimId) {
12937
+ if (session == null || (claimId == null && !session.browser?.lifecycle)) {
12938
+ return false;
12939
+ }
12940
+ try {
12941
+ await sendRuntimeCommand({
12942
+ port: session.port,
12943
+ method: INTERNAL_RUNTIME_SHUTDOWN_METHOD,
12944
+ params: { claimId, sessionId: session.sessionId },
12945
+ timeoutMs: 3_000,
12946
+ runtimeSession: session,
12947
+ });
12948
+ return true;
12949
+ }
12950
+ catch {
12951
+ return false;
12952
+ }
12953
+ }
12954
+ async function terminateRuntimeWorkspace(workspaceRoot) {
12955
+ let state = await getWorkspaceRuntimeState(workspaceRoot);
12956
+ const launchClaimId = state.launch?.claimId;
12957
+ const observation = await inspectRuntimeOwner(runtimeOwnerEndpoint(workspaceRoot));
12958
+ if (observation.state === 'unknown') {
12959
+ throw new Error(`Runtime ownership is unknown: ${observation.reason}. Inspect the dev process before retrying; no PID-only termination was attempted.`);
12960
+ }
12961
+ if (observation.state === 'live') {
12962
+ const owner = observation.owner;
12963
+ const session = state.session;
12964
+ if (owner.workspaceRoot !== workspaceRoot ||
12965
+ (session != null &&
12966
+ (owner.sessionId !== session.sessionId || owner.pid !== session.pid))) {
12967
+ throw new Error('The runtime owner changed during shutdown. Retry iwsdk dev down.');
12968
+ }
12969
+ // Startup and incomplete browser cleanup can retain the owner without a
12970
+ // session record. The verified IPC identity still authorizes stopping it.
12971
+ await stopRuntimeOwner(owner, () => requestRuntimeShutdown(session, launchClaimId));
12972
+ if (launchClaimId) {
12973
+ await clearLaunchMetadata(workspaceRoot, launchClaimId);
12974
+ }
12975
+ return { stopped: true, workspaceRoot, sessionId: owner.sessionId };
12976
+ }
12977
+ if (state.session == null &&
12978
+ state.launch?.phase === 'starting' &&
12979
+ launchClaimId != null) {
12980
+ const cancelled = await clearLaunchMetadata(workspaceRoot, launchClaimId, 'starting');
12981
+ if (cancelled) {
11376
12982
  return {
11377
12983
  stopped: true,
11378
12984
  workspaceRoot,
12985
+ cancelledStartup: true,
11379
12986
  };
11380
12987
  }
11381
- await sleep(250);
12988
+ state = await getWorkspaceRuntimeState(workspaceRoot);
11382
12989
  }
11383
- for (const pid of pids) {
11384
- try {
11385
- process.kill(pid, 'SIGKILL');
11386
- }
11387
- catch { }
12990
+ if (state.session != null || state.launch != null) {
12991
+ throw new Error('A live legacy runtime has no verifiable owner endpoint. Stop that dev process from its original terminal; no PID-only termination was attempted.');
11388
12992
  }
11389
- await clearLaunchMetadata(workspaceRoot);
11390
12993
  return {
11391
- stopped: true,
12994
+ stopped: false,
11392
12995
  workspaceRoot,
11393
- forced: true,
11394
12996
  };
11395
12997
  }
11396
12998
  async function handleDevUp(options, io) {
@@ -11403,56 +13005,59 @@ async function handleDevUp(options, io) {
11403
13005
  const timeoutMs = parseIntegerOption(options.timeout, '--timeout', 60000);
11404
13006
  const foreground = isForegroundLaunch(options);
11405
13007
  const openBrowser = devSessionOptions.open;
11406
- const existingSession = await getRuntimeSession(workspaceRoot);
11407
- if (existingSession) {
11408
- const waitResult = await waitForRuntimeSession(workspaceRoot, timeoutMs);
11409
- const launch = await getLaunchMetadata(workspaceRoot);
11410
- if (!waitResult.session) {
11411
- return createFailure(formatMissingRuntimeMessage(workspaceRoot), 'dev_up_missing_runtime', {
11412
- workspaceRoot,
11413
- launch,
11414
- });
11415
- }
11416
- if (!waitResult.browserReady) {
11417
- return createFailure(waitResult.browserIssue?.message ??
11418
- `Managed browser did not become ready within ${timeoutMs}ms`, 'dev_browser_not_ready', {
11419
- workspaceRoot,
11420
- logPath: launch?.logPath ?? null,
11421
- scriptName: launch?.scriptName,
11422
- session: waitResult.session,
11423
- browser: waitResult.session.browser ?? null,
11424
- cause: waitResult.browserIssue?.cause,
11425
- });
11426
- }
11427
- if (shouldOpenExternalBrowser(openBrowser, waitResult.session)) {
11428
- await openUrl(waitResult.session.localUrl);
11429
- }
11430
- const adapters = await readAdapterStatus(workspaceRoot);
11431
- if (foreground) {
11432
- io.stdout.write(`[IWSDK] Runtime already running at ${waitResult.session.localUrl}\n`);
11433
- return null;
11434
- }
11435
- return createSuccess({
11436
- action: 'attached',
11437
- workspaceRoot,
11438
- session: waitResult.session,
11439
- launch,
11440
- adapters,
11441
- });
13008
+ const [existingSession, existingLaunch] = await Promise.all([
13009
+ getRuntimeSession(workspaceRoot),
13010
+ getLaunchMetadata(workspaceRoot),
13011
+ ]);
13012
+ const observation = await inspectRuntimeOwner(runtimeOwnerEndpoint(workspaceRoot));
13013
+ if (observation.state === 'unknown') {
13014
+ throw new Error(`Runtime ownership is unknown: ${observation.reason}. Inspect the dev process before retrying; no second runtime was started.`);
13015
+ }
13016
+ if (existingSession || existingLaunch || observation.state === 'live') {
13017
+ return attachToRuntime(workspaceRoot, timeoutMs, foreground, openBrowser, io, observation.state === 'live' ? observation.owner.sessionId : undefined);
11442
13018
  }
11443
13019
  const packageManager = await detectPackageManager(workspaceRoot);
11444
13020
  const scriptName = await resolveDevRuntimeScript(workspaceRoot);
11445
13021
  const logPath = foreground ? null : await ensureLogPath(workspaceRoot);
11446
- const stdoutFd = logPath ? openSync(logPath, 'a') : -1;
11447
13022
  const spawnArgs = getRunScriptArgs(packageManager, scriptName);
11448
- const child = spawn(packageManager, spawnArgs, {
11449
- cwd: workspaceRoot,
11450
- detached: !foreground,
11451
- stdio: foreground ? 'inherit' : ['ignore', stdoutFd, stdoutFd],
11452
- env: buildDevRuntimeEnvironment(options),
11453
- // npm/pnpm/yarn are .cmd shims on Windows; Node cannot spawn them without a shell.
11454
- shell: process.platform === 'win32',
13023
+ const claimId = randomUUID();
13024
+ const claim = await claimLaunchMetadata({
13025
+ claimId,
13026
+ workspaceRoot,
13027
+ pid: process.pid,
13028
+ command: packageManager,
13029
+ args: spawnArgs,
13030
+ logPath,
13031
+ scriptName,
13032
+ port: null,
13033
+ openBrowser,
11455
13034
  });
13035
+ if (!claim.acquired) {
13036
+ return attachToRuntime(workspaceRoot, timeoutMs, foreground, openBrowser, io);
13037
+ }
13038
+ const stdoutFd = logPath ? openSync(logPath, 'a') : -1;
13039
+ const childEnvironment = buildDevRuntimeEnvironment(options);
13040
+ childEnvironment[INTERNAL_RUNTIME_LAUNCH_CLAIM_ENV] = claimId;
13041
+ let child;
13042
+ try {
13043
+ child = spawn(packageManager, spawnArgs, {
13044
+ cwd: workspaceRoot,
13045
+ // A separate POSIX process group lets the CLI forward Ctrl-C to the
13046
+ // package manager and every descendant without signaling itself.
13047
+ detached: process.platform !== 'win32' || !foreground,
13048
+ stdio: foreground ? 'inherit' : ['ignore', stdoutFd, stdoutFd],
13049
+ env: childEnvironment,
13050
+ // npm/pnpm/yarn are .cmd shims on Windows; Node cannot spawn them without a shell.
13051
+ shell: process.platform === 'win32',
13052
+ });
13053
+ }
13054
+ catch (error) {
13055
+ if (stdoutFd >= 0) {
13056
+ closeSync(stdoutFd);
13057
+ }
13058
+ await clearLaunchMetadata(workspaceRoot, claimId);
13059
+ throw error;
13060
+ }
11456
13061
  const childExitPromise = waitForChildExit(child);
11457
13062
  let childExit = null;
11458
13063
  void childExitPromise.then((result) => {
@@ -11463,85 +13068,184 @@ async function handleDevUp(options, io) {
11463
13068
  child.unref();
11464
13069
  }
11465
13070
  if (typeof child.pid !== 'number') {
13071
+ await clearLaunchMetadata(workspaceRoot, claimId);
11466
13072
  throw new Error('Failed to start the dev process');
11467
13073
  }
11468
- await setLaunchMetadata({
13074
+ const processGroupId = process.platform !== 'win32' ? child.pid : undefined;
13075
+ const claimedLaunch = await setLaunchMetadata({
13076
+ claimId,
13077
+ phase: 'running',
11469
13078
  workspaceRoot,
11470
13079
  pid: child.pid,
13080
+ launcherPid: child.pid,
13081
+ processGroupId,
11471
13082
  command: packageManager,
11472
13083
  args: spawnArgs,
11473
13084
  logPath,
11474
13085
  scriptName,
11475
13086
  port: null,
11476
13087
  openBrowser,
11477
- });
11478
- const waitResult = await waitForRuntimeSession(workspaceRoot, timeoutMs, () => childExit);
11479
- if (!waitResult.session) {
11480
- if (waitResult.exit) {
11481
- await clearLaunchMetadata(workspaceRoot);
11482
- return createFailure('Dev server exited before registering a runtime session', 'dev_up_exit', {
13088
+ }, claimId);
13089
+ if (claimedLaunch == null) {
13090
+ if (process.platform === 'win32') {
13091
+ await terminateWindowsProcessTree(child.pid, true);
13092
+ }
13093
+ else if (processGroupId != null) {
13094
+ try {
13095
+ process.kill(-processGroupId, 'SIGTERM');
13096
+ }
13097
+ catch { }
13098
+ }
13099
+ else {
13100
+ child.kill('SIGTERM');
13101
+ }
13102
+ throw new Error('Lost ownership of the IWSDK dev startup claim');
13103
+ }
13104
+ let receivedForegroundSignal = null;
13105
+ let foregroundSignalExitCode = null;
13106
+ let foregroundSignalCount = 0;
13107
+ const handleForegroundSignal = (signal) => {
13108
+ foregroundSignalCount += 1;
13109
+ receivedForegroundSignal = signal;
13110
+ foregroundSignalExitCode =
13111
+ signal === 'SIGINT' ? 130 : signal === 'SIGHUP' ? 129 : 143;
13112
+ if (child.exitCode == null && child.signalCode == null) {
13113
+ if (process.platform === 'win32' && child.pid != null) {
13114
+ if (foregroundSignalCount > 1) {
13115
+ void terminateWindowsProcessTree(child.pid, true);
13116
+ }
13117
+ else {
13118
+ void getRuntimeSession(workspaceRoot)
13119
+ .then((session) => requestRuntimeShutdown(session, claimId))
13120
+ .catch(() => { });
13121
+ }
13122
+ }
13123
+ else {
13124
+ try {
13125
+ process.kill(-child.pid, foregroundSignalCount > 1 ? 'SIGKILL' : signal);
13126
+ }
13127
+ catch { }
13128
+ }
13129
+ }
13130
+ };
13131
+ const removeForegroundSignalHandlers = () => {
13132
+ if (!foreground) {
13133
+ return;
13134
+ }
13135
+ process.off('SIGINT', handleForegroundSignal);
13136
+ process.off('SIGHUP', handleForegroundSignal);
13137
+ process.off('SIGTERM', handleForegroundSignal);
13138
+ };
13139
+ if (foreground) {
13140
+ process.on('SIGINT', handleForegroundSignal);
13141
+ process.on('SIGHUP', handleForegroundSignal);
13142
+ process.on('SIGTERM', handleForegroundSignal);
13143
+ }
13144
+ try {
13145
+ const waitResult = await waitForRuntimeSession(workspaceRoot, timeoutMs, () => childExit);
13146
+ // Ctrl-C can arrive while browser readiness is still being probed. The
13147
+ // resulting transport disconnect is expected shutdown, not startup
13148
+ // failure, so let the finally block finish bounded process cleanup.
13149
+ if (foreground && receivedForegroundSignal != null) {
13150
+ return foregroundSignalExitCode ?? 1;
13151
+ }
13152
+ if (!waitResult.session) {
13153
+ if (waitResult.exit) {
13154
+ await clearLaunchMetadata(workspaceRoot, claimId);
13155
+ return createFailure(await describeStartupExit(logPath), 'dev_up_exit', {
13156
+ workspaceRoot,
13157
+ logPath,
13158
+ exitCode: waitResult.exit.exitCode,
13159
+ signal: waitResult.exit.signal,
13160
+ scriptName,
13161
+ });
13162
+ }
13163
+ const cleanupConfirmed = await terminateSpawnedDevProcess(child, childExitPromise, processGroupId);
13164
+ if (cleanupConfirmed) {
13165
+ await clearLaunchMetadata(workspaceRoot, claimId);
13166
+ }
13167
+ return createFailure(cleanupConfirmed
13168
+ ? `Dev server did not register a runtime session within ${timeoutMs}ms and the timed-out process was stopped`
13169
+ : `Dev server did not register a runtime session within ${timeoutMs}ms, and process cleanup could not be confirmed. Run "iwsdk dev down" before retrying.`, 'dev_up_timeout', {
11483
13170
  workspaceRoot,
11484
13171
  logPath,
11485
- exitCode: waitResult.exit.exitCode,
11486
- signal: waitResult.exit.signal,
11487
13172
  scriptName,
13173
+ launcherPid: child.pid,
13174
+ processGroupId,
13175
+ cleanupConfirmed,
11488
13176
  });
11489
13177
  }
11490
- return createFailure(`Dev server did not register a runtime session within ${timeoutMs}ms`, 'dev_up_timeout', {
13178
+ await setLaunchMetadata({
13179
+ claimId,
11491
13180
  workspaceRoot,
13181
+ pid: waitResult.session.pid,
13182
+ launcherPid: child.pid,
13183
+ processGroupId,
13184
+ command: packageManager,
13185
+ args: spawnArgs,
11492
13186
  logPath,
11493
13187
  scriptName,
11494
- });
11495
- }
11496
- await setLaunchMetadata({
11497
- workspaceRoot,
11498
- pid: waitResult.session.pid,
11499
- command: packageManager,
11500
- args: spawnArgs,
11501
- logPath,
11502
- scriptName,
11503
- port: waitResult.session.port,
11504
- openBrowser,
11505
- });
11506
- if (!waitResult.browserReady) {
11507
- return createFailure(waitResult.browserIssue?.message ??
11508
- `Managed browser did not become ready within ${timeoutMs}ms`, 'dev_browser_not_ready', {
13188
+ port: waitResult.session.port,
13189
+ openBrowser,
13190
+ }, claimId);
13191
+ const launch = await getLaunchMetadata(workspaceRoot);
13192
+ const adapters = await readAdapterStatus(workspaceRoot);
13193
+ if (shouldOpenExternalBrowser(openBrowser, waitResult.session)) {
13194
+ await openUrl(waitResult.session.localUrl);
13195
+ }
13196
+ if (foreground) {
13197
+ io.stdout.write(`[IWSDK] Runtime ready at ${waitResult.session.localUrl}\n`);
13198
+ io.stdout.write(waitResult.browserReady
13199
+ ? '[IWSDK] Managed browser command path is ready.\n'
13200
+ : `[IWSDK] Managed browser command path is not ready${waitResult.browserIssue?.cause ? ` (${waitResult.browserIssue.cause})` : ''}. ${waitResult.session.browser?.lifecycle?.nextAction ?? 'Run "iwsdk dev status" and wait for browserCommandReady before issuing browser-backed commands.'}\n`);
13201
+ const exit = await childExitPromise;
13202
+ if (receivedForegroundSignal != null) {
13203
+ await clearLaunchMetadata(workspaceRoot, claimId).catch(() => { });
13204
+ return foregroundSignalExitCode ?? 1;
13205
+ }
13206
+ await clearLaunchMetadata(workspaceRoot, claimId);
13207
+ if (isAbnormalChildExit(exit) &&
13208
+ !(await wasWorkspaceStoppedExternally(workspaceRoot))) {
13209
+ return createFailure(describeChildExit(exit), 'dev_up_exit', {
13210
+ workspaceRoot,
13211
+ session: waitResult.session,
13212
+ exitCode: exit.exitCode,
13213
+ signal: exit.signal,
13214
+ scriptName,
13215
+ });
13216
+ }
13217
+ return null;
13218
+ }
13219
+ return createSuccess({
13220
+ action: 'started',
11509
13221
  workspaceRoot,
11510
- logPath,
11511
- scriptName,
11512
13222
  session: waitResult.session,
11513
- browser: waitResult.session?.browser ?? null,
11514
- cause: waitResult.browserIssue?.cause,
13223
+ launch,
13224
+ logPath,
13225
+ adapters,
13226
+ browserCommandReady: waitResult.browserReady,
13227
+ ...(waitResult.browserReady
13228
+ ? {}
13229
+ : {
13230
+ browserIssue: waitResult.browserIssue ?? null,
13231
+ browserNextAction: waitResult.session.browser?.lifecycle?.nextAction ??
13232
+ 'Run "iwsdk dev status" and wait for browserCommandReady before issuing browser-backed commands.',
13233
+ }),
11515
13234
  });
11516
13235
  }
11517
- const launch = await getLaunchMetadata(workspaceRoot);
11518
- const adapters = await readAdapterStatus(workspaceRoot);
11519
- if (shouldOpenExternalBrowser(openBrowser, waitResult.session)) {
11520
- await openUrl(waitResult.session.localUrl);
11521
- }
11522
- if (foreground) {
11523
- io.stdout.write(`[IWSDK] Runtime ready at ${waitResult.session.localUrl}\n`);
11524
- const exit = await childExitPromise;
11525
- if (isAbnormalChildExit(exit) &&
11526
- !(await wasWorkspaceStoppedExternally(workspaceRoot))) {
11527
- return createFailure(describeChildExit(exit), 'dev_up_exit', {
11528
- workspaceRoot,
11529
- session: waitResult.session,
11530
- exitCode: exit.exitCode,
11531
- signal: exit.signal,
11532
- scriptName,
11533
- });
13236
+ finally {
13237
+ removeForegroundSignalHandlers();
13238
+ if (foreground && child.exitCode == null && child.signalCode == null) {
13239
+ if (process.platform === 'win32' && child.pid != null) {
13240
+ const session = await getRuntimeSession(workspaceRoot).catch(() => null);
13241
+ await requestRuntimeShutdown(session, claimId);
13242
+ }
13243
+ await terminateSpawnedDevProcess(child, childExitPromise, processGroupId);
13244
+ }
13245
+ if (foreground && (child.exitCode != null || child.signalCode != null)) {
13246
+ await clearLaunchMetadata(workspaceRoot, claimId).catch(() => { });
11534
13247
  }
11535
- return null;
11536
13248
  }
11537
- return createSuccess({
11538
- action: 'started',
11539
- workspaceRoot,
11540
- session: waitResult.session,
11541
- launch,
11542
- logPath,
11543
- adapters,
11544
- });
11545
13249
  }
11546
13250
  async function handleDevDown(options, io) {
11547
13251
  const workspaceRoot = await resolveWorkspaceRoot({
@@ -23289,6 +24993,9 @@ const isUUID$1 = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[
23289
24993
  /** @type {(value: string) => boolean} */
23290
24994
  const isIPv4$1 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);
23291
24995
 
24996
+ /** @type {(value: string) => boolean} */
24997
+ const isPort = RegExp.prototype.test.bind(/^\d*$/u);
24998
+
23292
24999
  /** @type {(value: string) => boolean} */
23293
25000
  const isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu);
23294
25001
 
@@ -23296,45 +25003,45 @@ const isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu);
23296
25003
  const isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu);
23297
25004
 
23298
25005
  /** @type {(value: string) => boolean} */
23299
- const isPathCharacter = RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);
25006
+ const isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u);
23300
25007
 
23301
- /**
23302
- * @param {Array<string>} input
23303
- * @returns {string}
23304
- */
23305
- function stringArrayToHexStripped (input) {
23306
- let acc = '';
23307
- let code = 0;
23308
- let i = 0;
25008
+ /** @type {(value: string) => boolean} */
25009
+ const isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u);
23309
25010
 
23310
- for (i = 0; i < input.length; i++) {
23311
- code = input[i].charCodeAt(0);
23312
- if (code === 48) {
23313
- continue
23314
- }
23315
- if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {
23316
- return ''
23317
- }
23318
- acc += input[i];
23319
- break
23320
- }
25011
+ /** @type {(value: string) => boolean} */
25012
+ const isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u);
23321
25013
 
23322
- for (i += 1; i < input.length; i++) {
23323
- code = input[i].charCodeAt(0);
23324
- if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {
23325
- return ''
23326
- }
23327
- acc += input[i];
25014
+ const BYTE_HEX = new Array(256);
25015
+ {
25016
+ const HEX_DIGITS = '0123456789ABCDEF';
25017
+ for (let i = 0; i < 256; i++) {
25018
+ BYTE_HEX[i] = '%' + HEX_DIGITS[i >> 4] + HEX_DIGITS[i & 0xF];
25019
+ }
25020
+ }
25021
+ function percentEncodeNonAscii (cp) {
25022
+ if (cp < 0x800) {
25023
+ return BYTE_HEX[0xC0 | (cp >> 6)] +
25024
+ BYTE_HEX[0x80 | (cp & 0x3F)]
25025
+ }
25026
+ if (cp < 0x10000) {
25027
+ return BYTE_HEX[0xE0 | (cp >> 12)] +
25028
+ BYTE_HEX[0x80 | ((cp >> 6) & 0x3F)] +
25029
+ BYTE_HEX[0x80 | (cp & 0x3F)]
23328
25030
  }
23329
- return acc
25031
+ return BYTE_HEX[0xF0 | (cp >> 18)] +
25032
+ BYTE_HEX[0x80 | ((cp >> 12) & 0x3F)] +
25033
+ BYTE_HEX[0x80 | ((cp >> 6) & 0x3F)] +
25034
+ BYTE_HEX[0x80 | (cp & 0x3F)]
23330
25035
  }
23331
25036
 
23332
- /**
23333
- * @typedef {Object} GetIPV6Result
23334
- * @property {boolean} error - Indicates if there was an error parsing the IPv6 address.
23335
- * @property {string} address - The parsed IPv6 address.
23336
- * @property {string} [zone] - The zone identifier, if present.
23337
- */
25037
+ /** @type {(value: string) => boolean} */
25038
+ const isHextet = RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/);
25039
+
25040
+ /** @type {(value: string) => boolean} */
25041
+ const isIPvFuture = RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/);
25042
+
25043
+ /** @type {(value: string) => boolean} */
25044
+ const isZoneCharacter = RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/);
23338
25045
 
23339
25046
  /**
23340
25047
  * @param {string} value
@@ -23343,88 +25050,104 @@ function stringArrayToHexStripped (input) {
23343
25050
  const nonSimpleDomain$1 = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);
23344
25051
 
23345
25052
  /**
23346
- * @param {Array<string>} buffer
25053
+ * @param {string} zone
23347
25054
  * @returns {boolean}
23348
25055
  */
23349
- function consumeIsZone (buffer) {
23350
- buffer.length = 0;
25056
+ function isZoneIdentifier (zone) {
25057
+ if (zone.length === 0) return false
25058
+
25059
+ for (let i = 0; i < zone.length; i++) {
25060
+ if (isZoneCharacter(zone[i])) continue
25061
+ if (zone[i] === '%' && i + 2 < zone.length && isHexPair(zone.slice(i + 1, i + 3))) {
25062
+ i += 2;
25063
+ continue
25064
+ }
25065
+ return false
25066
+ }
25067
+
23351
25068
  return true
23352
25069
  }
23353
25070
 
23354
25071
  /**
23355
- * @param {Array<string>} buffer
23356
- * @param {Array<string>} address
23357
- * @param {GetIPV6Result} output
23358
- * @returns {boolean}
25072
+ * Compresses the longest run of zero hextets to "::" per RFC 5952. A run of a
25073
+ * single zero hextet is left uncompressed. On ties the leftmost run wins.
25074
+ *
25075
+ * @param {string[]} hextets
25076
+ * @returns {string}
23359
25077
  */
23360
- function consumeHextets (buffer, address, output) {
23361
- if (buffer.length) {
23362
- const hex = stringArrayToHexStripped(buffer);
23363
- if (hex !== '') {
23364
- address.push(hex);
25078
+ function compressIPv6ZeroRun (hextets) {
25079
+ let bestStart = -1;
25080
+ let bestLength = 0;
25081
+ let runStart = -1;
25082
+ let runLength = 0;
25083
+ for (let i = 0; i < hextets.length; i++) {
25084
+ if (hextets[i] === '0') {
25085
+ if (runStart === -1) runStart = i;
25086
+ runLength++;
25087
+ if (runLength > bestLength) {
25088
+ bestLength = runLength;
25089
+ bestStart = runStart;
25090
+ }
23365
25091
  } else {
23366
- output.error = true;
23367
- return false
25092
+ runStart = -1;
25093
+ runLength = 0;
23368
25094
  }
23369
- buffer.length = 0;
23370
25095
  }
23371
- return true
25096
+
25097
+ if (bestLength < 2) return hextets.join(':')
25098
+
25099
+ const head = hextets.slice(0, bestStart).join(':');
25100
+ const tail = hextets.slice(bestStart + bestLength).join(':');
25101
+ return head + '::' + tail
23372
25102
  }
23373
25103
 
23374
25104
  /**
25105
+ * Validates an IPv6 address against the alternatives in RFC 3986 section
25106
+ * 3.2.2 and returns the same address with leading hextet zeroes removed.
25107
+ * An embedded IPv4 address counts as two hextets and is only valid at the end.
25108
+ *
23375
25109
  * @param {string} input
23376
- * @returns {GetIPV6Result}
25110
+ * @returns {string|undefined}
23377
25111
  */
23378
- function getIPV6 (input) {
23379
- let tokenCount = 0;
23380
- const output = { error: false, address: '', zone: '' };
23381
- /** @type {Array<string>} */
23382
- const address = [];
23383
- /** @type {Array<string>} */
23384
- const buffer = [];
23385
- let endipv6Encountered = false;
23386
- let endIpv6 = false;
25112
+ function normalizeIPv6Address (input) {
25113
+ const compression = input.indexOf('::');
25114
+ if (compression !== -1 && input.indexOf('::', compression + 1) !== -1) return undefined
23387
25115
 
23388
- let consume = consumeHextets;
25116
+ const left = compression === -1 ? input.split(':') : input.slice(0, compression).split(':');
25117
+ const right = compression === -1 ? [] : input.slice(compression + 2).split(':');
25118
+ if (compression !== -1) {
25119
+ if (left.length === 1 && left[0] === '') left.length = 0;
25120
+ if (right.length === 1 && right[0] === '') right.length = 0;
25121
+ }
23389
25122
 
23390
- for (let i = 0; i < input.length; i++) {
23391
- const cursor = input[i];
23392
- if (cursor === '[' || cursor === ']') { continue }
23393
- if (cursor === ':') {
23394
- if (endipv6Encountered === true) {
23395
- endIpv6 = true;
23396
- }
23397
- if (!consume(buffer, address, output)) { break }
23398
- if (++tokenCount > 7) {
23399
- // not valid
23400
- output.error = true;
23401
- break
23402
- }
23403
- if (i > 0 && input[i - 1] === ':') {
23404
- endipv6Encountered = true;
23405
- }
23406
- address.push(':');
23407
- continue
23408
- } else if (cursor === '%') {
23409
- if (!consume(buffer, address, output)) { break }
23410
- // switch to zone detection
23411
- consume = consumeIsZone;
23412
- } else {
23413
- buffer.push(cursor);
25123
+ const parts = left.concat(right);
25124
+ let hextetCount = 0;
25125
+ for (let i = 0; i < parts.length; i++) {
25126
+ const part = parts[i];
25127
+ if (part === '') return undefined
25128
+
25129
+ if (part.indexOf('.') !== -1) {
25130
+ if (i !== parts.length - 1 || (compression !== -1 && right.length === 0) || !isIPv4$1(part)) return undefined
25131
+ hextetCount += 2;
23414
25132
  continue
23415
25133
  }
25134
+
25135
+ if (!isHextet(part)) return undefined
25136
+ parts[i] = parseInt(part, 16).toString(16);
25137
+ hextetCount++;
23416
25138
  }
23417
- if (buffer.length) {
23418
- if (consume === consumeIsZone) {
23419
- output.zone = buffer.join('');
23420
- } else if (endIpv6) {
23421
- address.push(buffer.join(''));
23422
- } else {
23423
- address.push(stringArrayToHexStripped(buffer));
23424
- }
25139
+
25140
+ if (compression === -1) {
25141
+ if (hextetCount !== 8) return undefined
25142
+ return compressIPv6ZeroRun(parts)
23425
25143
  }
23426
- output.address = address.join('');
23427
- return output
25144
+ if (hextetCount >= 8) return undefined
25145
+
25146
+ // expand "::" then re-compress the longest run for a canonical result
25147
+ const expanded = parts.slice(0, left.length);
25148
+ for (let i = hextetCount; i < 8; i++) expanded.push('0');
25149
+ for (let i = left.length; i < parts.length; i++) expanded.push(parts[i]);
25150
+ return compressIPv6ZeroRun(expanded)
23428
25151
  }
23429
25152
 
23430
25153
  /**
@@ -23432,26 +25155,49 @@ function getIPV6 (input) {
23432
25155
  * @property {string} host - The normalized host.
23433
25156
  * @property {string} [escapedHost] - The escaped host.
23434
25157
  * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address.
25158
+ * @property {boolean} [isIPVFuture] - Indicates if the host is an IPvFuture literal.
25159
+ * @property {boolean} [error] - Indicates if a bracketed IP literal is malformed.
23435
25160
  */
23436
25161
 
23437
25162
  /**
25163
+ * Validates and normalizes a bracketed IP literal. Raw zone separators remain
25164
+ * accepted for backwards compatibility, while encoded separators and zone
25165
+ * contents follow RFC 6874.
25166
+ *
23438
25167
  * @param {string} host
23439
25168
  * @returns {NormalizeIPv6Result}
23440
25169
  */
23441
25170
  function normalizeIPv6$1 (host) {
23442
- if (findToken(host, ':') < 2) { return { host, isIPV6: false } }
23443
- const ipv6 = getIPV6(host);
25171
+ const bracketed = host[0] === '[' && host[host.length - 1] === ']';
25172
+ const hasBracket = host[0] === '[' || host[host.length - 1] === ']';
25173
+ if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }
25174
+
25175
+ let input = bracketed ? host.slice(1, -1) : host;
25176
+ if (bracketed && isIPvFuture(input)) {
25177
+ input = input.toLowerCase();
25178
+ return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }
25179
+ }
25180
+
25181
+ if (findToken(input, ':') < 2) {
25182
+ return { host, isIPV6: false, error: bracketed }
25183
+ }
25184
+
25185
+ let zoneIdentifier = '';
25186
+ const zoneSeparator = input.indexOf('%');
25187
+ if (zoneSeparator !== -1) {
25188
+ const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === '%25' ? 3 : 1;
25189
+ zoneIdentifier = input.slice(zoneSeparator + separatorLength);
25190
+ if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }
25191
+ input = input.slice(0, zoneSeparator);
25192
+ }
23444
25193
 
23445
- if (!ipv6.error) {
23446
- let newHost = ipv6.address;
23447
- let escapedHost = ipv6.address;
23448
- if (ipv6.zone) {
23449
- newHost += '%' + ipv6.zone;
23450
- escapedHost += '%25' + ipv6.zone;
23451
- }
23452
- return { host: newHost, isIPV6: true, escapedHost }
23453
- } else {
23454
- return { host, isIPV6: false }
25194
+ const address = normalizeIPv6Address(input);
25195
+ if (address === undefined) return { host, isIPV6: false, error: true }
25196
+
25197
+ return {
25198
+ host: address + (zoneIdentifier ? '%' + zoneIdentifier : ''),
25199
+ escapedHost: address + (zoneIdentifier ? '%25' + zoneIdentifier : ''),
25200
+ isIPV6: true
23455
25201
  }
23456
25202
  }
23457
25203
 
@@ -23577,7 +25323,7 @@ function reescapeHostDelimiters$1 (host, isIP) {
23577
25323
 
23578
25324
  /**
23579
25325
  * Normalizes percent escapes and optionally decodes only unreserved ASCII bytes.
23580
- * Reserved delimiters such as `%2F` and `%2E` stay escaped.
25326
+ * Reserved delimiters such as `%2F` stay escaped; `%2E` is unreserved.
23581
25327
  *
23582
25328
  * @param {string} input
23583
25329
  * @param {boolean} [decodeUnreserved=false]
@@ -23626,7 +25372,8 @@ function normalizePathEncoding$1 (input) {
23626
25372
  let output = '';
23627
25373
 
23628
25374
  for (let i = 0; i < input.length; i++) {
23629
- if (input[i] === '%' && i + 2 < input.length) {
25375
+ const ch = input[i];
25376
+ if (ch === '%' && i + 2 < input.length) {
23630
25377
  const hex = input.slice(i + 1, i + 3);
23631
25378
  if (isHexPair(hex)) {
23632
25379
  const normalizedHex = hex.toUpperCase();
@@ -23643,10 +25390,25 @@ function normalizePathEncoding$1 (input) {
23643
25390
  }
23644
25391
  }
23645
25392
 
23646
- if (isPathCharacter(input[i])) {
23647
- output += input[i];
25393
+ if (isPathCharacter(ch)) {
25394
+ output += ch;
23648
25395
  } else {
23649
- output += escape(input[i]);
25396
+ const code = input.charCodeAt(i);
25397
+ if (code < 0x80) {
25398
+ output += isEscapeSafe(code) ? ch : BYTE_HEX[code];
25399
+ } else if (code < 0xD800 || code > 0xDFFF) {
25400
+ output += percentEncodeNonAscii(code);
25401
+ } else if (code <= 0xDBFF && i + 1 < input.length) {
25402
+ const low = input.charCodeAt(i + 1);
25403
+ if (low >= 0xDC00 && low <= 0xDFFF) {
25404
+ output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00));
25405
+ i++;
25406
+ } else {
25407
+ output += percentEncodeNonAscii(0xFFFD);
25408
+ }
25409
+ } else {
25410
+ output += percentEncodeNonAscii(0xFFFD);
25411
+ }
23650
25412
  }
23651
25413
  }
23652
25414
 
@@ -23654,16 +25416,73 @@ function normalizePathEncoding$1 (input) {
23654
25416
  }
23655
25417
 
23656
25418
  /**
23657
- * Escapes a component while preserving existing valid percent escapes.
25419
+ * Serializes a path without rewriting reserved data. Raw RFC 3986 path
25420
+ * characters remain literal, valid escapes are preserved and uppercased, and
25421
+ * everything else is UTF-8 percent-encoded. In a path-noscheme, a colon in the
25422
+ * first segment must be escaped so the result cannot be parsed as a scheme.
23658
25423
  *
23659
25424
  * @param {string} input
25425
+ * @param {boolean} [pathNoScheme=false]
23660
25426
  * @returns {string}
23661
25427
  */
23662
- function escapePreservingEscapes$1 (input) {
25428
+ function serializePathEncoding$1 (input, pathNoScheme = false) {
23663
25429
  let output = '';
25430
+ let firstSegment = pathNoScheme && input[0] !== '/';
23664
25431
 
23665
25432
  for (let i = 0; i < input.length; i++) {
23666
- if (input[i] === '%' && i + 2 < input.length) {
25433
+ const ch = input[i];
25434
+ if (ch === '%' && i + 2 < input.length) {
25435
+ const hex = input.slice(i + 1, i + 3);
25436
+ if (isHexPair(hex)) {
25437
+ output += '%' + hex.toUpperCase();
25438
+ i += 2;
25439
+ continue
25440
+ }
25441
+ }
25442
+
25443
+ if (ch === '/') {
25444
+ firstSegment = false;
25445
+ }
25446
+
25447
+ if (isPathCharacter(ch) && (ch !== ':' || !firstSegment)) {
25448
+ output += ch;
25449
+ } else {
25450
+ const code = input.charCodeAt(i);
25451
+ if (code < 0x80) {
25452
+ output += BYTE_HEX[code];
25453
+ } else if (code < 0xD800 || code > 0xDFFF) {
25454
+ output += percentEncodeNonAscii(code);
25455
+ } else if (code <= 0xDBFF && i + 1 < input.length) {
25456
+ const low = input.charCodeAt(i + 1);
25457
+ if (low >= 0xDC00 && low <= 0xDFFF) {
25458
+ output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00));
25459
+ i++;
25460
+ } else {
25461
+ output += percentEncodeNonAscii(0xFFFD);
25462
+ }
25463
+ } else {
25464
+ output += percentEncodeNonAscii(0xFFFD);
25465
+ }
25466
+ }
25467
+ }
25468
+
25469
+ return output
25470
+ }
25471
+
25472
+ /**
25473
+ * Percent-encodes a URI component using its RFC 3986 literal character set.
25474
+ * Existing valid escapes are preserved and normalized to uppercase hex.
25475
+ *
25476
+ * @param {string} input
25477
+ * @param {(value: string) => boolean} isAllowed
25478
+ * @returns {string}
25479
+ */
25480
+ function encodeComponent (input, isAllowed) {
25481
+ let output = '';
25482
+
25483
+ for (let i = 0; i < input.length; i++) {
25484
+ const ch = input[i];
25485
+ if (ch === '%' && i + 2 < input.length) {
23667
25486
  const hex = input.slice(i + 1, i + 3);
23668
25487
  if (isHexPair(hex)) {
23669
25488
  output += '%' + hex.toUpperCase();
@@ -23672,7 +25491,125 @@ function escapePreservingEscapes$1 (input) {
23672
25491
  }
23673
25492
  }
23674
25493
 
23675
- output += escape(input[i]);
25494
+ if (isAllowed(ch)) {
25495
+ output += ch;
25496
+ } else {
25497
+ const code = input.charCodeAt(i);
25498
+ if (code < 0x80) {
25499
+ output += BYTE_HEX[code];
25500
+ } else if (code < 0xD800 || code > 0xDFFF) {
25501
+ output += percentEncodeNonAscii(code);
25502
+ } else if (code <= 0xDBFF && i + 1 < input.length) {
25503
+ const low = input.charCodeAt(i + 1);
25504
+ if (low >= 0xDC00 && low <= 0xDFFF) {
25505
+ output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00));
25506
+ i++;
25507
+ } else {
25508
+ output += percentEncodeNonAscii(0xFFFD);
25509
+ }
25510
+ } else {
25511
+ output += percentEncodeNonAscii(0xFFFD);
25512
+ }
25513
+ }
25514
+ }
25515
+
25516
+ return output
25517
+ }
25518
+
25519
+ /**
25520
+ * Encodes userinfo while preserving its RFC 3986 §3.2.1 literal characters.
25521
+ * In particular, authority delimiters such as `@`, `/`, `?`, and `#` are data.
25522
+ *
25523
+ * @param {string} input
25524
+ * @returns {string}
25525
+ */
25526
+ function encodeUserinfo (input) {
25527
+ return encodeComponent(input, isUserinfoCharacter)
25528
+ }
25529
+
25530
+ /**
25531
+ * Encodes query data using the RFC 3986 §3.4 grammar. A literal `#` must be
25532
+ * escaped because it would otherwise begin the fragment component.
25533
+ *
25534
+ * @param {string} input
25535
+ * @returns {string}
25536
+ */
25537
+ function encodeQuery$1 (input) {
25538
+ return encodeComponent(input, isQueryFragmentCharacter)
25539
+ }
25540
+
25541
+ /**
25542
+ * Encodes fragment data using the RFC 3986 §3.5 grammar.
25543
+ *
25544
+ * @param {string} input
25545
+ * @returns {string}
25546
+ */
25547
+ function encodeFragment$1 (input) {
25548
+ return encodeComponent(input, isQueryFragmentCharacter)
25549
+ }
25550
+
25551
+ function isEscapeSafe (cp) {
25552
+ return (
25553
+ (cp >= 0x30 && cp <= 0x39) ||
25554
+ (cp >= 0x41 && cp <= 0x5A) ||
25555
+ (cp >= 0x61 && cp <= 0x7A) ||
25556
+ cp === 0x2A || cp === 0x2B || cp === 0x2D || cp === 0x2E ||
25557
+ cp === 0x2F || cp === 0x40 || cp === 0x5F
25558
+ )
25559
+ }
25560
+
25561
+ /**
25562
+ * Normalizes the percent-encoding of a query or fragment component.
25563
+ *
25564
+ * Like `normalizePathEncoding`, but uses the query/fragment character set
25565
+ * (which additionally allows `?`) and decodes `.` since it has no dot-segment
25566
+ * meaning outside of a path.
25567
+ *
25568
+ * @param {string} input
25569
+ * @returns {string}
25570
+ */
25571
+ function normalizeQueryFragmentEncoding$1 (input) {
25572
+ let output = '';
25573
+
25574
+ for (let i = 0; i < input.length; i++) {
25575
+ const ch = input[i];
25576
+ if (ch === '%' && i + 2 < input.length) {
25577
+ const hex = input.slice(i + 1, i + 3);
25578
+ if (isHexPair(hex)) {
25579
+ const normalizedHex = hex.toUpperCase();
25580
+ const decoded = String.fromCharCode(parseInt(normalizedHex, 16));
25581
+
25582
+ if (isUnreserved(decoded)) {
25583
+ output += decoded;
25584
+ } else {
25585
+ output += '%' + normalizedHex;
25586
+ }
25587
+
25588
+ i += 2;
25589
+ continue
25590
+ }
25591
+ }
25592
+
25593
+ if (isQueryFragmentCharacter(ch)) {
25594
+ output += ch;
25595
+ } else {
25596
+ const code = input.charCodeAt(i);
25597
+ if (code < 0x80) {
25598
+ output += isEscapeSafe(code) ? ch : BYTE_HEX[code];
25599
+ } else if (code < 0xD800 || code > 0xDFFF) {
25600
+ output += percentEncodeNonAscii(code);
25601
+ } else if (code <= 0xDBFF && i + 1 < input.length) {
25602
+ const low = input.charCodeAt(i + 1);
25603
+ if (low >= 0xDC00 && low <= 0xDFFF) {
25604
+ output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00));
25605
+ i++;
25606
+ } else {
25607
+ output += percentEncodeNonAscii(0xFFFD);
25608
+ }
25609
+ } else {
25610
+ output += percentEncodeNonAscii(0xFFFD);
25611
+ }
25612
+ }
23676
25613
  }
23677
25614
 
23678
25615
  return output
@@ -23686,15 +25623,21 @@ function recomposeAuthority$1 (component) {
23686
25623
  const uriTokens = [];
23687
25624
 
23688
25625
  if (component.userinfo !== undefined) {
23689
- uriTokens.push(component.userinfo);
25626
+ uriTokens.push(encodeUserinfo(component.userinfo));
23690
25627
  uriTokens.push('@');
23691
25628
  }
23692
25629
 
23693
25630
  if (component.host !== undefined) {
23694
- let host = unescape(component.host);
25631
+ let host = component.host;
23695
25632
  if (!isIPv4$1(host)) {
23696
- const ipV6res = normalizeIPv6$1(host);
23697
- if (ipV6res.isIPV6 === true) {
25633
+ let ipV6res = normalizeIPv6$1(host);
25634
+ if (ipV6res.isIPV6 !== true && ipV6res.isIPVFuture !== true) {
25635
+ // Decode only unreserved bytes, once. In particular, keep %25 encoded
25636
+ // so it cannot introduce a second escape during recomposition.
25637
+ host = normalizePercentEncoding$1(host, true);
25638
+ ipV6res = normalizeIPv6$1(host);
25639
+ }
25640
+ if (ipV6res.isIPV6 === true || ipV6res.isIPVFuture === true) {
23698
25641
  host = `[${ipV6res.escapedHost}]`;
23699
25642
  } else {
23700
25643
  host = reescapeHostDelimiters$1(host, false);
@@ -23704,8 +25647,12 @@ function recomposeAuthority$1 (component) {
23704
25647
  }
23705
25648
 
23706
25649
  if (typeof component.port === 'number' || typeof component.port === 'string') {
25650
+ const port = String(component.port);
25651
+ if (!isPort(port)) {
25652
+ throw new TypeError('URI port is malformed.')
25653
+ }
23707
25654
  uriTokens.push(':');
23708
- uriTokens.push(String(component.port));
25655
+ uriTokens.push(port);
23709
25656
  }
23710
25657
 
23711
25658
  return uriTokens.length ? uriTokens.join('') : undefined
@@ -23716,14 +25663,17 @@ var utils = {
23716
25663
  reescapeHostDelimiters: reescapeHostDelimiters$1,
23717
25664
  normalizePercentEncoding: normalizePercentEncoding$1,
23718
25665
  normalizePathEncoding: normalizePathEncoding$1,
23719
- escapePreservingEscapes: escapePreservingEscapes$1,
25666
+ serializePathEncoding: serializePathEncoding$1,
25667
+ normalizeQueryFragmentEncoding: normalizeQueryFragmentEncoding$1,
25668
+ encodeQuery: encodeQuery$1,
25669
+ encodeFragment: encodeFragment$1,
23720
25670
  removeDotSegments: removeDotSegments$1,
23721
25671
  isIPv4: isIPv4$1,
23722
25672
  isUUID: isUUID$1,
23723
25673
  normalizeIPv6: normalizeIPv6$1};
23724
25674
 
23725
25675
  const { isUUID } = utils;
23726
- const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;
25676
+ const URN_REG = /^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu;
23727
25677
 
23728
25678
  /**
23729
25679
  * @callback SchemeFn
@@ -23822,9 +25772,14 @@ function wsSerialize (wsComponent) {
23822
25772
 
23823
25773
  // reconstruct path from resource name
23824
25774
  if (wsComponent.resourceName) {
23825
- const [path, query] = wsComponent.resourceName.split('?');
25775
+ const queryIndex = wsComponent.resourceName.indexOf('?');
25776
+ const path = queryIndex === -1
25777
+ ? wsComponent.resourceName
25778
+ : wsComponent.resourceName.slice(0, queryIndex);
23826
25779
  wsComponent.path = (path && path !== '/' ? path : undefined);
23827
- wsComponent.query = query;
25780
+ wsComponent.query = queryIndex === -1
25781
+ ? undefined
25782
+ : wsComponent.resourceName.slice(queryIndex + 1);
23828
25783
  wsComponent.resourceName = undefined;
23829
25784
  }
23830
25785
 
@@ -23841,7 +25796,7 @@ function urnParse (urnComponent, options) {
23841
25796
  return urnComponent
23842
25797
  }
23843
25798
  const matches = urnComponent.path.match(URN_REG);
23844
- if (matches) {
25799
+ if (matches && matches[0] === urnComponent.path) {
23845
25800
  const scheme = options.scheme || urnComponent.scheme || 'urn';
23846
25801
  urnComponent.nid = matches[1].toLowerCase();
23847
25802
  urnComponent.nss = matches[2];
@@ -23973,9 +25928,24 @@ var schemes = {
23973
25928
  getSchemeHandler: getSchemeHandler$1,
23974
25929
  };
23975
25930
 
23976
- const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, escapePreservingEscapes, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = utils;
25931
+ const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = utils;
23977
25932
  const { SCHEMES, getSchemeHandler } = schemes;
23978
25933
 
25934
+ const VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/u;
25935
+ const MALFORMED_SCHEME_ERROR = 'URI scheme is malformed.';
25936
+
25937
+ /**
25938
+ * @param {string} scheme
25939
+ * @returns {string}
25940
+ */
25941
+ function decodeValidScheme (scheme) {
25942
+ const decodedScheme = unescape(String(scheme));
25943
+ if (!VALID_SCHEME.test(decodedScheme)) {
25944
+ throw new TypeError(MALFORMED_SCHEME_ERROR)
25945
+ }
25946
+ return decodedScheme
25947
+ }
25948
+
23979
25949
  /**
23980
25950
  * @template {import('./types/index').URIComponent|string} T
23981
25951
  * @param {T} uri
@@ -23999,7 +25969,50 @@ function normalize (uri, options) {
23999
25969
  */
24000
25970
  function resolve (baseURI, relativeURI, options) {
24001
25971
  const schemelessOptions = options ? Object.assign({ scheme: 'null' }, options) : { scheme: 'null' };
24002
- const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true);
25972
+ const {
25973
+ parsed: baseParsed,
25974
+ malformedAuthorityOrPort: baseMalformed,
25975
+ malformedPercentEncoding: baseMalformedPercentEncoding,
25976
+ malformedSchemeSpecific: baseMalformedSchemeSpecific,
25977
+ malformedHost: baseMalformedHost,
25978
+ malformedScheme: baseMalformedScheme
25979
+ } = parseWithStatus(baseURI, schemelessOptions);
25980
+ const {
25981
+ parsed: relativeParsed,
25982
+ malformedAuthorityOrPort: relativeMalformed,
25983
+ malformedPercentEncoding: relativeMalformedPercentEncoding,
25984
+ malformedSchemeSpecific: relativeMalformedSchemeSpecific,
25985
+ malformedHost: relativeMalformedHost,
25986
+ malformedScheme: relativeMalformedScheme
25987
+ } = parseWithStatus(relativeURI, schemelessOptions);
25988
+ if (
25989
+ baseMalformed ||
25990
+ relativeMalformed ||
25991
+ baseMalformedPercentEncoding ||
25992
+ relativeMalformedPercentEncoding ||
25993
+ baseMalformedSchemeSpecific ||
25994
+ relativeMalformedSchemeSpecific ||
25995
+ baseMalformedHost ||
25996
+ relativeMalformedHost ||
25997
+ baseMalformedScheme ||
25998
+ relativeMalformedScheme
25999
+ ) {
26000
+ throw new Error(baseParsed.error || relativeParsed.error || 'URI is malformed.')
26001
+ }
26002
+ const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true);
26003
+ const resolvedSchemeHandler = getSchemeHandler((options && options.scheme) || resolved.scheme);
26004
+ const resolvedHost = resolved.host;
26005
+ const resolvedHostIsIP = resolvedHost !== undefined && resolvedHost !== '' &&
26006
+ (isIPv4(resolvedHost) || normalizeIPv6(resolvedHost).isIPV6);
26007
+ canonicalizeHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP);
26008
+ // Percent escapes in an ASCII reg-name are encoded data. The WHATWG hostname
26009
+ // parser can reject them even though fast-uri preserves them safely as RFC
26010
+ // 3986 data. A raw non-ASCII host must still fail closed if conversion fails.
26011
+ const encodedASCIIHost = resolvedHost && resolvedHost.indexOf('%') !== -1 &&
26012
+ !/\P{ASCII}/u.test(resolvedHost);
26013
+ if (resolved.error && !encodedASCIIHost) {
26014
+ throw new Error(resolved.error)
26015
+ }
24003
26016
  schemelessOptions.skipEscape = true;
24004
26017
  return serialize(resolved, schemelessOptions)
24005
26018
  }
@@ -24082,7 +26095,7 @@ function equal$2 (uriA, uriB, options) {
24082
26095
  const normalizedA = normalizeComparableURI(uriA, options);
24083
26096
  const normalizedB = normalizeComparableURI(uriB, options);
24084
26097
 
24085
- return normalizedA !== undefined && normalizedB !== undefined && normalizedA.toLowerCase() === normalizedB.toLowerCase()
26098
+ return normalizedA !== undefined && normalizedB !== undefined && normalizedA === normalizedB
24086
26099
  }
24087
26100
 
24088
26101
  /**
@@ -24110,25 +26123,30 @@ function serialize (cmpts, opts) {
24110
26123
  const options = Object.assign({}, opts);
24111
26124
  const uriTokens = [];
24112
26125
 
26126
+ if (component.scheme) {
26127
+ component.scheme = decodeValidScheme(component.scheme);
26128
+ }
26129
+
24113
26130
  // find scheme handler
24114
26131
  const schemeHandler = getSchemeHandler(options.scheme || component.scheme);
24115
26132
 
24116
26133
  // perform scheme specific serialization
24117
26134
  if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options);
24118
26135
 
26136
+ const hasAuthority = component.userinfo !== undefined || component.host !== undefined || component.port !== undefined;
26137
+ const pathNoScheme = !options.skipEscape && component.scheme === undefined && !hasAuthority;
26138
+
24119
26139
  if (component.path !== undefined) {
24120
26140
  if (!options.skipEscape) {
24121
- component.path = escapePreservingEscapes(component.path);
24122
-
24123
- if (component.scheme !== undefined) {
24124
- component.path = component.path.split('%3A').join(':');
24125
- }
26141
+ component.path = serializePathEncoding(component.path, pathNoScheme);
24126
26142
  } else {
24127
26143
  component.path = normalizePercentEncoding(component.path);
24128
26144
  }
24129
26145
  }
24130
26146
 
24131
26147
  if (options.reference !== 'suffix' && component.scheme) {
26148
+ // Scheme handlers may replace the scheme during serialization.
26149
+ component.scheme = decodeValidScheme(component.scheme);
24132
26150
  uriTokens.push(component.scheme, ':');
24133
26151
  }
24134
26152
 
@@ -24151,6 +26169,13 @@ function serialize (cmpts, opts) {
24151
26169
  s = removeDotSegments(s);
24152
26170
  }
24153
26171
 
26172
+ // Dot-segment removal can expose a colon that was not originally in the
26173
+ // first segment (for example, "./a:b"). Reapply path-noscheme encoding so
26174
+ // the serialized relative reference cannot be reparsed as a URI scheme.
26175
+ if (pathNoScheme) {
26176
+ s = serializePathEncoding(s, true);
26177
+ }
26178
+
24154
26179
  if (
24155
26180
  authority === undefined &&
24156
26181
  s[0] === '/' &&
@@ -24164,11 +26189,11 @@ function serialize (cmpts, opts) {
24164
26189
  }
24165
26190
 
24166
26191
  if (component.query !== undefined) {
24167
- uriTokens.push('?', component.query);
26192
+ uriTokens.push('?', encodeQuery(component.query));
24168
26193
  }
24169
26194
 
24170
26195
  if (component.fragment !== undefined) {
24171
- uriTokens.push('#', component.fragment);
26196
+ uriTokens.push('#', encodeFragment(component.fragment));
24172
26197
  }
24173
26198
  return uriTokens.join('')
24174
26199
  }
@@ -24179,6 +26204,15 @@ const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:
24179
26204
  // with or without a scheme prefix, for the literal-backslash rejection below.
24180
26205
  const AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/;
24181
26206
 
26207
+ // Captures the leading authority-introducer region after an optional scheme: a
26208
+ // run of forward slashes, backslashes, and the characters the WHATWG URL parser
26209
+ // removes before parsing (TAB U+0009, LF U+000A, CR U+000D). A valid introducer
26210
+ // is exactly "//". Node treats "\" as "/" on special schemes and strips those
26211
+ // characters first, so forms like "\\", "/\", "\/", "/<TAB>/", or a leading
26212
+ // "<TAB>//" reach an authority in Node while fast-uri's URI_PARSE folds them into
26213
+ // the path group (host confusion / SSRF / redirect bypass).
26214
+ const AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;
26215
+
24182
26216
  /**
24183
26217
  * @param {import('./types/index').URIComponent} parsed
24184
26218
  * @param {RegExpMatchArray} matches
@@ -24196,10 +26230,86 @@ function getParseError (parsed, matches) {
24196
26230
  return undefined
24197
26231
  }
24198
26232
 
26233
+ /**
26234
+ * Checks percent syntax without decoding the represented octets. RFC 3986
26235
+ * percent-encoding is byte-oriented, so sequences such as `%FF` are valid even
26236
+ * though they are not independently valid UTF-8.
26237
+ *
26238
+ * @param {string|undefined} component
26239
+ * @returns {boolean}
26240
+ */
26241
+ function hasMalformedPercentEncoding (component) {
26242
+ if (component === undefined) return false
26243
+
26244
+ let percent = component.indexOf('%');
26245
+ while (percent !== -1) {
26246
+ if (percent + 2 >= component.length || !/^[\da-f]{2}$/iu.test(component.slice(percent + 1, percent + 3))) {
26247
+ return true
26248
+ }
26249
+ percent = component.indexOf('%', percent + 3);
26250
+ }
26251
+
26252
+ return false
26253
+ }
26254
+
26255
+ /**
26256
+ * Whether the host is a bracketed IP literal (RFC 3986 `IP-literal`).
26257
+ * An unterminated `[` is not a literal, so it must still be validated as a
26258
+ * reg-name instead of being waved through as an IP.
26259
+ *
26260
+ * @param {string} host
26261
+ * @returns {boolean}
26262
+ */
26263
+ function isIPLiteral (host) {
26264
+ return host[0] === '[' && host[host.length - 1] === ']'
26265
+ }
26266
+
26267
+ /**
26268
+ * @param {RegExpMatchArray} matches
26269
+ * @returns {boolean}
26270
+ */
26271
+ function hasMalformedComponentPercentEncoding (matches) {
26272
+ // Bracketed IP literals use a raw "%" as the zone separator for historical
26273
+ // compatibility. Their parsing is intentionally left to normalizeIPv6.
26274
+ const host = matches[4];
26275
+ return hasMalformedPercentEncoding(matches[3]) ||
26276
+ (host !== undefined && !isIPLiteral(host) && hasMalformedPercentEncoding(host)) ||
26277
+ hasMalformedPercentEncoding(matches[6]) ||
26278
+ hasMalformedPercentEncoding(matches[7]) ||
26279
+ hasMalformedPercentEncoding(matches[8])
26280
+ }
26281
+
26282
+ /**
26283
+ * @param {import('./types/index').URIComponent} parsed
26284
+ * @param {import('./types/index').Options} options
26285
+ * @param {{ domainHost?: boolean, unicodeSupport?: boolean }|undefined} schemeHandler
26286
+ * @param {boolean} isIP
26287
+ * @returns {boolean} whether host conversion failed
26288
+ */
26289
+ function canonicalizeHost (parsed, options, schemeHandler, isIP) {
26290
+ if (
26291
+ !options.unicodeSupport &&
26292
+ (!schemeHandler || !schemeHandler.unicodeSupport) &&
26293
+ parsed.host &&
26294
+ !isIPLiteral(parsed.host) &&
26295
+ (options.domainHost || (schemeHandler && schemeHandler.domainHost)) &&
26296
+ isIP === false &&
26297
+ nonSimpleDomain(parsed.host)
26298
+ ) {
26299
+ try {
26300
+ parsed.host = new URL('http://' + parsed.host).hostname;
26301
+ } catch (e) {
26302
+ parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
26303
+ return true
26304
+ }
26305
+ }
26306
+ return false
26307
+ }
26308
+
24199
26309
  /**
24200
26310
  * @param {string} uri
24201
26311
  * @param {import('./types/index').Options} [opts]
24202
- * @returns {{ parsed: import('./types/index').URIComponent, malformedAuthorityOrPort: boolean }}
26312
+ * @returns {{ parsed: import('./types/index').URIComponent, malformedAuthorityOrPort: boolean, malformedPercentEncoding: boolean, malformedSchemeSpecific: boolean, malformedHost: boolean, malformedScheme: boolean }}
24203
26313
  */
24204
26314
  function parseWithStatus (uri, opts) {
24205
26315
  const options = Object.assign({}, opts);
@@ -24215,6 +26325,11 @@ function parseWithStatus (uri, opts) {
24215
26325
  };
24216
26326
 
24217
26327
  let malformedAuthorityOrPort = false;
26328
+ let malformedPercentEncoding = false;
26329
+ let malformedSchemeSpecific = false;
26330
+ let malformedHost = false;
26331
+ let malformedIPLiteral = false;
26332
+ let malformedScheme = false;
24218
26333
 
24219
26334
  let isIP = false;
24220
26335
  if (options.reference === 'suffix') {
@@ -24238,6 +26353,28 @@ function parseWithStatus (uri, opts) {
24238
26353
  malformedAuthorityOrPort = true;
24239
26354
  }
24240
26355
 
26356
+ // Reject a malformed or whitespace-smuggled authority introducer. fast-uri
26357
+ // only recognizes a literal "//"; anything else in the leading separator run
26358
+ // (a backslash, or a "//" that appears only after removing the TAB/LF/CR that
26359
+ // Node strips) means the authority fast-uri parses differs from the one Node's
26360
+ // URL resolves. Reject rather than rewrite, mirroring the literal-backslash
26361
+ // guard above. Percent-encoded forms (%5C, %09) are untouched, valid data.
26362
+ const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION);
26363
+ if (introducerMatch !== null) {
26364
+ const region = introducerMatch[1];
26365
+ const normalizedRegion = region.replace(/[\t\n\r]/g, '');
26366
+ // Two or more leading separators introduce an authority.
26367
+ if (normalizedRegion.length >= 2) {
26368
+ if (normalizedRegion.slice(0, 2) !== '//') {
26369
+ parsed.error = parsed.error || 'URI authority must not contain a literal backslash.';
26370
+ malformedAuthorityOrPort = true;
26371
+ } else if (region.length !== normalizedRegion.length) {
26372
+ parsed.error = parsed.error || 'URI authority introducer must not contain whitespace.';
26373
+ malformedAuthorityOrPort = true;
26374
+ }
26375
+ }
26376
+ }
26377
+
24241
26378
  const matches = uri.match(URI_PARSE);
24242
26379
 
24243
26380
  if (matches) {
@@ -24250,6 +26387,21 @@ function parseWithStatus (uri, opts) {
24250
26387
  parsed.query = matches[7];
24251
26388
  parsed.fragment = matches[8];
24252
26389
 
26390
+ if (parsed.scheme !== undefined) {
26391
+ const decodedScheme = unescape(parsed.scheme);
26392
+ if (VALID_SCHEME.test(decodedScheme)) {
26393
+ parsed.scheme = decodedScheme.toLowerCase();
26394
+ } else {
26395
+ parsed.error = parsed.error || MALFORMED_SCHEME_ERROR;
26396
+ malformedScheme = true;
26397
+ }
26398
+ }
26399
+
26400
+ malformedPercentEncoding = hasMalformedComponentPercentEncoding(matches);
26401
+ if (malformedPercentEncoding) {
26402
+ parsed.error = parsed.error || 'URI contains malformed percent-encoding.';
26403
+ }
26404
+
24253
26405
  // fix port number
24254
26406
  if (isNaN(parsed.port)) {
24255
26407
  parsed.port = matches[5];
@@ -24264,9 +26416,17 @@ function parseWithStatus (uri, opts) {
24264
26416
  if (parsed.host) {
24265
26417
  const ipv4result = isIPv4(parsed.host);
24266
26418
  if (ipv4result === false) {
26419
+ const bracketedIPLiteral = isIPLiteral(parsed.host);
26420
+ const hasIPLiteralBracket = parsed.host.indexOf('[') !== -1 || parsed.host.indexOf(']') !== -1;
24267
26421
  const ipv6result = normalizeIPv6(parsed.host);
24268
- parsed.host = ipv6result.host.toLowerCase();
24269
- isIP = ipv6result.isIPV6;
26422
+ isIP = ipv6result.isIPV6 || ipv6result.isIPVFuture === true;
26423
+ malformedIPLiteral = hasIPLiteralBracket && (!bracketedIPLiteral || ipv6result.error === true);
26424
+ parsed.host = isIP ? ipv6result.host : ipv6result.host.toLowerCase();
26425
+
26426
+ if (malformedIPLiteral) {
26427
+ parsed.error = parsed.error || 'URI host is malformed.';
26428
+ malformedAuthorityOrPort = true;
26429
+ }
24270
26430
  } else {
24271
26431
  isIP = true;
24272
26432
  }
@@ -24289,49 +26449,44 @@ function parseWithStatus (uri, opts) {
24289
26449
  // find scheme handler
24290
26450
  const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);
24291
26451
 
24292
- // check if scheme can't handle IRIs
24293
- if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
24294
- // if host component is a domain name
24295
- if (parsed.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost)) && isIP === false && nonSimpleDomain(parsed.host)) {
24296
- // convert Unicode IDN -> ASCII IDN
24297
- try {
24298
- parsed.host = new URL('http://' + parsed.host).hostname;
24299
- } catch (e) {
24300
- parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
24301
- }
26452
+ // convert Unicode IDN -> ASCII IDN when the effective scheme uses domain hosts
26453
+ if (!malformedIPLiteral) {
26454
+ malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP);
26455
+ }
26456
+
26457
+ if (uri.indexOf('%') !== -1 && parsed.host !== undefined && !malformedIPLiteral) {
26458
+ let host = isIP ? parsed.host : normalizePercentEncoding(parsed.host, true);
26459
+ if (!isIP) {
26460
+ // Fold reg-name case after decoding unreserved octets. The second
26461
+ // pass only restores uppercase hex in escapes that remain encoded.
26462
+ host = normalizePercentEncoding(host.toLowerCase());
24302
26463
  }
24303
- // convert IRI -> URI
26464
+ parsed.host = reescapeHostDelimiters(host, isIP);
24304
26465
  }
24305
26466
 
24306
26467
  if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) {
24307
- if (uri.indexOf('%') !== -1) {
24308
- if (parsed.scheme !== undefined) {
24309
- parsed.scheme = unescape(parsed.scheme);
24310
- }
24311
- if (parsed.host !== undefined) {
24312
- parsed.host = reescapeHostDelimiters(unescape(parsed.host), isIP);
24313
- }
24314
- }
24315
26468
  if (parsed.path) {
24316
26469
  parsed.path = normalizePathEncoding(parsed.path);
24317
26470
  }
26471
+ if (parsed.query) {
26472
+ parsed.query = normalizeQueryFragmentEncoding(parsed.query);
26473
+ }
24318
26474
  if (parsed.fragment) {
24319
- try {
24320
- parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment));
24321
- } catch {
24322
- parsed.error = parsed.error || 'URI malformed';
24323
- }
26475
+ parsed.fragment = normalizeQueryFragmentEncoding(parsed.fragment);
24324
26476
  }
24325
26477
  }
24326
26478
 
24327
26479
  // perform scheme specific parsing
24328
26480
  if (schemeHandler && schemeHandler.parse) {
24329
26481
  schemeHandler.parse(parsed, options);
26482
+ if (schemeHandler === SCHEMES.urn && parsed.nid === undefined) {
26483
+ malformedSchemeSpecific = true;
26484
+ }
24330
26485
  }
24331
26486
  } else {
24332
26487
  parsed.error = parsed.error || 'URI can not be parsed.';
24333
26488
  }
24334
- return { parsed, malformedAuthorityOrPort }
26489
+ return { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme }
24335
26490
  }
24336
26491
 
24337
26492
  /**
@@ -24355,13 +26510,17 @@ function normalizeString (uri, opts) {
24355
26510
  /**
24356
26511
  * @param {string} uri
24357
26512
  * @param {import('./types/index').Options} [opts]
24358
- * @returns {{ normalized: string, malformedAuthorityOrPort: boolean }}
26513
+ * @returns {{ normalized: string, malformedAuthorityOrPort: boolean, malformedPercentEncoding: boolean, malformedSchemeSpecific: boolean, malformedHost: boolean, malformedScheme: boolean }}
24359
26514
  */
24360
26515
  function normalizeStringWithStatus (uri, opts) {
24361
- const { parsed, malformedAuthorityOrPort } = parseWithStatus(uri, opts);
26516
+ const { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = parseWithStatus(uri, opts);
24362
26517
  return {
24363
- normalized: malformedAuthorityOrPort ? uri : serialize(parsed, opts),
24364
- malformedAuthorityOrPort
26518
+ normalized: malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? uri : serialize(parsed, opts),
26519
+ malformedAuthorityOrPort,
26520
+ malformedPercentEncoding,
26521
+ malformedSchemeSpecific,
26522
+ malformedHost,
26523
+ malformedScheme
24365
26524
  }
24366
26525
  }
24367
26526
 
@@ -24371,14 +26530,18 @@ function normalizeStringWithStatus (uri, opts) {
24371
26530
  * @returns {string|undefined}
24372
26531
  */
24373
26532
  function normalizeComparableURI (uri, opts) {
24374
- if (typeof uri === 'string') {
24375
- const { normalized, malformedAuthorityOrPort } = normalizeStringWithStatus(uri, opts);
24376
- return malformedAuthorityOrPort ? undefined : normalized
26533
+ if (typeof uri !== 'string' && typeof uri !== 'object') {
26534
+ return undefined
24377
26535
  }
24378
26536
 
24379
- if (typeof uri === 'object') {
24380
- return serialize(uri, opts)
26537
+ let value;
26538
+ try {
26539
+ value = typeof uri === 'string' ? uri : serialize(uri, opts);
26540
+ } catch {
26541
+ return undefined
24381
26542
  }
26543
+ const { normalized, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = normalizeStringWithStatus(value, opts);
26544
+ return malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? undefined : normalized
24382
26545
  }
24383
26546
 
24384
26547
  const fastUri = {
@@ -28342,6 +30505,27 @@ function reportToolCall(toolName, success, durationMs, error, sessionId, clientV
28342
30505
  metaVrTelemetry(args, clientVersion);
28343
30506
  }
28344
30507
 
30508
+ /**
30509
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
30510
+ *
30511
+ * This source code is licensed under the MIT license found in the
30512
+ * LICENSE file in the root directory of this source tree.
30513
+ */
30514
+ function isScreenshotResult(value) {
30515
+ return (typeof value === 'object' &&
30516
+ value !== null &&
30517
+ !Array.isArray(value) &&
30518
+ typeof value.imageData === 'string');
30519
+ }
30520
+ async function saveScreenshot(result, requestedPath) {
30521
+ const extension = result.mimeType === 'image/jpeg' ? 'jpg' : 'png';
30522
+ const outputPath = requestedPath ??
30523
+ path.join(os.tmpdir(), `iwsdk-screenshot-${randomUUID$1()}.${extension}`);
30524
+ await mkdir(path.dirname(outputPath), { recursive: true });
30525
+ await writeFile(outputPath, Buffer.from(result.imageData, 'base64'), requestedPath == null ? { flag: 'wx' } : undefined);
30526
+ return outputPath;
30527
+ }
30528
+
28345
30529
  /**
28346
30530
  * Copyright (c) Meta Platforms, Inc. and affiliates.
28347
30531
  *
@@ -28351,6 +30535,73 @@ function reportToolCall(toolName, success, durationMs, error, sessionId, clientV
28351
30535
  function isRecord$1(value) {
28352
30536
  return typeof value === 'object' && value !== null && !Array.isArray(value);
28353
30537
  }
30538
+ const MAX_ASSET_PREVIEW_MCP_NAMED_PARTS = 40;
30539
+ const MAX_ASSET_PREVIEW_MCP_WARNINGS = 24;
30540
+ const MAX_ASSET_PREVIEW_MCP_WARNINGS_PER_CODE = 3;
30541
+ function compactAssetPreviewMetadata(metadata) {
30542
+ if (!isRecord$1(metadata.diagnostics)) {
30543
+ return metadata;
30544
+ }
30545
+ const diagnostics = metadata.diagnostics;
30546
+ const namedPartRecords = Array.isArray(diagnostics.namedParts)
30547
+ ? diagnostics.namedParts.filter(isRecord$1)
30548
+ : null;
30549
+ const namedParts = (namedPartRecords ?? [])
30550
+ .slice(0, MAX_ASSET_PREVIEW_MCP_NAMED_PARTS)
30551
+ .map((part) => ({
30552
+ ...(typeof part.name === 'string' ? { name: part.name } : {}),
30553
+ ...(typeof part.path === 'string' ? { path: part.path } : {}),
30554
+ ...(typeof part.type === 'string' ? { type: part.type } : {}),
30555
+ }));
30556
+ const namedPartCount = typeof diagnostics.namedPartCount === 'number'
30557
+ ? diagnostics.namedPartCount
30558
+ : namedPartRecords?.length;
30559
+ const warningRecords = Array.isArray(diagnostics.warnings)
30560
+ ? diagnostics.warnings.filter(isRecord$1)
30561
+ : null;
30562
+ const warningCodeCounts = new Map();
30563
+ const warningSampleCounts = new Map();
30564
+ const warnings = [];
30565
+ for (const warning of warningRecords ?? []) {
30566
+ const code = typeof warning.code === 'string' ? warning.code : 'unknown_warning';
30567
+ warningCodeCounts.set(code, (warningCodeCounts.get(code) ?? 0) + 1);
30568
+ const sampledForCode = warningSampleCounts.get(code) ?? 0;
30569
+ if (warnings.length >= MAX_ASSET_PREVIEW_MCP_WARNINGS ||
30570
+ sampledForCode >= MAX_ASSET_PREVIEW_MCP_WARNINGS_PER_CODE) {
30571
+ continue;
30572
+ }
30573
+ warningSampleCounts.set(code, sampledForCode + 1);
30574
+ warnings.push({
30575
+ code,
30576
+ ...(typeof warning.message === 'string'
30577
+ ? { message: warning.message }
30578
+ : {}),
30579
+ ...(typeof warning.path === 'string' ? { path: warning.path } : {}),
30580
+ });
30581
+ }
30582
+ return {
30583
+ ...metadata,
30584
+ diagnostics: {
30585
+ ...diagnostics,
30586
+ ...(namedPartRecords == null
30587
+ ? {}
30588
+ : {
30589
+ namedPartsTruncated: diagnostics.namedPartsTruncated === true ||
30590
+ (namedPartCount ?? namedPartRecords.length) > namedParts.length,
30591
+ namedPartCount: namedPartCount ?? namedPartRecords.length,
30592
+ namedParts,
30593
+ }),
30594
+ ...(warningRecords == null
30595
+ ? {}
30596
+ : {
30597
+ warningCodeCounts: Object.fromEntries(warningCodeCounts),
30598
+ warningCount: warningRecords.length,
30599
+ warnings,
30600
+ warningsTruncated: warningRecords.length > warnings.length,
30601
+ }),
30602
+ },
30603
+ };
30604
+ }
28354
30605
  function createTabMetadataText(tabId, tabGeneration) {
28355
30606
  return {
28356
30607
  type: 'text',
@@ -28502,7 +30753,9 @@ async function startRuntimeMcpStdioServer({ serverName = 'iwsdk', version = '1.0
28502
30753
  runtimeSession: session,
28503
30754
  });
28504
30755
  reportToolCall(name, true, Date.now() - startTime, undefined, session.sessionId, version);
28505
- const normalizedResponse = name === 'xr_get_session_status'
30756
+ // Managed browser status would misdescribe a headset's session.
30757
+ const normalizedResponse = name === 'xr_get_session_status' &&
30758
+ command.target?.deviceClass !== 'physical'
28506
30759
  ? {
28507
30760
  ...rawResponse,
28508
30761
  result: withBrowserStatus$1(rawResponse.result ?? rawResponse, session),
@@ -28512,27 +30765,49 @@ async function startRuntimeMcpStdioServer({ serverName = 'iwsdk', version = '1.0
28512
30765
  if ((name === 'browser_screenshot' ||
28513
30766
  name === 'scene_screenshot' ||
28514
30767
  name === 'scene_render_file' ||
30768
+ name === 'asset_render_preview' ||
28515
30769
  name === 'ui_render_preview') &&
30770
+ isScreenshotResult(result)) {
30771
+ const screenshotPath = await saveScreenshot(result);
30772
+ const { imageData: _imageData, ...metadata } = result;
30773
+ const responseMetadata = name === 'asset_render_preview'
30774
+ ? compactAssetPreviewMetadata(metadata)
30775
+ : metadata;
30776
+ return tabTracker.processResponse({
30777
+ ...normalizedResponse,
30778
+ result: { ...responseMetadata, screenshotPath },
30779
+ });
30780
+ }
30781
+ if (name === 'browser_interact' &&
28516
30782
  isRecord$1(result) &&
28517
- typeof result.imageData === 'string' &&
28518
- typeof result.mimeType === 'string') {
28519
- const image = {
28520
- type: 'image',
28521
- data: result.imageData,
28522
- mimeType: result.mimeType,
30783
+ isRecord$1(result.failure) &&
30784
+ isRecord$1(result.failure.screenshot) &&
30785
+ typeof result.failure.screenshot.imageData === 'string') {
30786
+ const screenshot = result.failure.screenshot;
30787
+ const mimeType = typeof screenshot.mimeType === 'string'
30788
+ ? screenshot.mimeType
30789
+ : 'image/png';
30790
+ const sanitizedResult = {
30791
+ ...result,
30792
+ failure: {
30793
+ ...result.failure,
30794
+ screenshot: {
30795
+ captured: true,
30796
+ mimeType,
30797
+ },
30798
+ },
28523
30799
  };
28524
- if (name === 'scene_render_file') {
28525
- const { imageData: _imageData, ...metadata } = result;
28526
- const content = [
28527
- { type: 'text', text: JSON.stringify(metadata, null, 2) },
28528
- image,
28529
- ];
28530
- if (normalizedResponse._tabId != null) {
28531
- content.push(createTabMetadataText(normalizedResponse._tabId, normalizedResponse._tabGeneration));
28532
- }
28533
- return { content };
30800
+ const content = [
30801
+ { type: 'text', text: JSON.stringify(sanitizedResult, null, 2) },
30802
+ {
30803
+ type: 'image',
30804
+ data: screenshot.imageData,
30805
+ mimeType,
30806
+ },
30807
+ ];
30808
+ if (normalizedResponse._tabId != null) {
30809
+ content.push(createTabMetadataText(normalizedResponse._tabId, normalizedResponse._tabGeneration));
28534
30810
  }
28535
- const content = [image];
28536
30811
  return { content };
28537
30812
  }
28538
30813
  return tabTracker.processResponse(normalizedResponse);
@@ -28805,6 +31080,7 @@ function resolveRuntimeParams(operationName, options) {
28805
31080
  if (operationName === 'browser_screenshot' ||
28806
31081
  operationName === 'scene_screenshot' ||
28807
31082
  operationName === 'scene_render_file' ||
31083
+ operationName === 'asset_render_preview' ||
28808
31084
  operationName === 'ui_render_preview') {
28809
31085
  allowed.add('outputFile');
28810
31086
  }
@@ -28828,12 +31104,6 @@ function resolveRuntimeParams(operationName, options) {
28828
31104
  function isRecord(value) {
28829
31105
  return typeof value === 'object' && value !== null && !Array.isArray(value);
28830
31106
  }
28831
- function isScreenshotResult(value) {
28832
- return isRecord(value) && typeof value.imageData === 'string';
28833
- }
28834
- function isBrowserRelaunchedResult(value) {
28835
- return isRecord(value) && value.status === 'browser_relaunched';
28836
- }
28837
31107
  function withBrowserStatus(result, session) {
28838
31108
  const browser = session.browser ?? null;
28839
31109
  const browserConnected = Boolean(session.browser?.connected);
@@ -28853,13 +31123,26 @@ function withBrowserStatus(result, session) {
28853
31123
  browserCommandReady,
28854
31124
  };
28855
31125
  }
28856
- async function saveScreenshot(result, requestedPath) {
28857
- const outputPath = typeof requestedPath === 'string'
28858
- ? requestedPath
28859
- : path.join(os.tmpdir(), `iwsdk-screenshot-${Date.now()}.png`);
28860
- await mkdir(path.dirname(outputPath), { recursive: true });
28861
- await writeFile(outputPath, Buffer.from(result.imageData, 'base64'));
28862
- return outputPath;
31126
+ async function normalizeInteractionFailureScreenshot(result) {
31127
+ if (!isRecord(result) || !isRecord(result.failure)) {
31128
+ return result;
31129
+ }
31130
+ const screenshot = result.failure.screenshot;
31131
+ if (!isScreenshotResult(screenshot)) {
31132
+ return result;
31133
+ }
31134
+ const screenshotPath = await saveScreenshot(screenshot);
31135
+ return {
31136
+ ...result,
31137
+ failure: {
31138
+ ...result.failure,
31139
+ screenshot: {
31140
+ captured: true,
31141
+ mimeType: screenshot.mimeType ?? 'image/png',
31142
+ screenshotPath,
31143
+ },
31144
+ },
31145
+ };
28863
31146
  }
28864
31147
  async function handleRuntimeOperation(domain, action, options, io) {
28865
31148
  const operation = action
@@ -28891,10 +31174,6 @@ async function handleRuntimeOperation(domain, action, options, io) {
28891
31174
  let rawResult;
28892
31175
  try {
28893
31176
  rawResult = await sendRuntimeCommand(sendOptions);
28894
- if (operation.mcpName === 'browser_screenshot' &&
28895
- isBrowserRelaunchedResult(rawResult.result ?? rawResult)) {
28896
- rawResult = await sendRuntimeCommand(sendOptions);
28897
- }
28898
31177
  }
28899
31178
  catch (error) {
28900
31179
  if (operation.mcpName === 'xr_accept_session' &&
@@ -28903,12 +31182,18 @@ async function handleRuntimeOperation(domain, action, options, io) {
28903
31182
  }
28904
31183
  throw error;
28905
31184
  }
28906
- const result = operation.mcpName === 'xr_get_session_status'
31185
+ // Managed browser status would misdescribe a headset's session.
31186
+ let result = operation.mcpName === 'xr_get_session_status' &&
31187
+ command.target?.deviceClass !== 'physical'
28907
31188
  ? withBrowserStatus(rawResult.result ?? rawResult, session)
28908
31189
  : (rawResult.result ?? rawResult);
31190
+ if (operation.mcpName === 'browser_interact') {
31191
+ result = await normalizeInteractionFailureScreenshot(result);
31192
+ }
28909
31193
  const isScreenshotOperation = operation.mcpName === 'browser_screenshot' ||
28910
31194
  operation.mcpName === 'scene_screenshot' ||
28911
31195
  operation.mcpName === 'scene_render_file' ||
31196
+ operation.mcpName === 'asset_render_preview' ||
28912
31197
  operation.mcpName === 'ui_render_preview';
28913
31198
  const hasExplicitScreenshotPath = typeof options.outputFile === 'string';
28914
31199
  if (options.outputFile === true) {
@@ -28916,23 +31201,15 @@ async function handleRuntimeOperation(domain, action, options, io) {
28916
31201
  }
28917
31202
  // An explicit output path is an instruction to persist the PNG. Honor it
28918
31203
  // even when --raw is also present, instead of silently printing base64 and
28919
- // ignoring the requested file.
28920
31204
  if (isScreenshotOperation &&
28921
31205
  isScreenshotResult(result) &&
28922
31206
  (hasExplicitScreenshotPath || !options.raw)) {
28923
- const screenshotPath = await saveScreenshot(result, options.outputFile);
28924
- if (operation.mcpName === 'scene_render_file') {
28925
- const { imageData: _imageData, ...metadata } = result;
28926
- return createSuccess({
28927
- workspaceRoot,
28928
- operation: operation.id,
28929
- result: metadata,
28930
- screenshotPath,
28931
- });
28932
- }
31207
+ const screenshotPath = await saveScreenshot(result, typeof options.outputFile === 'string' ? options.outputFile : undefined);
31208
+ const { imageData: _imageData, ...metadata } = result;
28933
31209
  return createSuccess({
28934
31210
  workspaceRoot,
28935
31211
  operation: operation.id,
31212
+ ...(Object.keys(metadata).length > 0 ? { result: metadata } : {}),
28936
31213
  screenshotPath,
28937
31214
  });
28938
31215
  }
@@ -28978,6 +31255,12 @@ function formatSchemaPropertyLines(propertyPath, schema, required, indent = 2) {
28978
31255
  lines.push(...formatSchemaPropertyLines(`${propertyPath}.${name}`, nestedSchema, nestedRequired.has(name), indent + 2));
28979
31256
  }
28980
31257
  }
31258
+ if (schema.items?.properties) {
31259
+ const itemRequired = new Set(schema.items.required ?? []);
31260
+ for (const [name, itemSchema] of Object.entries(schema.items.properties)) {
31261
+ lines.push(...formatSchemaPropertyLines(`${propertyPath}[].${name}`, itemSchema, itemRequired.has(name), indent + 2));
31262
+ }
31263
+ }
28981
31264
  if (schema.items?.enum?.length) {
28982
31265
  lines.push(`${prefix} item values: ${schema.items.enum.join(', ')}`);
28983
31266
  }
@@ -29018,6 +31301,7 @@ function buildRuntimeCommandHelp(domain, action) {
29018
31301
  const writesScreenshot = operation.mcpName === 'browser_screenshot' ||
29019
31302
  operation.mcpName === 'scene_screenshot' ||
29020
31303
  operation.mcpName === 'scene_render_file' ||
31304
+ operation.mcpName === 'asset_render_preview' ||
29021
31305
  operation.mcpName === 'ui_render_preview';
29022
31306
  const lines = [
29023
31307
  `Usage: iwsdk ${domain} ${action} [--input-json <json>] [--timeout <ms>] [--raw]${writesScreenshot ? ' [--output-file <path>]' : ''}`,
@@ -29056,11 +31340,15 @@ function buildRuntimeDomainHelp(domain) {
29056
31340
  if (operations.length === 0) {
29057
31341
  return [`Unknown command group "${domain}".`];
29058
31342
  }
31343
+ const actions = operations.map((operation) => ` ${operation.action.padEnd(24)} ${operation.description}`);
31344
+ if (domain === 'browser') {
31345
+ actions.push(` ${'run'.padEnd(24)} Run trusted workspace Playwright code against the existing managed browser (requires explicit dev-server opt-in).`);
31346
+ }
29059
31347
  return [
29060
31348
  `Usage: iwsdk ${domain} <action>`,
29061
31349
  '',
29062
31350
  'Actions:',
29063
- ...operations.map((operation) => ` ${operation.action.padEnd(24)} ${operation.description}`),
31351
+ ...actions,
29064
31352
  '',
29065
31353
  `Run "iwsdk ${domain} <action> --help" for parameters.`,
29066
31354
  ];
@@ -29073,6 +31361,21 @@ function buildMcpInspectHelp() {
29073
31361
  ' --tool <mcpName> Show description and input schema for one runtime tool',
29074
31362
  ];
29075
31363
  }
31364
+ function buildBrowserRunHelp() {
31365
+ return [
31366
+ 'Usage: iwsdk browser run <workspace-script.mjs> [--timeout <ms>] [--workspace <path>]',
31367
+ '',
31368
+ 'Run trusted local Playwright code against the existing managed Chromium session.',
31369
+ 'Start the dev server with --allow-browser-automation first.',
31370
+ 'The script must stay inside the workspace and export a default function or named run function.',
31371
+ 'It receives { browser, context, page, frame, cdp, workspaceRoot }.',
31372
+ 'IWSDK owns the managed browser, context, and page; destructive close operations are blocked.',
31373
+ '',
31374
+ 'Options:',
31375
+ ' --timeout <ms> Script timeout. Defaults to 60000.',
31376
+ ' --workspace <path> Resolve a running IWSDK workspace explicitly.',
31377
+ ];
31378
+ }
29076
31379
  function buildReferenceCommandHelp(action) {
29077
31380
  if (action === 'status') {
29078
31381
  return [
@@ -29142,8 +31445,10 @@ function buildDevCommandHelp(action) {
29142
31445
  ' --headed Launch the managed browser headed (default)',
29143
31446
  ' --open Open the managed browser on startup (default)',
29144
31447
  ' --no-open Do not open the managed browser on startup',
31448
+ ' --native-xr-control Control native Quest WebXR through ADB-reversed localhost',
29145
31449
  ' --screenshot-width <pixels> Positive screenshot width; default behavior is 800px',
29146
31450
  ' --screenshot-height <pixels> Positive screenshot height; default behavior is 800px',
31451
+ ' --allow-browser-automation Enable the local same-session Playwright runner',
29147
31452
  ' --foreground Keep the package-manager process attached',
29148
31453
  ' --timeout <milliseconds> Runtime readiness timeout (default: 60000)',
29149
31454
  ' --workspace <path> Select an IWSDK application explicitly',
@@ -29168,12 +31473,14 @@ function usageLines() {
29168
31473
  'Commands:',
29169
31474
  ' status',
29170
31475
  ' dev up|restart [--ai-mode <mode>] [--headed|--headless] [--open|--no-open]',
31476
+ ' runtime status|targets|wait|recover|pair-headset',
29171
31477
  ' dev down|logs|open|status',
29172
31478
  ' adapter sync|status|prune|prompt',
29173
31479
  ' reference status|warmup|inspect|search|relationship|api|file|components|systems|dependents|examples',
29174
31480
  ' mcp stdio|inspect [--tool <mcpName>]',
29175
31481
  ' xr <action>',
29176
- ' browser <action>',
31482
+ ' browser <action>|run <script>',
31483
+ ' asset <action>',
29177
31484
  ' scene <action>',
29178
31485
  ' ui <action>',
29179
31486
  ' ecs <action>',
@@ -29191,7 +31498,7 @@ async function runCli(argv, io = {}) {
29191
31498
  const stderr = io.stderr ?? process.stderr;
29192
31499
  const cwd = io.cwd ?? process.cwd();
29193
31500
  const parsed = parseArgv(argv);
29194
- const [command, subcommand] = parsed.positionals;
31501
+ const [command, subcommand, argument] = parsed.positionals;
29195
31502
  const context = { stdout, stderr, cwd };
29196
31503
  try {
29197
31504
  let result;
@@ -29214,9 +31521,15 @@ async function runCli(argv, io = {}) {
29214
31521
  }
29215
31522
  if (command === 'xr' ||
29216
31523
  command === 'browser' ||
31524
+ command === 'asset' ||
29217
31525
  command === 'scene' ||
29218
31526
  command === 'ui' ||
29219
- command === 'ecs') {
31527
+ command === 'ecs' ||
31528
+ command === 'runtime') {
31529
+ if (command === 'browser' && subcommand === 'run') {
31530
+ stdout.write(`${buildBrowserRunHelp().join('\n')}\n`);
31531
+ return 0;
31532
+ }
29220
31533
  stdout.write(`${(subcommand
29221
31534
  ? buildRuntimeCommandHelp(command, subcommand)
29222
31535
  : buildRuntimeDomainHelp(command)).join('\n')}\n`);
@@ -29297,9 +31610,15 @@ async function runCli(argv, io = {}) {
29297
31610
  throw new Error('Usage: iwsdk mcp stdio|inspect');
29298
31611
  case 'xr':
29299
31612
  case 'browser':
31613
+ case 'asset':
29300
31614
  case 'scene':
29301
31615
  case 'ui':
29302
31616
  case 'ecs':
31617
+ case 'runtime':
31618
+ if (command === 'browser' && subcommand === 'run') {
31619
+ result = await handleBrowserRun(argument, parsed.options, context);
31620
+ break;
31621
+ }
29303
31622
  if (!subcommand) {
29304
31623
  throw new Error(buildRuntimeDomainHelp(command).join('\n'));
29305
31624
  }
@@ -29308,6 +31627,9 @@ async function runCli(argv, io = {}) {
29308
31627
  default:
29309
31628
  throw new Error(`Unknown command: ${command}`);
29310
31629
  }
31630
+ if (typeof result === 'number') {
31631
+ return result;
31632
+ }
29311
31633
  if (result) {
29312
31634
  if (isCliRawOutput(result)) {
29313
31635
  writeJson(stdout, result.value);
@@ -29328,7 +31650,11 @@ async function runCli(argv, io = {}) {
29328
31650
  cause: error.issueCause,
29329
31651
  browser: error.browser ?? null,
29330
31652
  })
29331
- : createFailure(error instanceof Error ? error.message : String(error));
31653
+ : error instanceof RuntimeOwnerError
31654
+ ? createFailure(error.message, error.code, {
31655
+ owner: error.owner,
31656
+ })
31657
+ : createFailure(error instanceof Error ? error.message : String(error));
29332
31658
  writeJson(stderr, failure);
29333
31659
  return 1;
29334
31660
  }